python基础之socket编程(二)

ssh远程执行命令:

思路分析:

客户端给服务端发送命令,服务端返回一个输出结果传给客户端.

#coding:utf-8
#买手机
import socket
import struct
import json
import subprocess
phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#绑定电话卡
ip_port=('192.168.16.114',8081)
phone.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
phone.bind(ip_port)
#开机
phone.listen(5)
#等待电话 #链接循环
while True:
conn,addr=phone.accept()
print('client addr',addr)
#通讯循环
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', 8080)
ip_port = ('192.168.16.114', 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)
print(head_dic)
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()

客户端

上一篇:Python 基础之socket编程(一)


下一篇:canvas雪花