#服务端import socketimport osimport subprocessphone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)print('进行绑定,监听')phone.bind(('127.0.0.1', 8080))phone.listen(5)

def cmd(cmdlist):    obj=subprocess.Popen(        cmdlist,        shell=True,        stdout=subprocess.PIPE,        stderr=subprocess.PIPE    )

    stdout_res=obj.stdout.read()    stderr_res=obj.stderr.read()

    return stdout_res+stderr_res#假如不写成方法,这里可以分成两次发送过去,更加节省内存

while True:    conn, add = phone.accept()    print('建立连接')

    while True:        try:            msg = conn.recv(1024)            if not len(msg):                break

            print('执行命令')            print(msg)            #os.system(msg.decode(encoding='utf-8'))

            stdout_res=cmd(msg.decode(encoding='utf-8'))            print('发送消息')            conn.send(stdout_res)        except Exception:            break

    conn.close()phone.close()

#客户端
import socket

st = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

st.connect(('127.0.0.1', 8080))while True:    msg=input('请输入cmd 命令').strip()    print('发送消息')    if not len(msg):continue

    st.send(msg.encode(encoding='utf-8'))    data=st.recv(1024)    print(data.decode('gbk'))

st.close()

#服务端
# import socketserver### class Myhandler(socketserver.BaseRequestHandler):#     def Hadler(self):#         print('连接建立成功')#         while True:#             try:#                 data = self.request.recv(1024)#                 if not len(data): break#                 self.request.send(data)##             except ConnectionResetError:#                 break##         self.request.close()### if __name__ == '__main__':#     print('开始启动')#     st = socketserver.ThreadingTCPServer(('127.0.0.1', 8080), Myhandler, bind_and_activate=True)#     print('开始建立连接')#     st.serve_forever()  # 提供无限循环,循环建立链接#     # 每建立链接,就会启动一个线程,专门与刚刚#     # 建立好的链接做通信循环#     # 调用myhandler类产生一个对象,条用该对象下的handler方法,专门与刚刚建立好的#     # 连接做通信循环

import socketserverimport jsonimport structimport subprocessimport os

class MyHandler(socketserver.BaseRequestHandler):    def handle(self):        # 通信循环        while True:            try:                cmd = self.request.recv(1024)                if len(cmd) == 0:                    break                else:                    cmd = cmd.decode(encoding='utf-8')

                if cmd == 'get':                    path = 'file.txt'                    if not os.path.exists(path):                        raise ValueError('没有文件')                    total_size = os.path.getsize(filename=path)                    print(total_size)                    import hashlib                    with open(path, 'rb') as f:                        for line in f:                            line                    hashlib_value = 'xxxx'                else:                    obj = subprocess.Popen(cmd,                                           shell=True,                                           stdout=subprocess.PIPE,                                           stderr=subprocess.PIPE)                    s_out = obj.stdout.read()                    s_err = obj.stderr.read()                    total_size = len(s_out) + len(s_err)                    path = None                    hashlib_value = '你大爷'

                header_dic = {                    'file_name': path,                    'total_size': total_size,                    'hashlib': hashlib_value                }                header_json = (json.dumps(header_dic)).encode(encoding='utf-8')                header_len = struct.pack('i', len(header_json))                print('header_len:%s' % header_len)

                # print(header_len)                self.request.send(header_len)                # print(header_json)                self.request.send(header_json)

                if cmd == 'get':                    with open(path, 'rb') as f:                        for line in f:                            # print(line)                            self.request.send(line)                else:                    # print('cmd')                    self.request.send(s_out)                    self.request.send(s_err)

            except ConnectionResetError:                break

        self.request.close()

if __name__ == "__main__":    s = socketserver.ThreadingTCPServer(('127.0.0.1', 8080), MyHandler, bind_and_activate=True)    s.serve_forever()

#客户端
# from socket import *## socket_client = socket(AF_INET, SOCK_STREAM)# print('进行连接')# socket_client.connect(('127.0.0.1', 8080))# print('连接成功')# while True:#     msg = input('请输入')#     if not len(msg): continue#     socket_client.send(msg.encode(encoding='utf-8'))#     data =socket_client.recv(1024)#     print(data.decode(encoding='utf-8'))## socket_client.close()

import socket, struct, json, hashlib

st = socket.socket(socket.AF_INET, socket.SOCK_STREAM)st.connect(('127.0.0.1', 8080))

def get_file(st):    data = st.recv(4)    print(data)    data = struct.unpack('i', data)[0]    header_json = json.loads((st.recv(data)).decode('utf-8'))    print(header_json)    file_down = b''    encodeing = None    while header_json['total_size'] > 0:        msg = st.recv(1024)        header_json['total_size'] -= len(msg)        file_down += msg        try:            if encodeing == None:                print(msg.decode(encoding='utf-8'))            else:                print(msg.decode(encodeing='gbk'))        except Exception:            encodeing == False            print(msg.decode(encoding='gbk'))

    return file_down

