python subprocess.Popen和ssh端口在后台转发 [英] python subprocess.Popen and ssh port forwarding in the background
问题描述
我需要具有可以从本质上模拟用户创建使用ssh进行压缩的端口的功能.因此,基本上应该这样工作:
-执行ssh -f -N -L 10000:gateway:11000 localhost
-如果该命令有输出,则向用户显示并泵送用户输入作为响应
- 结束
我在下面提供的代码几乎可以满足我的需求:
I need to have functionality that would essentially emulate user creating a port forwrding with ssh. So, essentially that should work like that:
- execute ssh -f -N -L 10000:gateway:11000 localhost
- if there is an output from that command, show to the user and pump user's input as a response
- finish
The code I came up with below, almost does what I need:
ssh_proc = Popen(['ssh', '-f', '-N', '-L', '10000:gateway:11000', 'localhost'], stdin=PIPE, stdout=PIPE)
stdoutdata, stderrdata = ssh_proc.communicate()
但是问题是它永远不会完成.我看到命令已执行,转发隧道已创建,但communication()仍然卡住.我可以使用Ctrl + C打破这一点,并得到这个:
But the problem is it never finishes. I see the command is executed and forwarding tunnel is created but communicate() is still stuck. I can break out of that with Ctrl+C and get this:
^CTraceback (most recent call last):
File "sshman.py", line 278, in <module>
add(args.remote_host, args.remote_port, args.local_port, args.local_host)
File "sshman.py", line 125, in add
stdoutdata, stderrdata = ssh_proc.communicate()
File "/usr/lib64/python2.7/subprocess.py", line 740, in communicate
return self._communicate(input)
File "/usr/lib64/python2.7/subprocess.py", line 1256, in _communicate
stdout, stderr = self._communicate_with_poll(input)
File "/usr/lib64/python2.7/subprocess.py", line 1310, in _communicate_with_poll
ready = poller.poll()
KeyboardInterrupt
由于我将-f与ssh命令一起使用,因此它应该分叉连接.完成后是否可以中断通讯(),或者有更优雅的解决方案?
Since i use -f with ssh command, it should fork the connection. Is there a way to interrupt communicate() when it is done or is there more elegant solution?
在此先感谢您的任何建议/建议/意见.
Thank you in advance for any advices/suggestions/comments.
推荐答案
我认为解决方案非常简单
I guess the solution was pretty easy
ssh_proc = Popen(['ssh', '-f', '-N', '-L', '10000:gateway:11000', 'localhost'], stdin=PIPE, stdout=PIPE)
stat = ssh_proc.poll()
while stat == None:
stat = ssh_proc.poll()
这篇关于python subprocess.Popen和ssh端口在后台转发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!