Python实现远程执行命令(cmd)文件上传与此方法类似
server端:
import socket import subprocess#cmd模块 # subprocess.Popen() sk = socket.socket() address = ('127.0.0.1',8000) sk.bind(address) sk.listen(3) print('writing..........') while True: conn,addr = sk.accept() print(addr) while True: try: data = conn.recv(1024) except Exception: break print(str(data,'utf8')) #拿到一个对象 obj = subprocess.Popen(str(data,'gbk'),shell=True,stdout=subprocess.PIPE) cmd_result = obj.stdout.read() #int类型和bytes类型不能直接转换,需要中间人str,才能进行转换 result_len = bytes(str(len(cmd_result)),'utf8') conn.sendall(result_len) conn.sendall(cmd_result) # if not data:break # inp = input('>>>>>>>>') # conn.send(bytes(inp,'utf8')) conn.close() sk.close()
Client端:
import socket sk = socket.socket() address = ('127.0.0.1',8000) print(sk) sk.connect(address) while True: inp = input('>>>>>.') if inp == 'exit': break sk.send(bytes(inp,'utf8')) result_len = int(str(sk.recv(1024),'utf8')) print(result_len) data = bytes() while len(data) != result_len: recv = sk.recv(1024) data += recv print(str(data,'gbk')) sk.close()
在Client端执行cmd命令,如dir,cd,ipconfig等
结果如下: