Python 脚本 - 连接到 SSH 并运行命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4896785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python script - connect to SSH and run command
提问by Ilias
I already know there are ssh modules for Python, that's not for what I'm looking for. What I want to have is an python script to do the following:
我已经知道 Python 有 ssh 模块,这不是我要找的。我想要的是一个 python 脚本来执行以下操作:
- > connect to an [ input by user ] SSH host
- > connect using the credentials [ provided by the user ]
- > run command on the SSH host [ telnet to [host - input by user ]
- > Select menu item in the telnet session
- > 连接到 [ 用户输入 ] SSH 主机
- > 使用凭据 [ 由用户提供 ] 进行连接
- > 在 SSH 主机上运行命令 [telnet 到 [主机 - 用户输入]
- > 在 telnet 会话中选择菜单项
Thanks in advance,
提前致谢,
Best regards,
此致,
采纳答案by ismail
Use paramiko, see http://jessenoller.com/2009/02/05/ssh-programming-with-paramiko-completely-different/for a through example of using it.
使用paramiko,请参阅http://jessenoller.com/2009/02/05/ssh-programming-with-paramiko-completely-different/以获取使用它的完整示例。
回答by Vlad H
回答by ThiefMaster
Use paramikoor the libssh2 python bindings.
回答by Vikas Gupta
There are many libraries to do that.
有很多图书馆可以做到这一点。
- Subprocess
- Pexpect
- Paramiko (Mostly used)
- Fabric
- Exscript
- 子进程
- 期待
- Paramiko(最常用)
- 织物
- 说明
You can check their documentation for the implementation.
您可以查看他们的文档以了解实施情况。
回答by Shawn
You can use the vassalpackage, which is exactly designed for this.
您可以使用专为此设计的vassal包。
All you need is to install vassal and do
您只需要安装 vassal 并执行
from vassal.terminal import Terminal
shell = Terminal(["ssh username@host", "cd scripts", "python foo1.py", "python foo2.py"])
shell.run()
This will run the command once every second, and you can make it run faster to change sec=0.1.
这将每秒运行一次命令,您可以通过更改 sec=0.1 使其运行得更快。

