我想连接到putty,并想要执行以下几个步骤:
- 登录Putty
- 键入一些命令以关闭服务器
- 遍历到特定路径
- 从目录中删除文件
- 重新启动服务器
我需要在Windows中编写代码。但我的服务器在Linux上。 我应该如何继续? 提前致谢。
import ssh
server = ssh.Connection(host='host', username='user', private_key='key_path')
result = server.execute('your command')
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。它在我的环境中可以正常工作。
# 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连接配置文件名称。
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机器。