在 Python 中创建和维护多个 ssh 会话 [英] Create and maintain several ssh sessions in Python

查看:52
本文介绍了在 Python 中创建和维护多个 ssh 会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一旦我的程序启动,它就会打开任意数量的 ssh 会话(用户定义)并无限期地在服务器上运行特定命令(当真正循环时)或直到用户退出.出于效率原因,我只想创建每个会话一次,然后能够运行命令直到用户退出.

Once my program has been launched, it opens any number of ssh sessions (user defined) and runs specific commands on the servers indefinitely (while true loop) or until the user quits. For efficiency reasons I want to create each session only once, then be able to run the commands until the user quits.

我怎样才能在 python 中做到这一点?我在另一篇文章中遇到了一个很酷的方法,该方法使用 subprocess 来运行命令并捕获其 STDOUT.如何先启动会话,然后运行循环命令?

How can I do this in python? I ran across a cool method in another post which used subprocess to run a command and capture its STDOUT. How can I first initiate the session, then run looped commands?

任何指向 Python 中类似进程的东西的链接也将不胜感激.这是我的第一个 python 应用程序.

Any links to process-like stuff in Python would also be appreciated. This is my first python application.

推荐答案

暂时忽略 Python,你可以通过添加这个来复用 ssh 会话

Ignoring Python for the moment, you can multiplex ssh sessions by adding this

ControlMaster auto
ControlPath /tmp/ssh_mux_%h_%p_%r
ControlPersist 1h

到你的 ~/.ssh/config 文件.连接到一台机器一次后,到这台机器的 ssh 会话将保持打开状态,之后的命令将在这台机器上几乎立即执行.然后,您可以使用 Python 子进程调用 ssh 并根据需要在该机器上执行命令,会话将被重用,而无需执行任何特殊操作.

to your ~/.ssh/config file. After connecting to a machine once, the ssh session to this machine will stay open, and subsequent commands will execute on this machine near-instantaneously thereafter. You could then use Python subprocess to call ssh and execute commands on that machine as-needed, and the session will be reused without having to do anything special.

如果您不想让会话多路复用默认行为(或者您'正在为可能没有将其作为默认设置的其他用户进行部署).

You could also call ssh with the -F flag pointing to an alternate config file, if you'd rather not make the session multiplexing the default behavior (or you're deploying for other users who might not have it as their default).

这篇关于在 Python 中创建和维护多个 ssh 会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