博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python subprocess 小例子
阅读量:5226 次
发布时间:2019-06-14

本文共 5998 字,大约阅读时间需要 19 分钟。

#服务端 import socket import os import subprocess phone = 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 socketserver import json import struct import subprocess import 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()

转载于:https://www.cnblogs.com/yanxiatingyu/p/9294633.html

你可能感兴趣的文章
JavaScript中的继承
查看>>
MySQL简介
查看>>
设计模式之桥接模式(Bridge)
查看>>
转:探讨跨域请求资源的几种方式
查看>>
jquery的$(document).ready()和onload的加载顺序
查看>>
Python Web框架Django (五)
查看>>
.net学习之继承、里氏替换原则LSP、虚方法、多态、抽象类、Equals方法、接口、装箱拆箱、字符串------(转)...
查看>>
Android 开发 ThreadPool(线程池) 总结
查看>>
【poj1568】 Find the Winning Move
查看>>
【codevs1033】 蚯蚓的游戏问题
查看>>
TP框架中的page分页实现
查看>>
[转]跨越千年的RSA算法
查看>>
传奇学者应明生
查看>>
【程序执行原理】
查看>>
第二次项目冲刺(Beta阶段)5.24
查看>>
python的多行注释
查看>>
连接Oracle需要jar包和javadoc文档的下载
查看>>
UVA 10976 - Fractions Again?!
查看>>
poj 1183
查看>>
Dreamweaver cc新版本css单行显示
查看>>