python 远程 Windows 防止电脑处于不活跃状态

161 阅读1分钟

1、在Windows中 打开PowerShell(以管理员身份运行)

#启用WinRM
Enable-PSRemoting -Force


#查看是否启用WinRM成功
Get-Service -Name WinRM


#确保防火墙允许5985端口的入站通信  
New-NetFirewallRule -Name "WinRM-HTTP" -DisplayName "WinRM over HTTP" -Enabled True -Direction Inbound -Protocol TCP -LocalPort 5985 -Action Allow


#确保防火墙允许5985端口的入站通信  
winrm quickconfig


#配置WinRM以允许基本身份验证和未加密的流量
# 允许基本身份验证
Set-Item -Path WSMan:\localhost\Service\Auth\Basic -Value $true

# 允许未加密的流量
Set-Item -Path WSMan:\localhost\Service\AllowUnencrypted -Value $true

注: ECS安全组中需要开放5985端口

其他命令参考:

#停止WinRM服务
Stop-Service -Name WinRM


#开始WinRM服务
Start-Service -Name WinRM

2、在Linux中测试远程连接Windows

import winrm

try:
    session = winrm.Session('http://ip:5985/wsman', auth=('administrator', 'password'))
    result = session.run_cmd('dir')
    #result = session.run_cmd('whoami')
    print(result.std_out.decode())
    print(result.std_err.decode())
except Exception as e:
    print(f"Connection failed: {e}")

安装依赖包:pip3 install pywinrm 执行结果: image.png

注:remote_winrm.py和WorkBench远程链接不在一个端口上,所以remote_winrm.py运行不会中断在连接状态的WorkBench。

放在后台执行remote_winrm.py

nohup python3 remote_winrm.py &
import winrm
import time
import logging

logging.basicConfig(filename='remote_winrm.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

def connect_and_run():
    try:
        session = winrm.Session('http://ip:5985/wsman', auth=('administrator', 'password'))
        result = session.run_cmd('whoami')
        logging.info(result.std_out.decode())
    except Exception as e:
        logging.error(f"Connection failed: {e}")

while True:
    connect_and_run()
    time.sleep(10)

参考文章: 解决Windows Server远程断开后自动锁屏问题_远程桌面后如何解除屏幕锁定-CSDN博客