使用 Paramiko 一次创建多个 SSH 连接
下面的代码通过 SSH 在一台机器上运行 grep 并打印结果:
import sys, os, string
import paramiko
cmd = "grep -h 'king' /opt/data/horror_20100810*"
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('10.10.3.10', username='xy', password='xy')
stdin, stdout, stderr = ssh.exec_command(cmd)
stdin.write('xy\n')
stdin.flush()
print stdout.readlines()
如何同时 grep 五台机器(这样我就不会出现重大延迟),然后将所有内容放入五个变量中并将它们全部打印出来。
The code below runs grep in one machine through SSH and prints the results:
import sys, os, string
import paramiko
cmd = "grep -h 'king' /opt/data/horror_20100810*"
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('10.10.3.10', username='xy', password='xy')
stdin, stdout, stderr = ssh.exec_command(cmd)
stdin.write('xy\n')
stdin.flush()
print stdout.readlines()
How can I grep five machines all at once (so that I don't have major delay), than put all that in five variables and print them all out.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要将调用放入单独的线程(或进程,但这会太过分),这反过来又要求代码位于函数中(无论如何,这是一个好主意:模块顶部没有大量代码等级)。
例如:
如果您有超过五个主机,我建议使用“线程池”架构和工作单元队列。但是,对于只有五个,坚持“专用线程”模型会更简单(特别是因为标准库中没有线程池,所以您需要像 threadpool...或者您自己的许多微妙的自定义代码;-)。
You'll need to put the calls into separate threads (or processes, but that would be overkill) which in turn requires the code to be in a function (which is a good idea anyway: don't have substantial code at a module's top level).
For example:
If you had many more than five hosts, I would recommend using instead a "thread pool" architecture and a queue of work units. But, for just five, it's simpler to stick to the "dedicated thread" model (especially since there is no thread pool in the standard library, so you'd need a third party package like threadpool... or a lot of subtle custom code of your own of course;-).
就我而言,我必须在具有一个 ip 和端口的服务器上执行命令,完成后需要对其他 ip 和不同端口执行 sftp。条件是由于端口转发,在对另一个 ip 执行 sftp 时一个连接应该处于活动状态。
两个连接都可以单独工作,但是在组合两个连接时,第二个 sftp 连接无法工作。
In my case i have to execute commands on server with one ip and port and after complete need to do sftp to other ip and different port.Condition is one connection should be live while doing sftp to another ip due to port forwarding.
Both connection are working separably but while combining both second sftp connection is not working.