👉技__能👈:C/C++/C#/Python/Java/PHP/Vue/Node.js/HTML语言
👉专__注👈:专注主流机器人、人工智能等相关领域的开发、测试技术。
局域网内通过python远程重启另一台windows电脑
目录
- 局域网内通过python远程重启另一台windows电脑
- 前提条件
- 代码实现
前提条件
如果想要使用代码控制远程电脑重启或其他相关操作,需要保证你当前的电脑能够通过windows系统自带的远程桌面连接,能够远程访问另一台电脑。
如果当前还不能通过远程桌面访问,请查看网上教程,这里不做讲解。
代码实现
import subprocess
import time
def restart_server():
remote_ip = "192.168.2.12"
username = "admin"
password = '123456'
remote_share = f"\\\\{remote_ip}\\C$"
# 1. 连接共享
cmd_login = f'net use {remote_share} /user:{username} {password}'
login_result = subprocess.run(cmd_login, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
print("Login STDOUT:", login_result.stdout)
print("Login STDERR:", login_result.stderr)
# 2. 远程重启
cmd_shutdown = f"shutdown /r /m \\\\{remote_ip} /t 0 /f"
shutdown_result = subprocess.run(cmd_shutdown, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
print("Shutdown STDOUT:", shutdown_result.stdout)
print("Shutdown STDERR:", shutdown_result.stderr)
# 3. 删除共享
cmd_logout = f'net use {remote_share} /delete'
logout_result = subprocess.run(cmd_logout, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
print("Logout STDOUT:", logout_result.stdout)
print("Logout STDERR:", logout_result.stderr)
restart_server()
- 定义了远程服务器的IP地址、用户名和密码等信息。
- 构建了远程共享路径。
- 使用
net use
命令连接远程共享路径,实现登录操作。 - 使用
shutdown
命令远程重启指定IP地址的计算机。 - 使用
net use
命令删除共享映射,实现退出登录操作。
需要注意的是:
- 这段代码执行的功能是连接到远程计算机,执行重启操作,然后断开连接。确保在真实环境中谨慎操作,避免造成误操作带来的问题。
- 必须需谨慎处理密码信息的传递和存储,尤其是明文密码。
- 确保目标计算机具有相应权限让指定用户进行远程操作。
- 可能需要处理一些异常情况,比如账户验证失败等。