day08_04 sock_server_ssh

sock_server_ssh.py

__author__ = "Alex Li"

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

server.listen()

while True:
    conn, addr = server.accept()
    print("new conn:",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 output..."

        conn.send( str(len(cmd_res.encode())).encode("utf-8")    )     #先发大小给客户端
        # time.sleep(0.5)

        # 利用应答解决粘包
        client_ack = conn.recv(1024) #等待确认sleep优化
        print("ack from client:",client_ack.decode())
        conn.send(cmd_res.encode("utf-8"))
        print("send done")
        # os.path.isfile()
        # os.stat("sock")
server.close()

import hashlib
m = hashlib.md5()

sock_server_client.py

__author__ = "Alex Li"
import socket
client = socket.socket()

client.connect(('10.0.0.6',9999))
# 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("准备好接收了,loser可以发了".encode("utf-8")) #ack确认,将sleep去掉做优化
    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
    else:
        print("cmd res receive done...",received_size)
        print(received_data.decode())


client.close()

# 将server文件上传到linux上,然后在socke_server_client终端执行linux相关命令:
#   ip a
#   top -bn 2
#   netstat -lnutp |grep LISTEN

'''
>>:netstat -lnutp |grep LISTEN
命令结果大小: b'808'
cmd res receive done... 808
tcp        0      0 0.0.0.0:9999            0.0.0.0:*               LISTEN      16599/python3       
tcp        0      0 192.168.122.1:53        0.0.0.0:*               LISTEN      3404/dnsmasq        
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1158/sshd           
tcp        0      0 127.0.0.1:631           0.0.0.0:*               LISTEN      1154/cupsd          
tcp        0      0 127.0.0.1:6010          0.0.0.0:*               LISTEN      4858/sshd: root@pts 
tcp6       0      0 :::22                   :::*                    LISTEN      1158/sshd           
tcp6       0      0 ::1:631                 :::*                    LISTEN      1154/cupsd          
tcp6       0      0 ::1:6010                :::*                    LISTEN      4858/sshd: root@pts 

>>:
'''
上一篇:【Linux下安装配置Jupyter】 �


下一篇:【Linux下安装配置Jupyter】