一. struct 变成固定字节长度的数字
import struct # ii 可接收两个数字参数 i 接收一个数字参数
def packI_scope(mode, num, plus):#mode="i" int固定4个字节的长度
while True:
try:
num = num + plus
p = struct.pack(mode, num)
u = struct.unpack(mode, p)
print(p, len(p), str(num), len(str(num)), u, u[0])
except:
if plus > 0:
print("最大整数值=", num - plus,"\n")
else:
print("最小整数值=", num - plus,"\n")
break
if __name__ == '__main__':
print(-pow(2,4*8-1),pow(2,31)-1,"\n")
packI_scope("i", num=2147483640, plus=1)
packI_scope("i", num=-2147483640, plus=-1)
p0 = struct.pack("i", 0)
u0 = struct.unpack("i", p0)
print("[0]也是四个字节=",p0, u0)
print(5+-1,-1+5)
import struct
def structPackII(num1, num2): #int int 固定8个字节
p = struct.pack("ii", num1, num2)
u = struct.unpack("ii", p)
print(p, len(p), u)
if __name__ == '__main__':
structPackII(0, 0)
structPackII(-2147483648, -2147483648)
structPackII(2147483647, 2147483647)
structPackII(2147483647, -2147483648)
structPackII(-2147483648, 2147483647)
import struct
dataTypes = ["i", "ii", "f", "ff", "s", "ss", "d", "dd"]
for t in dataTypes:
print("{:<2} 长度length: {}".format(t, struct.calcsize(t)))
f0=struct.pack("f",3.14)
print(struct.unpack("f",f0),len(f0))
二.hashlib md5
import hashlib
m=hashlib.md5()
m.update( "123456".encode("utf-8") )
print(m.hexdigest())
print( hashlib.md5( "123456".encode("UTF-8") ).hexdigest() )
m1=hashlib.md5( "12".encode("Utf-8") )
m1.update( "345".encode("uTF-8") )
m1.update( "6".encode("uTF-8") )
print(m1.hexdigest()) # 此处才计算 十六进制 md5值
三.subprocess.Popen
import subprocess
def cmd(command):
obj0 = subprocess.Popen("echo %cd%", shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
present_working_directory=obj0.stdout.read().decode("gbk").strip()
obj=subprocess.Popen(command,shell=True,
stdout=subprocess.PIPE,stderr=subprocess.PIPE)
cmd_res_stdout, cmd_res_stderr = obj.stdout.read(), obj.stderr.read()
print("[1]",cmd_res_stdout)
print("[2]",cmd_res_stderr)
print("[3] {}> {}".format(present_working_directory,command))
print(cmd_res_stdout.decode("gbk"))
if __name__ == '__main__':
cmd("ipconfig /all")
四.json
import json,hashlib
header_dic={ "filename":"a.txt", }
header_dic.update( md5=hashlib.md5("123456".encode("utf8")).hexdigest() )
header_dic["total_size"]= len( "123456".encode("utf8") )
print( header_dic,type(header_dic),"\t单引号=字典" )
header_json=json.dumps( header_dic )
print( header_json, type(header_json),"\t双引号=json序列化为字符串")
h_dic=json.loads(header_json)
print( h_dic, type(h_dic),"\t反序列化为字典" )
Server发送前4字节(头部长度)+发送头部+主体信息
import hashlib,json,socket,struct,subprocess # 先运行服务器a1.py程序
import multiprocessing,threading
import time
ADDR= (HOST,PORT) ="127.0.0.1",9999
class ServerTCPcmd:
def __init__(self):
self.server=get_tcp_server()
print("服务器已启动..")
def runCmd(self):
while True:
conn,client_addr=self.server.accept()
print(client_addr,conn)
#handle_client_cmd(conn) #不能同时接受客户端服务
#receive_thread = threading.Thread(target=handle_client_cmd, args=(conn,))
#receive_thread.start() # 多线程方法 多进程方法
process=multiprocessing.Process(target=handle_client_cmd,args=(conn,))
process.start() #同时接受多个客户端服务,超出最大连接数的客户端只能等待
def get_tcp_server( server_address=ADDR ):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind( server_address )
server.listen(5)
return server
def handle_client_cmd(client_conn:socket.socket):
# 指明client_conn类型 代码将有提示
while True:
try:
cmd=step1_receive_client_commands(client_conn)
if not cmd:
break #出现情形 客户端已经断开了
print(f"[{time.strftime('%Y-%m-%d %X')}]接收remote_client_cmd:", cmd)
cmd_res_bytes=step2_execute_cmd(cmd)
step3_send(cmd, cmd_res_bytes, client_conn)
except ConnectionResetError:
break
client_conn.close()
def step1_receive_client_commands( conn:socket.socket ):
cmd = conn.recv(1024).decode().strip()
return cmd
def step2_execute_cmd(cmd:str):
obj = subprocess.Popen(
cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
return obj.stdout.read() + obj.stderr.read()
def step3_send(cmd:str, cmd_res_bytes:bytes, conn):
header_dic={
"client_cmd" : cmd,
"cmd_res_md5" : hashlib.md5( cmd_res_bytes ).hexdigest(),
"cmd_res_bytes_lenth" : len( cmd_res_bytes ),
}
header_json=json.dumps( header_dic )
header_bytes=header_json.encode("gbk")
header_len=struct.pack("i",len(header_bytes))
conn.send( header_len )
conn.send( header_bytes + cmd_res_bytes )
if __name__ == '__main__':
ServerTCPcmd().runCmd()
Client.py
import socket, struct, json, hashlib, sys # a2.py(pycharm 打开多个a2.py)
class ClientTCPcmd:
def __init__(self):
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self.client.connect( ("localhost", 9999) )
print("连接服务器成功",self.client.getpeername(),self.client.getsockname())
except:
print("服务器已断开无法连接(程序将退出)")
sys.exit()
def CmdSend(self):
while True:
if self.step1_send_cmd()==-1:
break
self.step2_receive_server_result()
self.client.close()
def step1_send_cmd(self):
print("【0】请输入WindowsCMD(输exit退出客户端程序)..")
cmd = input(">> ").strip().encode("utf8")
if not cmd:
self.step1_send_cmd() #相当于循环 continue
if cmd.decode() in ["exit", "bye", "quit"]:
return -1
self.client.send(cmd)
return 0
def step2_receive_server_result(self):
rec_header_len = struct.unpack("i", self.client.recv(4) )[0]
print("【1】获取服务器头部信息长度", rec_header_len)
rec_header_bytes = self.client.recv(rec_header_len)
rec_header_dict = json.loads( rec_header_bytes.decode("gbk") )
print("【2】获取服务端的头部信息内容", rec_header_dict)
recv_data_size, recv_data = 0, b""
while recv_data_size < rec_header_dict["cmd_res_bytes_lenth"]:
#recv_size=数据长度 时退出循环
res=self.client.recv(1024)
recv_data += res
recv_data_size += len(res)
print("【3】获取服务器执行cmd结果的数据长度", recv_data_size, len(recv_data))
# 4.获取服务器发来的文件名称/md5
client_cmd=rec_header_dict["client_cmd"]
cmd_res_md5 = rec_header_dict["cmd_res_md5"]
display_data = recv_data.decode("gbk")
print(display_data)
# 5.对比发送的数据与接收数据的md5
md5 = hashlib.md5( recv_data ).hexdigest()
print(cmd_res_md5 == md5, md5, client_cmd, "\n")
if __name__ == '__main__':
ClientTCPcmd().CmdSend()
#dir ipconfig 或ipconfig /all 或 ping www.baidu.com