我需要在后台使用 python 执行命令 ssh -NTf -R 5000:localhost:22 server@ip
。由于选项 -f
,我知道命令本身在后台运行。
我已经使用 python 子进程包来执行此操作。
cm="ssh -NTf -o ExitOnForwardFailure=yes -o ConnectTimeout=10 -R 5000:localhost:22 servermc@122.174.345.9"
try:
out=sp.check_output(cm,stderr=sp.STDOUT,shell=True)
except Exception as e:
print "ddddd",e.output
但是发生的是进程仍然在前台。当我们运行上面的 python 代码时,执行在 check_output 命令处暂停,我需要按 ctrl+c
退出 python 代码。
我还尝试了 Popen 和 poll() 函数。使用这些功能,我可以实现所需的功能,但问题是如果发生任何错误(如端口未空闲或 IP 地址错误),我将无法获取状态。
我需要做的是我想使用 python 在后台运行 ssh 反向隧道,并且我还需要从服务器端获取它是否运行成功的状态?
我只能访问服务器,上面的脚本将在客户端运行。因此我可以通过服务器访问客户端。如果客户端运行这个脚本,状态将被发送到云端,这样我就可以验证状态并从服务器连接到客户端。
最佳答案
“背景”纯粹是一个 shell 概念:您可能想要生成一个新进程。subprocess.Popen()
仅在 python 脚本中没有任何内容依赖于输出的情况下运行一个进程正在运行的命令。
例子:
import subprocess
subprocess.Popen(["ls","-lha","/"])
如果要检查某个进程的错误或信息,一种方法是查看该进程的日志。
您可以在 ssh 命令上使用 -E
参数并将调试日志附加到日志文件:
ssh -NTf -o ExitOnForwardFailure=yes -o ConnectTimeout=10 -R 5000:localhost:22 servermc@x.x.x.x -E /tmp/ssh.log
在使用 subprocess.Popen()
执行 ssh 命令后,您可以不间断地检查日志文件是否有任何错误。
Using shell=True can be a security hazard.
更新 1:我脚本中的 result
变量与您脚本中的 out
变量完全相同。并且脚本不会停留在 Popen
#!/usr/bin/python
import shlex
from subprocess import Popen, PIPE
import time
tmp_file = "/tmp/ssh.log" #temp log file address
cmd="ssh -NTf -o ExitOnForwardFailure=yes -o ConnectTimeout=10 -R 5000:localhost:22 servermc@x.x.x.x -E "+tmp_file #command to execute
def executor(command):
try:
file = open(tmp_file,"w+") #create or truncates the log file if exist
p = Popen(shlex.split(command), stdin=PIPE, stdout=PIPE, stderr=PIPE) #execute the command
p.wait()
content = file.read().strip()
file.close()
return content
except Exception as e:
return e
result = executor(cmd)
print (result)
关于linux - 如何使用python在后台运行ssh反向隧道?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57809991/