• python socket简单实现SSH服务器端


    #server


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

    server.listen()

    while True:
    conn,addr=server.accept()
    while True:
    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"))#先发大小给客户端
    conn.send(cmd_res.encode("utf-8"))
    print("semd 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)
    received_size= 0
    received_data=b''
    while received_size< int(cmd_res_size.decode()):
    data = client.recv(1024)
    received_size +=len(data)#每次收到的有可能小于1024,所以必须用len判断
    received_data +=data

    else:
    print("cmd res receive done...",received_size)
    print(received_data.decode())


    client.close()
  • 相关阅读:
    Datediff的使用(统计本日,昨日,本周,本月)
    数据库之查询语句
    数据库之表关系
    数据库中的数据类型
    数据库概念和基本操作
    IO模型
    并发编程之协程
    GIL与多线程(线程池与进程池,同步异步阻塞非阻塞)
    并发编程之多线程
    并发编程之多进程
  • 原文地址:https://www.cnblogs.com/anhao-world/p/13420189.html
Copyright © 2020-2023  润新知