1、执行命令os.system('ls')
- os.system 返回1 or 0 ,不能当做数据发送
# windows # dir 查看某个文件夹下子自文件名与子文件夹名 # ipconfig 查看本地网卡的ip信息 # tasklist 查看运行的进程 # linux # ls # ifconfig # ps aux
2、subprocess模块
但注意注意注意:
res = subprocess.Popen(cmd.decode('utf-8'),shell=True,stderr=subprocess.PIPE,stdout=subprocess.PIPE)
命令结果的编码是以当前所在的系统为准的,如果是windows,那么res.stdout.read()读出的就是GBK编码的,在接收端需要用GBK解码,且只能从管道里读一次结果
import subprocess # subprocess.Popen('dir') # FileNotFoundError: [WinError 2] 系统找不到指定的文件。 # subprocess.Popen('dir', shell=True) # 命令执行正确 obj = subprocess.Popen('dir', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) print(obj) print('studout:', obj.stdout.read().decode('gbk')) # windows解码成gbk # 并且只能从管道读一次 print('studerr:', obj.stderr.read().decode('gbk')) # linux解码成utf-8 # 命令执行错误 obj = subprocess.Popen('dissr', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) print(obj) print('studout:', obj.stdout.read().decode('gbk')) # windows解码成gbk print('studerr:', obj.stderr.read().decode('gbk')) # linux解码成utf-8
3、简单远程执行命令程序开发
(1)服务端
import socket import subprocess server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(('127.0.0.1', 9994)) server.listen(5) while True: print('waiting...') conn, addr = server.accept() while True: try: # 1.收命令 data = conn.recv(1024) print('=》', data) if not data: break # 2.执行命令,拿到结果 obj = subprocess.Popen(data.decode('utf-8'), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) # 3.把命令的结果返回给客户端 stdout = obj.stdout.read() stderr = obj.stderr.read() conn.send(stdout+stderr) # 可以优化的一个点 except ConnectionResetError: break conn.close() server.close()
(2)客户端
import socket client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(('127.0.0.1', 9994)) while True: # 1.发出命令 data = input('>>>').strip() if not data: continue client.send(data.encode('utf-8')) # 2.接受命令的结果,打印 ret = client.recv(1024) print('from server:', ret.decode('gbk')) # windows gbk编码 client.close()