1.客户端和服务端ssh
import socket,struct import subprocess phone = socket.socket( socket.AF_INET , socket.SOCK_STREAM ) phone.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) phone.bind(( '127.0.0.1', 8090 )) phone.listen(5) while True: conn,addr = phone.accept() while True: try: cmd = conn.recv(1024) if not cmd:continue res = subprocess.Popen(cmd.decode('utf-8'), shell = True , stdout= subprocess.PIPE , stderr= subprocess.PIPE ) out_data = res.stdout.read() error_data = res.stderr.read() data_size = len(out_data) + len(error_data) conn.send(struct.pack("i",data_size)) conn.send(out_data) conn.send(error_data) except Exception: break conn.close() phone.close()
import socket,struct phone = socket.socket(socket.AF_INET , socket.SOCK_STREAM) phone.connect(('127.0.0.1' , 8090)) while True: cmd = input('input cmd:').strip() if not cmd: continue phone.send(bytes(cmd,encoding='utf-8')) baotou = phone.recv(4) data_size = struct.unpack("i",baotou)[0] recive_data = b"" recive_size = 0 while recive_size < data_size: data = phone.recv(1024) recive_size += len(data) recive_data += data print(recive_data.decode("utf-8")) phone.close()
2.发送报头长度 报头 数据 ssh
#coding:utf-8 import socket import struct import json import subprocess phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) ip_port=('127.0.0.1',8081) phone.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) phone.bind(ip_port) phone.listen(100) #链接循环 while True: conn,addr=phone.accept() #通讯循环 while True: try: cmd=conn.recv(1024) res=subprocess.Popen(cmd.decode('utf-8'), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out_res=res.stdout.read() err_res=res.stderr.read() data_size=len(out_res)+len(err_res) head_dic={'data_size':data_size} head_json=json.dumps(head_dic) head_bytes=head_json.encode('utf-8') #part1:先发报头的长度 head_len=len(head_bytes) conn.send(struct.pack('i',head_len)) #part2:再发送报头 conn.send(head_bytes) #part3:最后发送数据部分 conn.send(out_res) conn.send(err_res) except Exception: break conn.close() phone.close()
import socket import struct import json phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ip_port = ('127.0.0.1', 8081) phone.connect(ip_port) while True: cmd = input('>>: ').strip() if not cmd: continue phone.send(bytes(cmd, encoding='utf-8')) # part1:先收报头的长度 head_struct=phone.recv(4) head_len=struct.unpack('i',head_struct)[0] # part2:再收报头 head_bytes=phone.recv(head_len) head_json=head_bytes.decode('utf-8') head_dic=json.loads(head_json) data_size = head_dic['data_size'] #part3:收数据 recv_size = 0 recv_data = b'' while recv_size < data_size: data = phone.recv(1024) recv_size += len(data) recv_data += data print(recv_data.decode('utf-8')) phone.close()
3. FTP
import socket,json,os,struct,subprocess class Ftp_Server: sock_famiy = socket.AF_INET sock_type = socket.SOCK_STREAM allow_reuse_address = False request_queue_size = 100 max_package_size = 1024 coding = "utf-8" server_dir = '/Users/centos/PycharmProjects/py_fullstack_s4/day35/file_upload' def __init__(self,server_addr,bind_active=True): self.server_addr=server_addr self.socket = socket.socket(self.sock_famiy,self.sock_type) if bind_active: try: self.server_bind() except Exception: self.server_close() def server_bind(self): if self.allow_reuse_address: self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(self.server_addr) self.socket.listen(self.request_queue_size) def get_request(self): return self.socket.accept() def server_close(self): self.socket.close() def run(self): while True: self.conn,self.client_addr = self.get_request() while True: try: head_struck = self.conn.recv(4) if not head_struck:break head_len = struct.unpack("i",head_struck)[0] head_json = self.conn.recv(head_len).decode(self.coding) head_dic = json.loads(head_json) cmd = head_dic["cmd"] if hasattr(self,cmd): func = getattr(self,cmd) func(head_dic) except Exception: break def put(self,args): filepath = os.path.join(self.server_dir,args["filename"]) filesize = args["filesize"] recv_size = 0 with open(filepath,"wb") as f: while recv_size < filesize: recv_data = self.conn.recv(self.max_package_size) f.write(recv_data) recv_size += len(recv_data) print('recvsize:%s filesize:%s' % (recv_size, filesize)) def get(self,args): filepath = os.path.join(self.server_dir,args["filename"]) filename = args["filename"] filesize = os.path.getsize(filepath) head_dict={"filename":os.path.basename(filepath),"filesize":filesize} print(head_dict) head_json=json.dumps(head_dict) head_json_bates=bytes(head_json,encoding=self.coding) head_struck=struct.pack("i",len(head_json_bates)) self.conn.send(head_struck) self.conn.send(head_json_bates) with open(filepath,"rb") as f: for i in f: self.conn.send(i) obj = Ftp_Server(("127.0.0.1",9020)) obj.run()
import socket,json,os,struct class Ftpclient: address_family = socket.AF_INET socket_type = socket.SOCK_STREAM allow_reuse_address = False max_packet_size = 1024 coding = "utf-8" request_queue_size = 100 server_dir = "/Users/centos/PycharmProjects/py_fullstack_s4/day37/file_upload" def __init__(self,server_address,connect=True): self.server_address=server_address self.socket=socket.socket(self.address_family,self.socket_type) if connect: try: self.client_connect() except Exception: self.client_clode() def client_connect(self): self.socket.connect(self.server_address) def client_close(self): self.socket.close() def run(self): while True: inp = input(">>: ").strip() if not inp:continue l= inp.split() cmd=l[0] if hasattr(self,cmd): func=getattr(self,cmd) func(l) def put(self,arg): cmd=arg[0] filename=arg[1] filesize=os.path.getsize(filename) head_dict={"cmd":cmd,"filename":os.path.basename(filename),"filesize":filesize} head_json=json.dumps(head_dict) head_json_bates=bytes(head_json,encoding=self.coding) head_struck=struct.pack("i",len(head_json_bates)) self.socket.send(head_struck) self.socket.send(head_json_bates) send_size=0 with open(filename,"rb") as f: for line in f: self.socket.send(line) send_size+=len(line) print(send_size) else: print("upload successful") def get(self,args): cmd = args[0] filename = args[1] filesize = len(args) head_dict={"cmd":cmd,"filename":os.path.basename(filename),"filesize":filesize} head_json=json.dumps(head_dict) head_json_bates=bytes(head_json,encoding=self.coding) head_struck=struct.pack("i",len(head_json_bates)) self.socket.send(head_struck) self.socket.send(head_json_bates) filepath = os.path.join(self.server_dir,filename) while True: try: head_struck = self.socket.recv(4) head_len = struct.unpack("i", head_struck)[0] head_json = self.socket.recv(head_len).decode(self.coding) head_dic = json.loads(head_json) print(head_dict) recv_size = 0 print(filepath) with open(filepath,"wb") as f: while recv_size < head_dic["filesize"]: data = self.socket.recv(self.max_packet_size) f.write(data) recv_size += len(data) except Exception: break obj = Ftpclient(("127.0.0.1",9020)) obj.run()
2. socketserver
基于tcp的套接字,关键就是两个循环,一个链接循环,一个通信循环
socketserver模块中分两大类:server类(解决链接问题)
request类(解决通信问题)
server类
request类
继承关系:
import socketserver,json,os,struct,subprocess class Ftp_Server(socketserver.BaseRequestHandler): request_queue_size = 100 max_package_size = 1024 coding = "utf-8" server_dir = '/Users/centos/PycharmProjects/py_fullstack_s4/day35/file_upload' def handle(self): while True: try: head_struck = self.request.recv(4) if not head_struck:break head_len = struct.unpack("i",head_struck)[0] head_json = self.request.recv(head_len).decode(self.coding) head_dic = json.loads(head_json) cmd = head_dic["cmd"] if hasattr(self,cmd): func = getattr(self,cmd) func(head_dic) except Exception: break def put(self,args): filepath = os.path.join(self.server_dir,args["filename"]) filesize = args["filesize"] recv_size = 0 with open(filepath,"wb") as f: while recv_size < filesize: recv_data = self.request.recv(self.max_package_size) f.write(recv_data) recv_size += len(recv_data) print('recvsize:%s filesize:%s' % (recv_size, filesize)) def get(self,args): filepath = os.path.join(self.server_dir,args["filename"]) filename = args["filename"] filesize = os.path.getsize(filepath) head_dict={"filename":os.path.basename(filepath),"filesize":filesize} print(head_dict) head_json=json.dumps(head_dict) head_json_bates=bytes(head_json,encoding=self.coding) head_struck=struct.pack("i",len(head_json_bates)) self.request.send(head_struck) self.request.send(head_json_bates) with open(filepath,"rb") as f: for i in f: self.request.send(i) obj = socketserver.ThreadingTCPServer(("127.0.0.1",9000),Ftp_Server) obj.serve_forever()
import socket,json,os,struct class Ftpclient: address_family = socket.AF_INET socket_type = socket.SOCK_STREAM allow_reuse_address = False max_packet_size = 1024 coding = "utf-8" request_queue_size = 100 server_dir = "/Users/centos/PycharmProjects/py_fullstack_s4/day37/file_upload" def __init__(self,server_address,connect=True): self.server_address=server_address self.socket=socket.socket(self.address_family,self.socket_type) if connect: try: self.client_connect() except Exception: self.client_clode() def client_connect(self): self.socket.connect(self.server_address) def client_close(self): self.socket.close() def run(self): while True: inp = input(">>: ").strip() if not inp:continue l= inp.split() cmd=l[0] if hasattr(self,cmd): func=getattr(self,cmd) func(l) def put(self,arg): cmd=arg[0] filename=arg[1] filesize=os.path.getsize(filename) head_dict={"cmd":cmd,"filename":os.path.basename(filename),"filesize":filesize} head_json=json.dumps(head_dict) head_json_bates=bytes(head_json,encoding=self.coding) head_struck=struct.pack("i",len(head_json_bates)) self.socket.send(head_struck) self.socket.send(head_json_bates) send_size=0 with open(filename,"rb") as f: for line in f: self.socket.send(line) send_size+=len(line) print(send_size) else: print("upload successful") def get(self,args): cmd = args[0] filename = args[1] filesize = len(args) head_dict={"cmd":cmd,"filename":os.path.basename(filename),"filesize":filesize} head_json=json.dumps(head_dict) head_json_bates=bytes(head_json,encoding=self.coding) head_struck=struct.pack("i",len(head_json_bates)) self.socket.send(head_struck) self.socket.send(head_json_bates) filepath = os.path.join(self.server_dir,filename) while True: try: head_struck = self.socket.recv(4) head_len = struct.unpack("i", head_struck)[0] head_json = self.socket.recv(head_len).decode(self.coding) head_dic = json.loads(head_json) print(head_dict) recv_size = 0 print(filepath) with open(filepath,"wb") as f: while recv_size < head_dic["filesize"]: data = self.socket.recv(self.max_packet_size) f.write(data) recv_size += len(data) except Exception: break obj = Ftpclient(("127.0.0.1",9000)) obj.run()