while True:

    msg = input('请输入').strip()    if not len(msg): continue    try:        st.send(msg.encode('utf-8'))        file_down = get_file(st)

        if msg == 'get':            with open('save.txt', 'wb') as f:                f.write(file_down)            print('end')

    except ConnectionResetError:        break

st.close()

python subprocess 小例子的更多相关文章

  1. 感受python之美,python简单易懂的小例子

    前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 1 简洁之美 通过一行代码,体会Python语言简洁之美 2 Python ...

  2. python闭包小例子

    ------------------ 首先根据实例, 体会一下闭包的效果 ------------------ 定义闭包: def foo(x): a = [0] def bar(y): a[0] = ...

  3. python ctypes小例子

    import time import ctypes import ctypes.wintypes SEE_MASK_NOCLOSEPROCESS = 0x00000040 SEE_MASK_INVOK ...

  4. [Python]Python 函数调用小例子

    函数定义: In [78]: def printme(str): ....: print str ....: return ....: 调用: In [79]: printme('This is Ji ...

  5. [Spark][Hive][Python][SQL]Spark 读取Hive表的小例子

    [Spark][Hive][Python][SQL]Spark 读取Hive表的小例子$ cat customers.txt 1 Ali us 2 Bsb ca 3 Carls mx $ hive h ...

  6. [Python]Python 使用 for 循环的小例子

    [Python]Python 使用 for 循环的小例子: In [7]: for i in range(5): ...: print "xxxx" ...: print &quo ...

  7. [python]python 遍历一个list 的小例子:

    [python]python 遍历一个list 的小例子: mlist=["aaa","bbb","ccc"]for ss in enume ...

  8. Python,while循环小例子--猜拳游戏(三局二胜)

    Python,while循环小例子--猜拳游戏(三局二胜) import random all_choice = ['石头', '剪刀', '布'] prompt = '''(0)石头 (1)剪刀 ( ...

  9. 这42个Python小例子,太走心

    告别枯燥,60秒学会一个Python小例子.奔着此出发点,我在过去1个月,将平时经常使用的代码段换为小例子,分享出来后受到大家的喜欢. 一.基本操作 1 链式比较 i = 3print(1 <  ...

随机推荐

  1. &符号 (弃用引用传参了,不要用!!)

    写法一 $age = function grow($age) { $age += ; return $age; } echo grow($age) echo $age 写法二 $age = funct ...

  2. LisView控件

    用LisView控件在窗体中创建一个表,设置一个按钮,点击按钮, 将数据库中的表在这个控件中显示(LisView控件中表格式列名与数据库中一致) 首先使用控件将表的每一列创建好,加入一个按钮,如图,现 ...

  3. JAVA回文

    package huiwen; import java.util.Scanner; public class Huiwen { public static void main(String[] arg ...

  4. 阿里大于发送短信(java)

    一.短信签名设置 1.短信签名是什么? 签名是在短信内容开始或者末尾跟的品牌或者应用名称,设置签名有一下几个好处:增加品牌的曝光度,增强用户的记忆让用户能更清楚的知道正在使用的应用. 2.签名可不可以 ...

  5. java 集合 Se HashTreeSet

    Set接口  Set是Collection的子接口,与List相对 Set集合中的元素的特点是1,无序性 2,无下标3,无重复的元素 Set是个接口,所以无法直接创建对象,要依赖它的实现类来创建对象  ...

  6. 动态代理 JDK动态代理 CGLIB代理

    代理模式:代理类和被代理类实现共同的接口(或继承),代理类中存有指向被代理类的索引,实际执行时通过调用代理类的方法.实际执行的是被代理类的方法. 而AOP,是通过动态代理实现的. 一.简单来说: JD ...

  7. AssetBundle 策略

    [AssetBundle 策略] 1.Logical Entity Grouping.按逻辑功能分. Examples Bundling all the textures and layout dat ...

  8. DB2 57016报错的解决办法(表状态不正常,导致表无法操作)

    新建了一张表,删除了一列,然后执行insert的时候,报错 57016,解释为:因为表不活动. 1.执行db2 "load query table <tabname>" ...

  9. day15模块内容

    1.生成器表达式 先说三元表达式如下 res = [i for i in range(10) if 1 > 5] 这样res就是一个列表6,7,8,9] 只要在这个基础上稍加调整,如下 方括号改 ...

  10. php打印错误报告

    //error handler functionfunction customError($errno, $errstr){ echo "<b>Error:</b> ...