简易的两台机器拷贝文件:
server端:
#!/usr/bin/python
import socket
import sys
import os
def filesplit(filename):
filesp = os.path.dirname(filename)
filespdir = "/root/tmp" + filesp
filespbase = "/root/tmp" + filename
return filespdir,filespbase
def makedir(dir):
if os.path.exists(dir):
return None
else:
dirname = os.path.dirname(dir)
if os.path.exists(dirname):
os.path.mkdir(dir)
else:
makedir(dirname)
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server_address = ('192.168.1.100',10000)
print >>sys.stderr,'starting up on %s port %s' % server_address
sock.bind(server_address)
sock.listen(10)
while True:
print >>sys.stderr,'waiting for a connection'
connection,client_address = sock.accept()
try :
print >>sys.stderr,'connection from',client_address
file = connection.recv(100)
filedir,filebase = filesplit(file)
makedir(filedir)
filecre = open(filebase,"w")
connection.sendall("start")
while True:
data = connection.recv(2048)
if len(data) > 0:
filecre.write(data)
else:
break
filecre.close()
finally:
connection.close()
客户端:
#!/usr/bin/python
import sys
import socket
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server_address = ('192.168.1.100',10000)
print >>sys.stderr,'connection to %s port %s' % server_address
try:
sock.connect(server_address)
except socket.error:
print >>sys.stderr,"connection to this server failued"
sys.exit(1)
file = raw_input("please input your filepath: ").rstrip()
try:
fd = open(file,"r")
except IOError:
print >>sys.stderr,"open %s failued" % file
sys.exit(1)
sock.sendall(file)
data = sock.recv(5)
if data == "start":
print >>sys.stderr,'start put file "%s"' % file
try :
while True:
put_line = fd.read(2048)
if len(put_line) > 0:
sock.sendall(put_line)
else:
print "put % success" % file
break
finally:
sock.close()
else :
print "put file %s failure" % file
sys.exit(255)
阅读(1782) | 评论(0) | 转发(0) |