我想运行一个tail -f logfile
使用 python 的 paramiko 模块在远程计算机上运行命令。到目前为止,我一直在尝试以下方式:
interface = paramiko.SSHClient()
#snip the connection setup portion
stdin, stdout, stderr = interface.exec_command("tail -f logfile")
#snip into threaded loop
print stdout.readline()
我希望该命令能够根据需要运行,但我有两个问题:
- 我怎样才能干净地阻止这个?我想制作一个频道然后使用
shutdown()
当我完成后在频道上发出命令 - 但这看起来很混乱。是否可以做类似发送的事情Ctrl-C
到频道的标准输入?
-
readline()
块,如果我有一种非阻塞的获取输出的方法,我可以避免线程 - 有什么想法吗?
不要在客户端调用 exec_command,而是掌握传输并生成您自己的通道。这channel http://www.lag.net/paramiko/docs/paramiko.Channel-class.html可用于执行命令,您可以在 select 语句中使用它来确定何时可以读取数据:
#!/usr/bin/env python
import paramiko
import select
client = paramiko.SSHClient()
client.load_system_host_keys()
client.connect('host.example.com')
transport = client.get_transport()
channel = transport.open_session()
channel.exec_command("tail -f /var/log/everything/current")
while True:
rl, wl, xl = select.select([channel],[],[],0.0)
if len(rl) > 0:
# Must be stdout
print channel.recv(1024)
通道对象可以读取和写入,与远程命令的 stdout 和 stdin 连接。您可以通过调用来获取 stderrchannel.makefile_stderr(...)
.
我已将超时设置为0.0
秒,因为请求了非阻塞解决方案。根据您的需要,您可能希望使用非零超时进行阻止。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)