Python发送命令,达到远程锁定服务器的目的

# Server

import socket
import subprocess

def get_ip_address():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("10.255.255.255", 1))
        IP = s.getsockname()[0]
    except Exception:
        IP = "127.0.0.1"
    finally:
        s.close()
    return IP

ip_address = get_ip_address()
print("Current IP Address:", ip_address)


def main():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    #server_socket.bind(('localhost', 5000))
    server_socket.bind((ip_address, 5000))
    server_socket.listen(5)

    while True:
        client_socket, addr = server_socket.accept()
        print("Connection from {addr} established.")
        command = client_socket.recv(1024).decode()
        print('command is')
        print(command)
        try:
            output = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT)
            client_socket.send(output)
        except subprocess.CalledProcessError as e:
            client_socket.send(e.output)

        client_socket.close()

if __name__ == '__main__':
    main()

import socket

# 服务器配置
host = '192.168.2.125'  # 服务器地址
port = 5000        # 服务器端口

# 创建 socket 对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((host, port))


def execute_command_a():
    print("Executing command A")
    command = """osascript -e 'tell application "System Events" to keystroke "q" using {control down, command down}'"""
    return command

def execute_command_b():
    print("Executing command B")
    command = """osascript -e 'tell app "System Events" to restart'"""
    return command

def execute_command_c():
    print("Executing command C")
    command = """osascript -e 'tell app "System Events" to shut down'"""
    return command

def default_command():
    print("Unrecognized command")

def switch_case(command):
    switch = {
        'a': execute_command_a,
        'b': execute_command_b,
        'c': execute_command_c
    }
    # 获取命令对应的函数并执行,如果命令不存在则执行默认函数
    return switch.get(command, default_command)()

# 发送命令
str = "Enter command to execute:\n"
str += "a -- lock\n"
str += "b -- restart\n"
str += "c -- shutdown\n"
print(str)
command = input('')
command = switch_case(command)
#command = "rundll32.exe user32.dll,LockWorkStation"
#command = """osascript -e 'tell application "System Events" to keystroke "q" using {control down, command down}'"""

client_socket.send(command.encode())

# 接收并打印响应
response = client_socket.recv(4096)
print(response.decode())

client_socket.close()

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值