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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 18:00:56  来源:igfitidea点击:

Python script - connect to SSH and run command

pythonautomationsshtelnet

提问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 脚本来执行以下操作:

  1. > connect to an [ input by user ] SSH host
  2. > connect using the credentials [ provided by the user ]
  3. > run command on the SSH host [ telnet to [host - input by user ]
  4. > Select menu item in the telnet session
  1. > 连接到 [ 用户输入 ] SSH 主机
  2. > 使用凭据 [ 由用户提供 ] 进行连接
  3. > 在 SSH 主机上运行命令 [telnet 到 [主机 - 用户输入]
  4. > 在 telnet 会话中选择菜单项

Thanks in advance,

提前致谢,

Best regards,

此致,

回答by Vlad H

If you're actually looking for a module that lets you automate CLI interaction, there's pexpect

如果您实际上正在寻找一个可以让您自动执行 CLI 交互的模块,那么pexpect

回答by ThiefMaster

回答by linbo

now the popular solution is Fabric

现在流行的解决方案是Fabric

回答by Vikas Gupta

There are many libraries to do that.

有很多图书馆可以做到这一点。

  1. Subprocess
  2. Pexpect
  3. Paramiko (Mostly used)
  4. Fabric
  5. Exscript
  1. 子进程
  2. 期待
  3. Paramiko(最常用)
  4. 织物
  5. 说明

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 使其运行得更快。