使用 Socket 实现 FTP Server

Posted pzk7788

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用 Socket 实现 FTP Server相关的知识,希望对你有一定的参考价值。

使用 Socket 实现 FTP Server ,实现如下功能:

get  /tmp/1.txt  /tmp/1.txt :把服务端 /tmp/1.txt 下载到客户端 /tmp/1.txt
put  /tmp/1.txt  /tmp/1.txt :把客户端 /tmp/1.txt 上传到服务端 /tmp/1.txt

[[email protected] ~]# cat ftp_server.py 
#!/usr/bin/env python
#-*- coding: utf8 -*-

import socket
from subprocess import Popen, PIPE

HOST = ‘‘
PORT = 1234
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print conn, conn
print Connected by, addr
while 1:
    cmd = conn.recv(1024)
    cmd_list = cmd.split()
    if cmd_list[0] == get:
        with open(cmd_list[1]) as fd:
            while True:
                data = fd.read(1024)
                conn.sendall(data)
                if not data:
                    conn.sendall(EOF)
                    break
    if not cmd: break
conn.close()
[[email protected] ~]# cat ftp_client.py 
#!/usr/bin/env python
#-*- coding:utf-8 -*-

import os
import sys
import tab
import socket

HOST = 192.168.5.131
PORT = 1234
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
while True:
    cmd = raw_input("Please input cmd: ").strip()
    if cmd.lower()== exit or cmd.lower() == quit:
        break
    cmd_list = cmd.split()
    if len(cmd_list) != 3:
        print "Ex: get file1 file2"
        continue
    else:
        s.sendall(cmd)
        if not os.path.exists(cmd_list[2]):
            dst_file = cmd_list[2]
        else:
            dst_file = cmd_list[2]+.new
        n = 1
        while True:
            data_rev = s.recv(1024)
            if data_rev.endswith(EOF):
                data = data_rev[:-3]
            else:
                data = data_rev
            if n == 1:
                with open(dst_file, wb) as fd:
                    fd.write(data) 
            else:
                with open(dst_file, a) as fd:
                    fd.write(data)
            n += 1
            if data_rev[-3:] == EOF:
                print "Success! destination file is %s" % dst_file
                break
s.close()

 

以上是关于使用 Socket 实现 FTP Server的主要内容,如果未能解决你的问题,请参考以下文章

socket实现的简单的ftp服务

实现简单socket的ftp功能

socket&socket实现ftp的get方法socketserver

FTP使用Socket编程

FTP Proxy Server

ftp实现终端start,并且反射型命令分发