如何在python中使用paramiko发送控制信号? [英] How to send control signals using paramiko in python?
问题描述
我有一个类似这样的代码片段:
I have a code snippet something like this:
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port=Port, username=usr,password=Psw)
stdin, stdout, stderr= ssh.exec_command("watch -n1 ps")
print stdout.read(),stderr.read()
这里的问题是我必须运行 watch
或任何无限运行的命令 10 秒,然后我应该发送 SIGINT
(Ctrl + c) 并打印状态.
The problem here is I have to run watch
or any infinitely running command for 10 seconds and after that I should send SIGINT
(Ctrl + c) and print the status.
我该怎么做?
推荐答案
解决此问题的一种方法是打开您自己的会话、伪终端,然后使用 recv_ready 以非阻塞方式读取()
知道什么时候读.10 秒后,您发送 ^C
(0x03) 以终止正在运行的进程,然后关闭会话.由于您无论如何都要关闭会话,因此发送 ^C
是可选的,但如果您想让会话保持活动状态并多次运行命令,它可能很有用.
One way to get around this would be to open your own session, pseudo-terminal, and then read in a non-blocking fashion, using recv_ready()
to know when to read. After 10 seconds, you send ^C
(0x03) to terminate the running process and then close the session. Since you're closing the session anyway, sending ^C
is optional, but it may be useful if you want to keep the session alive and run commands multiple times.
import paramiko
import time
import sys
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, port=Port, username=usr,password=Psw)
transport = ssh.get_transport()
session = transport.open_session()
session.setblocking(0) # Set to non-blocking mode
session.get_pty()
session.invoke_shell()
# Send command
session.send('watch -n1 ps\n')
# Loop for 10 seconds
start = time.time()
while time.time() - start < 10:
if session.recv_ready():
data = session.recv(512)
sys.stdout.write(data)
sys.stdout.flush() # Flushing is important!
time.sleep(0.001) # Yield CPU so we don't take up 100% usage...
# After 10 seconds, send ^C and then close
session.send('\x03')
session.close()
print
这篇关于如何在python中使用paramiko发送控制信号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!