Pyhton编程:socket实现ssh通讯
  TEZNKK3IfmPf 2023年11月15日 43 0
服务器端
import socket
import os

server = socket.socket()

server.bind(("localhost", 6969)) # 绑定监听端口

server.listen(5)  # 监听

print("监听开始..")

while True:
    conn, addr = server.accept()  # 等待连接

    print("conn:", conn, "\naddr:", addr)  # conn连接实例

    while True:
        data = conn.recv(1024)  # 接收
        if not data:  # 客户端已断开
            print("客户端断开连接")
            break

        print("收到的命令:", data.decode("utf-8"))
        res = os.popen(data.decode("utf-8")).read()

        print("发送的大小:", len(res))
        conn.send(str(len(res)).encode("utf-8"))  # 先发送长度
        confirm = conn.recv(1024)  # 等待确认,解决粘包问题
        print(res)

        conn.send(res.encode("utf-8"))  # 再发送内容

server.close()
客户端
import socket

client = socket.socket()  # 生成socket连接对象

ip_port =("localhost", 6969)  # 地址和端口号

client.connect(ip_port)  # 连接

print("服务器已连接")

while True:
    content = input(">>")

    if len(content)==0: continue  # 如果传入空字符会阻塞

    client.send(content.encode("utf-8"))  # 传送和接收都是bytes类型

    receive_size = client.recv(1024)  # 先接收长度,建议8192

    data_size = int(receive_size.decode("utf-8"))

    print("接收到的大小:", data_size)
    client.send("准备好接收".encode("utf-8"))
    datas = ""

    while len(datas) < data_size:
        data = client.recv(1024)  # 多次接收内容,接收大数据
        datas += data.decode("utf-8")

    print(len(datas), datas)  # 解码

client.close()
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月15日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2024年05月31日   34   0   0 python开发语言
  TEZNKK3IfmPf   2024年05月31日   25   0   0 python
  TEZNKK3IfmPf   2024年05月31日   34   0   0 excelpython
  TEZNKK3IfmPf   2024年05月31日   25   0   0 python
TEZNKK3IfmPf