zoukankan      html  css  js  c++  java
  • day 30 客户端获取cmd 命令的步骤

    import subprocess
    import struct
    import json
    from socket import *
    server=socket(AF_INET,SOCK_STREAM)
    server.bind(('127.0.0.1',8099))
    # print(server)
    server.listen(5)
    while True:
    conn,addr=server.accept()
    print(conn)
    print(addr)
    while True:
    try:
    cmd=conn.recv(8096)
    if not cmd:break #针对linux

    #执行命令
    cmd=cmd.decode('utf-8')
    #调用模块,执行命令,并且收集命令的执行结果,而不是打印
    obj = subprocess.Popen(cmd, shell=True,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    )
    stdout=obj.stdout.read()
    stderr=obj.stderr.read()

    # 1:先制作报头,报头里放:数据大小, md5, 文件
    header_dic = {
    'total_size':len(stdout)+len(stderr),
    'md5': 'xxxxxxxxxxxxxxxxxxx',
    'filename': 'xxxxx',
    'xxxxx':'123123'
    }
    header_json = json.dumps(header_dic)
    header_bytes = header_json.encode('utf-8')
    header_size = struct.pack('i', len(header_bytes))
    #字典的此长度(报头的长度)
    # 2: 先发报头的长度
    conn.send(header_size)

    # 3:先发报头
    conn.send(header_bytes)

    # 4:再发送真实数据
    conn.send(stdout)
    conn.send(stderr)
    except ConnectionResetError:
    break
    conn.close()

    server.close()

    -----------
    import struct
    import json
    from socket import *

    client=socket(AF_INET,SOCK_STREAM)
    client.connect(('127.0.0.1',8099))

    while True:
    cmd=input('>>: ').strip()
    if not cmd:continue
    client.send(cmd.encode('utf-8'))
    # 1:先收报头长度
    obj = client.recv(4)
    header_size = struct.unpack('i', obj)[0]
    # 2:先收报头,解出报头内容
    header_bytes = client.recv(header_size)
    header_json = header_bytes.decode('utf-8')
    header_dic = json.loads(header_json)
    print(header_dic)
    total_size = header_dic['total_size']
    # 3:循环收完整数据
    recv_size=0
    res=b''
    while recv_size < total_size:
    recv_data=client.recv(1024)
    res+=recv_data
    recv_size+=len(recv_data)
    print(res.decode('gbk'))
    client.close()
  • 相关阅读:
    【计蒜客习题】取石子游戏
    【SCOI2005】骑士精神
    依赖背包
    强连通分量
    2017 Multi-University Training Contest
    2017 Multi-University Training Contest
    3月每日。
    2月每日DONE。
    寒假划水。
    基础实验2-2.5 整数分解为若干项之和 (20分)--dfs
  • 原文地址:https://www.cnblogs.com/xiaoluoboer/p/7911586.html
Copyright © 2011-2022 走看看