server
import socket,os,time
server=socket.socket()
server.bind((
'localhost',9999))
server.listen()

while True:
    conn,addr=server.accept()
   
print("new connect:",addr)
   
while True:
       
print("等待新指令")
        data=conn.recv(
1024)
       
if not data:
           
print("客户端已经断开")
           
break
       
print("执行指令:",data)
        cmd_res=os.popen(data.decode()).read()
#接收字符串,执行结果过也是字符串
       
print("before send:",len(cmd_res))
       
if len(cmd_res)==0:
            cmd_res=
"cmd has no out put..."
       
conn.send(str(len(cmd_res.encode())).encode("utf-8")) #先发大小给客户端 cmd_res先编码成bytes,在判断bytes len长度,len长度不能直接encode,需要先转成字符串str,字符串在编码成byte发送

       
client_ack=conn.recv(1024) #wait client to confirm 用于消除socket数据粘包
       
print("ack from client:",client_ack.decode())

        conn.send(cmd_res.encode(
"utf-8")) #汉字转bytes类型要用encode
       
print("send done")
server.close()
 
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_size=client.recv(
1024) #接收命令结果的长度
   
print("命令结果过大小:",cmd_res_size)

    client.send(
"客户端已准备接收数据...".encode("utf-8")) #对应server端的 client_ack汉字转成byte类型用 encode

   
received_size=0
   
received_data=b''
   
while received_size < int(cmd_res_size.decode()): #实际收到的数据小于命令执行的结果(实际发送的数据)就不断收,直到数据收完
       
data=client.recv(1024)
        received_size +=
len(data) #每次收到的有可能小于1024,所以必须用len判断
        #print(data.decode())
       
received_data +=data
       
# print(received_size)
   
else:                        #received_size < int(cmd_res_size.decode())不成立时执行else,即数据收完了执行else
       
print("cmd res receive done...",received_size)
       
print(received_data.decode())
client.close()
 
linux后台运行python脚本 -u参数才能打印日志
nohup python3 -u sock_ssh_server.py >py_run.log
2>1 &
自动拉起 sh脚本

#!/bin/sh
source ~/.bash_profile
 ps -ef|grep -v grep|grep '/usr/local/bin/python3 -u /root/sock_ssh_server.py' > /dev/null 2>&1

if [ $? -eq 0 ]
then
        echo `date`"------python脚本正在运行" >> ~/result.log
else
         nohup /usr/local/bin/python3 -u ~/sock_ssh_server.py > ~/py_run.log 2>1 &
fi