一. 模拟ssh
# ===================================== 服务器端 ===================================== import socket import subprocess # 系统操作 server = socket.socket() server.bind(('127.0.0.1',8008)) server.listen(5) while True: print("server is working.....") conn,addr = server.accept() # 字节类型 while True: # 针对window系统 try: cmd = conn.recv(1024).decode("utf8") # 阻塞 if cmd == b'exit': break res=subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE, ) # print("stdout",res.stdout.read()) # print("stderr",res.stderr.read().decode("gbk")) out=res.stdout.read() err=res.stderr.read() print("out响应长度",len(out)) print("err响应长度",len(err)) if err: import struct header_pack = struct.pack("i", len(err)) conn.send(header_pack) conn.send(err) else: #构建报头 import struct header_pack=struct.pack("i",len(out)) print("header_pack",header_pack) # # 发送报头 conn.send(str(len(out)).encode("utf8")) # 发送数据 conn.send(out) except Exception as e: break conn.close() # ===================================== 客户端 ===================================== import socket import struct sk = socket.socket() sk.connect(('127.0.0.1', 8008)) while 1: cmd = input("请输入命令:") sk.send(cmd.encode('utf-8')) # 字节 if cmd == "": # 空字符串无法发送 continue if cmd == 'exit': break header_pack = sk.recv(4) data_length = struct.unpack("i", header_pack)[0] # unpack是一个元组 print("data_length", data_length) data_length = int(sk.recv(1024).decode("utf8")) print("data_length", data_length) recv_data_length = 0 recv_data = b"" while recv_data_length < data_length: data = sk.recv(1024) recv_data_length += len(data) recv_data += data print(recv_data.decode("gbk")) sk.close()
二. hashlib模块
import hashlib md5=hashlib.md5() md5.update(b"hello") md5.update(b"yuan") print(md5.hexdigest()) print(len(md5.hexdigest())) #helloyuan: d843cc930aa76f7799bba1780f578439 # d843cc930aa76f7799bba1780f578439 # 多次update和单次update结果一样 ############################################# md5=hashlib.md5() with open("ssh_client.py","rb") as f: for line in f: md5.update(line) # 多次update和单次update结果一样 print(md5.hexdigest()) # f.read()
三. struct模块
import struct res=struct.pack("i",2934781) print(res) print(len(res)) obj=struct.unpack("i",res) print(obj[0])
四. subprocess模块 # windows系统明命令
import subprocess res=subprocess.Popen("dir", shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE) print(res.stdout.read().decode("gbk"))