在 python 中执行时 autossh 不工作

autossh not working when executed in python

我正在尝试创建 ssh 反向隧道。当我 运行 在终端上执行以下命令时,它的效果很好:

autossh -M 10876 -N -f -o PubkeyAuthentication=yes -o PasswordAuthentication=no -i /root/.ssh/id_rsa -R 6666:localhost:22 root@**.**.**.** -p 2233

但是当我 运行 在 python 中使用 os.system() 或使用 subprocess 时它不起作用。当我检查进程列表时,进程已创建并且 运行ning 与上一种方法没有区别。(运行ning 直接在终端中)

python代码:

command ='autossh -M 10876 -N -f -o PubkeyAuthentication=yes -o PasswordAuthentication=no -i /root/.ssh/id_rsa -R 6666:localhost:22 root@**.**.**.** -p 2233'
proc = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE, shell=True)

知道有什么问题吗?

当您使用 shell=True 时,您不想在命令参数上使用 shlex.split()...它应该只是一个字符串。

由于您将 args 作为序列传递给 Popen,因此第一个 arg (autossh) 用作命令,其余的 args 实际上传递给 shell,不要autossh.

所以...您可以删除 shell=True,或者通过删除 shlex.split().

的使用将参数作为字符串传递

https://docs.python.org/2/library/subprocess.html#subprocess.Popen

它在 Windows10 中对我有用(在 cygwin 中使用 autossh,Python 3.6) port = 6379; command = f'autossh -M 1{port} -N -f -C -L {port}:localhost:{port} root@acone2'; proc = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE, shell=True)