一.subprocess模块
在学习这个模块前,我们先用Python的help()函数查看一下subprocess模块是干嘛的:
即允许你去创建一个新的进程让其执行另外的程序,并与它进行通信,获取标准的输入、标准输出、标准错误以及返回码等。
subprocess模块中定义了一个Popen类,通过它可以来创建进程,并与其进行复杂的交互。
应用:
1 import subprocess 2 3 res=subprocess.Popen("ipconfig", 4 shell=True, 5 stderr=subprocess.PIPE, 6 stdout=subprocess.PIPE) 7 8 print(res.stdout.read().decode("gbk"))
简单应用
1 import socket 2 import subprocess 3 4 sever=socket.socket() 5 6 sever.bind(('192.168.13.137',8016)) 7 8 sever.listen(10) 9 10 while True: 11 print('服务器准备好了') 12 conn,addr=sever.accept() 13 14 while True: 15 try: 16 cmd=conn.recv(1024).decode('utf-8') 17 if cmd=='exit': 18 break 19 res=subprocess.Popen(cmd, 20 shell=True, 21 stderr=subprocess.PIPE, 22 stdout=subprocess.PIPE, 23 ) 24 out=res.stdout.read() 25 err = res.stderr.read() 26 if out: 27 conn.send(out) 28 29 else: 30 conn.send(err) 31 32 except Exception as e: 33 break 34 conn.close()
1 import socket 2 client=socket.socket() 3 client.connect(('192.168.13.137',8016)) 4 while True: 5 cmd=input('请输入命令:') 6 if cmd=='exit': 7 client.send(cmd.encode('utf-8')) 8 break 9 client.send(cmd.encode('utf-8')) 10 ret=client.recv(1024) 11 print(ret.decode('gbk'))
二.黏包
1..struct模块
1 import struct 2 res=struct.pack('i',12535353) #压包 3 print(res) 4 print(len(res)) 5 ret=struct.unpack('i',res) #解包 6 print(ret[0])
实例:
1 import socket 2 import subprocess 3 4 sever=socket.socket() 5 6 sever.bind(('192.168.13.137',8016)) 7 8 sever.listen(10) 9 10 while True: 11 print('服务器准备好了') 12 conn,addr=sever.accept() 13 14 while True: 15 try: 16 cmd=conn.recv(1024).decode('utf-8') 17 if cmd=='exit': 18 break 19 res=subprocess.Popen(cmd, 20 shell=True, 21 stderr=subprocess.PIPE, 22 stdout=subprocess.PIPE, 23 ) 24 out=res.stdout.read() 25 err = res.stderr.read() 26 if out: 27 import struct 28 header_pack = struct.pack('i', len(out)) 29 # 发送报头 30 conn.send(header_pack) 31 # 发送数据 32 conn.send(out) 33 34 else: 35 # 构建报头数据 36 import struct 37 header_pack=struct.pack('i',len(err)) 38 # 发送报头 39 conn.send(header_pack) 40 # 发送数据 41 conn.send(err) 42 43 except Exception as e: 44 break 45 conn.close()
1 import socket 2 import struct 3 client=socket.socket() 4 client.connect(('192.168.13.137',8016)) 5 while True: 6 cmd=input('请输入命令:') 7 if cmd=='exit': 8 client.send(cmd.encode('utf-8')) 9 break 10 client.send(cmd.encode('utf-8')) 11 header_pack=client.recv(4) 12 data_length=struct.unpack('i',header_pack) 13 14 recv_data_length=0 15 total_size=b'' 16 while recv_data_length<data_length[0]: 17 data=client.recv(1024) 18 recv_data_length+=len(data) 19 total_size+=data 20 print(total_size.decode('gbk'))
2.hashlib模块
1 import hashlib 2 md5=hashlib.md5() 3 md5.update(b'sd') 4 md5.update(b'ghjk') #追加上传,不是覆盖 5 print(md5.hexdigest())
1 import hashlib 2 md5=hashlib.sha3_512() #加密效果更好 3 md5.update(b'sd') 4 md5.update(b'ghjk') 5 print(md5.hexdigest()) 6 7 import hashlib 8 md5=hashlib.sha3_256() #加密效果更好 9 md5.update(b'sd') 10 md5.update(b'ghjk') 11 print(md5.hexdigest())