Chinaunix首页 | 论坛 | 博客
  • 博客访问: 915354
  • 博文数量: 75
  • 博客积分: 1216
  • 博客等级: 少尉
  • 技术积分: 1998
  • 用 户 组: 普通用户
  • 注册时间: 2012-08-11 16:20
个人简介

优秀是一种习惯

文章分类

全部博文(75)

文章存档

2014年(1)

2013年(29)

2012年(45)

分类: Python/Ruby

2012-12-22 14:21:15

简易的两台机器拷贝文件:
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)

阅读(1775) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~