在Windows下Python使用SSH若干事

本文介绍了如何在Windows环境下使用Python实现SSH远程操作。通过安装必要的库并解决常见问题,最终实现了脚本远程执行的功能。

在Windows下Python使用SSH若干事

在Windows下Python使用SSH若干事

#

缘由

叶子我最近折腾OpenSUSE,新本到了之后,实在懒得折腾多系统了,所以搞了虚拟机,OpenSUSE感觉还是不错的,在Windows下配合PuTTY(顺便说一下,一定要用英文版)真是……怎一个爽字了得。

咳咳,扯远了……于是,在ST3下,准备折腾一下,写个插件,写好脚本直接用SSH传到虚拟机去,然后远端执行……

顺带提一下,我偷懒装的WinPython……

折腾

先装ssh,直接用pip

pip install ssh

这货需要PyCrypto,会自动安装的,然后……一大堆我就木有仔细看,直接运行脚本了

#!/usr/bin/env python
import ssh

# New SSHClient
client = ssh.SSHClient()

# Default accept unknown keys
client.set_missing_host_key_policy(ssh.AutoAddPolicy())

# Connect
client.connect("192.168.17.128", port=22, username="xana", password='xxxxxxx')

# Execute shell remotely
stdin, stdout, stderr = client.exec_command("ls -alh")
print(stdout.read())

Ctrl+B……报错! 
找不到Crypto……ssh要引用它,好么,仔细一看,site-packages下crypto文件夹改为Crypto,再来。 
Ctrl+B……报错!python告诉我找不到Crypto.Random,我看了一下,包里还真没有……奇怪。

pip uninstall crypto

然后再来

pip install pycrypto

这次眼睛放雪亮了,看到Error了…… Unable to find vcvarsall.bat ,好吧,感情pycrypto这货居然还要编译,估计是为了效率?核心部分都用C写的啊……

google了一下, 这里 提到了解决方案,对于他的第二个方案装VS我倒是很简单,VS2013老早就装好了,算了一下,应该是VC110,打开 Lib/distuils/msvc9compiler.py ,找到 toolskey,把赋值部分直接改成

toolskey = "VS110COMNTOOLS"

再次安装PyCrypto,编译成功,搞定。

### Python 实现远程或定时关机脚本 #### 远程关机脚本 要通过 Python 编写一个能够实现远程关机的脚本,可以利用 `paramiko` 库来连接到目标主机并通过 SSH 执行关机命令。以下是具体代码示例: ```python import paramiko def remote_shutdown(host, port, username, password): try: client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(host, port=port, username=username, password=password) command = 'sudo shutdown now' # 关闭系统的命令 stdin, stdout, stderr = client.exec_command(command) error_message = stderr.read().decode('utf-8') if error_message.strip() != '': print(f"Error occurred while shutting down the system: {error_message}") else: print("Remote shutdown initiated successfully.") client.close() except Exception as e: print(f"An exception occurred: {e}") if __name__ == "__main__": host = "192.168.1.100" # 替换为目标主机IP地址 port = 22 # 默认SSH端口 username = "root" # 用户名 password = "password" # 密码 remote_shutdown(host, port, username, password) ``` 上述代码实现了通过 SSH 对远程服务器发送关闭指令的功能[^2]。 --- #### 定时关机脚本 如果希望编写一个本地运行的 Python 脚本来实现定时关机,则可以通过调用操作系统的关机命令完成此功能。以下是一个简单的例子: ```python import os import time def schedule_shutdown(shutdown_time): current_time = time.strftime("%H:%M", time.localtime()) while current_time != shutdown_time: current_time = time.strftime("%H:%M", time.localtime()) time.sleep(60) # 每隔一分钟检查一次时间 os.system("shutdown /s /t 0") # Windows 的关机命令 if __name__ == "__main__": scheduled_time = "23:00" # 设定为晚上11点 schedule_shutdown(scheduled_time) ``` 这段代码会持续监测当前的时间,当到达设定好的关机时刻时执行系统自带的关机命令[^3]。 --- #### 结合交互式的菜单设计 为了增强用户体验,还可以加入类似于批处理文件中的选项菜单机制,让用户自行决定是否立即或者延迟一段时间后再进行关机操作。下面展示了一个综合性的解决方案: ```python from datetime import timedelta, datetime import subprocess def immediate_shutdown(): confirmation = input("Are you sure to shut down immediately? (y/n): ") if confirmation.lower() == 'y': subprocess.call(["shutdown", "/s", "/t", "0"]) def delayed_shutdown(minutes): confirmation = input(f"Will your PC be turned off after {minutes} minutes. Confirm?(y/n): ") if confirmation.lower() == 'y': subprocess.call(["shutdown", "/s", "/t", str(int(minutes)*60)]) menu_options = { 1: ("Immediate Shutdown", lambda :immediate_shutdown()), 2: ("Delayed Shutdown", lambda :delayed_shutdown(input("Enter delay in minutes: ")) ), } while True: print("\nMenu:") for key, value in menu_options.items(): print(f"{key}. {value[0]}") choice = int(input("Select an option: ")) if choice in menu_options.keys(): action_function = menu_options.get(choice)[1] action_function() break else: print("Invalid selection! Try again.") ``` 这个程序提供给用户两个选择:立刻关机或是指定若干分钟后自动关机,并且只有在获得用户的确认之后才会真正触发关机动作[^4]。 --- ### 注意事项 - 使用这些脚本前,请确保拥有足够的权限去操控目标机器上的资源。 - 配置好防火墙规则允许来自特定源 IP 地址范围内的入站流量访问 SSH 端口。 - 测试阶段建议先尝试重启而非完全断电的方式来验证逻辑无误。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值