连接到PuTTY并输入几个命令
我想连接到Putty,并想做几个步骤:
- 登录到Putty
- 输入几个命令来关闭服务器
- 进入特定的路径
- 从目录中删除文件
- 再次启动服务器
我需要在Windows上写代码,但我的服务器在Linux上。 我该怎么做呢? 提前谢谢你!
4 个回答
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()
关于credentials
,最好是使用一个已经设置好用户名和SSH密钥的PuTTY连接配置文件的名字。
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系统。在我的环境中,这一切都正常工作。
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上都能用。使用我的脚本,你只需要关注你想要执行的命令,并根据自己的需求调整代码。
祝你好运。如果有帮助,请告诉我。