连接Putty并输入几个命令。

7

我想连接到putty,并想要执行以下几个步骤:

  1. 登录Putty
  2. 键入一些命令以关闭服务器
  3. 遍历到特定路径
  4. 从目录中删除文件
  5. 重新启动服务器

我需要在Windows中编写代码。但我的服务器在Linux上。 我应该如何继续? 提前致谢。


你可以使用Fabric来执行这些步骤。 - Mohammad Tayseer
我认为你想要登录到一个SSH服务器,这样你就可以使用http://www.lag.net/paramiko/。你不需要PuTTY! - W0bble
4个回答

9
你需要的是Paramiko,但对于初学者来说可能有点复杂。
对于简单重复的任务,可以使用我的脚本 - 它位于GitHub(https://github.com/tadeck/ssh-matic)上,是为了学习Python而创建的。它基于别人友好的SSH Python接口到Paramiko(代码可在此处访问)。
使用提到的SSH模块连接到服务器并执行命令相当简单:
import ssh
server = ssh.Connection(host='host', username='user', private_key='key_path')
result = server.execute('your command')

基本上你需要的不是PuTTy,而是Python的SSH模块。这个模块应该能在Windows和Linux上都工作。使用我的脚本,你只需要编写你想要调用的命令,并根据你的需要调整代码。
祝你好运。告诉我它是否有帮助。

请问您能否将该模块上传到 PyPi 上吗? - Xbox One
Paramiko的链接已失效。 - Xbox One
你能否包含链接到“...别人的友好SSH Python界面...”? - Xbox One

5
from pywinauto.application import Application
import time

app = Application ().Start (cmd_line=u'putty -ssh user_name@10.70.15.175')
putty = app.PuTTY
putty.Wait ('ready')
time.sleep (1)
putty.TypeKeys ("password")
putty.TypeKeys ("{ENTER}")
time.sleep (1)
putty.TypeKeys ("ls")
putty.TypeKeys ("{ENTER}")

我正在使用Python 2.7。代码在Windows上运行,并连接到远程Linux。它在我的环境中可以正常工作。


1
你能提供一个解决办法,使其等待直到rsync这样的复杂进程结束,然后执行其他命令吗?谢谢。 - Anshuman Banerjee

4
你可以这样做:
# Use plink to open a connection to the remote shell
command = "plink.exe -ssh %s -batch" % credentials
sp = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
# Send commands to the shell as if they were read from a shell script
sp.stdin.write("command1\n")
sp.stdin.write("command2\n")
sp.stdin.close()
# read out the answers, if needed
ans = sp.stdout.read()
sp.wait()    

对于凭据,最好使用已经设置了用户名和SSH密钥的PuTTY连接配置文件名称。


3
您可以使用类似以下代码的方式: command = "plink.exe -ssh 用户名@" + 主机名 + " -pw 密码 -batch \"export DISPLAY='" + 主机名 + "/unix:0.0' ; " 这将使用用户名密码打开到所需主机名的ssh连接。
关机: command += "sudo /sbin/halt\"" 重启: command += "sudo /sbin/reboot\"" 使用与上述相同的方法添加其他命令,
使用以下指令运行命令: pid = subprocess.Popen(command).pid 正如Tadeck指出的那样,这只适用于尝试连接到Linux机器的Windows机器。

当然,你的解决方案完全依赖于平台,只能在连接到Linux/Unix系统的Windows上运行。 - Tadeck
1
确实如此,但这正是原帖作者想要的,也是我最近所做的。 - Serdalis
@Tadeck,谢谢你,我应该提到你说的话,这是我的疏忽,我会添加它以确保正确性。 - Serdalis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接