socket使用实例
# socket_server_ssh: 服务端
import socket, os
server = socket.socket()
server.bind(('localhost', 9999))
server.listen()
while True:
conn, addr =server.accept()
print("new conn:", addr)
while True:
data =conn.recv(1024)
print("服务已启动")
if not data:
print('客户端已断开')
break
print('执行指令:', data)
cmd_res = os.popen(data.decode()).read()
conn.send(cmd_res.encode("utf-8"))
server.close()
# socket_server_client: 客户端
import socket
client = socket.socket()
client.connect(('localhost', 9999))
while True:
cmd = input(">>:").strip()
if len(cmd) == 0: continue
client.send(cmd.encode("utf-8"))
cmd_res = client.recv(1024)
print(cmd_res.decode("utf-8"))