python 编写一个远程执行命令的服务器与客户端示例

29 篇文章 1 订阅
24 篇文章 0 订阅

服务器:

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("执行失败")

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值