进程终止,如果它是 运行 通过 paramiko ssh 会话并且最后带有“&”

Process dies, if it is run via paramiko ssh session and with "&" in the end

我只想 运行 tcpdump 在后台使用 paramiko。

代码部分如下:

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=login, password=password)
transport = ssh.get_transport()
channel = transport.open_session()
channel.get_pty()
channel.set_combine_stderr(True)

cmd = "(nohup tcpdump -i eth1  port 443 -w /tmp/dump20150317183305940107.pcap) &"
channel.exec_command(cmd)
status = channel.recv_exit_status()

我执行这段代码后,pgrep tcpdump returns什么也没有。

如果我正确删除 & 符号 tcpdump 运行,但是我的 ssh shell 被阻止了。

如何才能在后台正确运行tcpdump

我试过什么命令:

cmd = 'nohup tcpdump -i eth1  port 443 -w /tmp/dump20150317183305940107.pcap &\n'
cmd = "screen -d -m 'tcpdump -i eth1  port 443 -w /tmp/dump20150317183305940107.pcap'"
cmd = 'nohup sleep 5 && echo $(date) >> "test.log" &'

使用 & 可以使远程命令立即退出。因此,远程 sshd 可能(取决于实现,但 openssh 会)终止所有从您的命令调用启动的进程。在您的情况下,您只是生成一个新进程 nohup tcpdump,由于最后 &,该进程将立即 return。 channel.recv_exit_status() 只会阻塞,直到 & 操作的退出代码准备就绪,即刻准备就绪。然后您的代码就会终止,终止您的 ssh 会话,这将使远程 sshd 杀死生成的 nohup tcpdump 进程。这就是为什么你最终没有 tcpdump 进程。

您可以执行以下操作:

由于 exec_command 将为您的命令生成一个新线程,您可以将其保持打开状态并继续执行其他任务。但是请确保不时清空缓冲区(对于冗长的远程命令)以防止 paramiko 停滞。

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=login, password=password)
transport = ssh.get_transport()
channel_tcpdump = transport.open_session()
channel_tcpdump.get_pty()
channel_tcpdump.set_combine_stderr(True)

cmd = "tcpdump -i eth1  port 443 -w /tmp/dump20150317183305940107.pcap"        # command will never exit
channel_tcpdump.exec_command(cmd)  # will return instantly due to new thread being spawned.
# do something else
time.sleep(15)      # wait 15 seconds
_,stdout,_ = ssh.exec_command("pgrep tcpdump") # or explicitly pkill tcpdump
print stdout.read()     # other command, different shell
channel_tcpdump.close()     # close channel and let remote side terminate your proc.
time.sleep(10)

只需要添加一个睡眠命令,

cmd = "(nohup tcpdump -i eth1  port 443 -w /tmp/dump20150317183305940107.pcap) &"  

改为

cmd = "(nohup tcpdump -i eth1  port 443 -w /tmp/dump20150317183305940107.pcap) &; sleep 1"