python-socket实现简单的ssh客户端

2018-06-25 05:54:21来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

  客户端代码,监听端口号为 localhost 9999

#!/usr/local/bin/python3
# -*- coding:utf-8 -*-

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.decode())

    # 防止粘包-装逼方法
    client.send("接收成功".encode("utf-8"))

    # print(cmd_res)

    received_size = 0

    while received_size < int(cmd_res_size.decode()):

        data = client.recv(1024)
        received_size += len(data)
        print(data.decode())
        print("-----%s-----" % len(data))
    else:
        print("received done...", cmd_res_size.decode())



client.close()

  服务器端代码

#!/usr/local/bin/python3
# -*- coding:utf-8 -*-

import socket, os, time

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)
        if not data:
            print("客户端断开连接")
            break
        print("执行指令:", data)
        cmd_res = os.popen(data.decode()).read()
        conn.send(str(len(cmd_res)).encode("utf-8"))    # 先发大小给客户端

        # 防止粘包-low的方法
        # time.sleep(0.5)     # 强制缓冲区超时,防止粘包

        # 防止粘包-装逼方法     # 在两次send中间强制进行一次收发,这样就能有效防止粘包
        ack = conn.recv(1024)
        print(">>>>>:", ack.decode())

        tmp = conn.send(cmd_res.encode("utf-8"))
        print(">>>>>: 发送成功")

server.close()

  

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Python3 与 C# 面向对象之~继承与多态

下一篇:题目:打印出所有的&quot;水仙花数&quot;