服务器:
import socket
import subprocess
server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# server.settimeout(10)
host="0.0.0.0"
port=9999
server.bind((host,port))
server.listen(1)
print("server lisen on "+str(port))
auth="admin"
while True:
try:
client, addr = server.accept()
print("connected from :",addr[0])
# client.send("server is ready".encode())
data=client.recv(1024)
command=data.decode()
if command:
if "::" not in command:
print("请求命令非法")
continue
command=command.split('::')
if command[0] == auth:
cmd=command[1]
print("run: {}".format(cmd))
ret=subprocess.check_output([cmd],shell=True)
client.send(ret)
else:
print("认证非法")
continue
except:
continue
客户端:
import socket
def remote_cmd(host,port,auth,command):
client=socket.socket()
client.settimeout(10)
try:
client.connect((host,port))
#认证密码+::符号分割
client.send((auth+"::"+command).encode())
result=client.recv(1024)
return result.decode("gbk")
client.close()
except Exception as e:
print(e)
client.close()
return False
if __name__=="__main__":
host=input("host:")
auth=input("auth:")
while True:
command=input("command(type exit to end):")
if command=="exit":
exit(0)
result = remote_cmd(host=host, port=9999, auth=auth, command=command)
# result=remote_cmd(host="192.168.66.164",port=9999,auth="admin",command="cmd /c dir z:")
if result:
print(result)
else:
print("执行失败")