python-TCP模拟ftp文件传输
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python-TCP模拟ftp文件传输相关的知识,希望对你有一定的参考价值。
1 #!/usr/bin/python 2 #coding=utf-8 3 #server 4 from socket import* 5 import sys,os 6 def command(): 7 l=[ "Welcome!\n","command\n", "list\n","upload\n","download\n"] 8 return l 9 def list(): 10 l=[] 11 for filename in os.listdir(‘.‘): 12 l.append(filename) 13 return l 14 HOST="192.168.1.33" 15 PORT=5126 16 ADDR=(HOST,PORT) 17 sockob=socket(AF_INET,SOCK_STREAM) 18 sockob.bind(ADDR) 19 sockob.listen(5) 20 21 a=[] 22 while 1: 23 sock,addr=sockob.accept() 24 25 while 1: 26 data=sock.recv(1024) 27 str=data.split(" ") 28 29 if data =="command": 30 a=command() 31 for i in a: 32 sock.send(i) 33 elif data =="list": 34 a=list() 35 for i in a: 36 sock.send(i) 37 elif str[0]=="upload": 38 f=open(str[1],‘w‘) 39 s=sock.recv(1024) 40 print s 41 for i in s: #range(len(str)): 42 f.write(i) 43 print "upload is ok!" 44 elif str[0]=="download": 45 f=open(str[1],‘r‘) 46 s=f.readlines() 47 for i in s: 48 sock.send(i) 49 print "download is ok!" 50 sockob.close() 51 sock.close()
1 #!/usr/bin/python 2 #coding=utf-8 3 #client 4 from socket import * 5 import sys 6 7 HOST=‘192.168.1.33‘ 8 PORT=5126 9 ADDR=(HOST,PORT) 10 sockob=socket(AF_INET,SOCK_STREAM) 11 sockob.connect(ADDR) 12 13 while 1: 14 data=raw_input(">",) 15 str=data.split(‘ ‘) 16 if not str: 17 break 18 elif str[0]=="upload": 19 f=open(str[1],‘r‘) 20 sockob.send(data) 21 s0=f.readlines() 22 print s0 23 for i in s0: 24 sockob.send(i) 25 elif str[0]=="download": 26 f=open(str[1],‘w‘) 27 sockob.send(data) 28 s1=sockob.recv(1024) 29 f.write(s1) 30 elif data=="command" or data=="list": 31 sockob.send(data) 32 data=sockob.recv(1024) 33 print data 34 35 36 sockob.close()
以上是关于python-TCP模拟ftp文件传输的主要内容,如果未能解决你的问题,请参考以下文章