zoukankan      html  css  js  c++  java
  • 4.20---远程执行命令的CS架构软件

    服务端

    import socket
    import subprocess
    
    # 创建服务器套接字
    phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    
    # 绑定ip+端口
    phone.bind(("127.0.0.1",6668))
    # 监听连接,5代表半连接池大小为5
    phone.listen(5)
    print('服务端启动完成,监听地址为:%s:%s' %('127.0.0.1',8080))
    
    while True:
        # #接受客户端链接,返回值为 sock, addr
        conn,client_addr = phone.accept()
    
        while True:
            try:
                # 设置接收大小为1024个bytes
                cmd = conn.recv(1024)
                obj = subprocess.Popen(cmd.decode("utf-8"),shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
            # 错误示范:if res.stdout:    必须加read() 不然即使里面没有内容,obj.stdout仍为真
                res = obj.stdout.read()
                if res:
                    conn.send(res)
            # 错误示范:if obj.stderr.read(),stderr中数据只能被读一次,第二次读取将变为空
            # 错误示范:conn.send(res.stdout.read())  此处笔误,则出现报错 res.stdout.read()为空,在TCP中发送空包会阻塞
                err_res = obj.stderr.read()
                if err_res:
                    conn.send(err_res)
    
            except Exception:
                print("连接出错。")
                break
        conn.close()

    客户端

    import socket
    
    phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    
    phone.connect(("127.0.0.1",6668))
    
    while True:
        cmd = input("请输入指令:").strip()
        if len(cmd) == 0:
            continue
    
        phone.send(cmd.encode("utf-8"))
        res = phone.recv(1024)
        print(res.decode("gbk"))
    
    phone.close()
  • 相关阅读:
    poj 2676 Suduku (dfs)
    poj 1562 Oil Deposits (dfs)
    poj 2907 Collecting Beepers (dfs)
    poj 1655 Balancing Act (树形dfs)
    poj 3411 Paid Roads (dfs)
    hdu 2896 病毒侵袭 (AC)
    hdu 3065 病毒侵袭持续中 (AC)
    poj 2251 Dungeon Master (bfs)
    java中debug使用
    Swing入门级小项目总结
  • 原文地址:https://www.cnblogs.com/zhubincheng/p/12741163.html
Copyright © 2011-2022 走看看