python socket模块之python模拟scp

发布时间:2020-03-21编辑:脚本学堂
本文介绍下python模块中的socket模块,模拟下scp命令的实现,有需要的朋友参考下。

python中用socket模块模拟slinuxjishu/13998.html target=_blank class=infotextkey>cp命令的实现两台机器拷贝文件:

1,python socket模块实现的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()

2,python socket模块实现的客户端:
 

复制代码 代码示例:

#!/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)