码迷,mamicode.com
首页 > 其他好文 > 详细

使用 Socket 实现 FTP Server

时间:2018-01-03 11:50:54      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:net   popen   root   soc   localhost   listen   ted   port   with   

使用 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

[root@localhost ~]# 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()
[root@localhost ~]# 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

标签:net   popen   root   soc   localhost   listen   ted   port   with   

原文地址:https://www.cnblogs.com/pzk7788/p/8182014.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!