【发布时间】:2017-12-01 20:26:44
【问题描述】:
我正在尝试使用 Python 设置反向 SSH 隧道。一些随系统启动的软件会根据它收到的命令来管理它并杀死它或启动它。
我写了一个类来管理反向隧道,如下所示:
# imports omitted for brevity
class SshProcess():
def __init__(self):
self.process = None
def start(self, port):
if self.process is not None:
return None
command = [
# 'sudo',
'ssh',
'-R {port}:127.0.0.1:22'.format(port=port),
'{username}@{host}'.format(username=config.USERNAME, host=config.HOST),
'-o StrictHostKeyChecking=no'
]
def threaded_popen():
self.process = subprocess.Popen(
(' '.join(command)), # command, # shlex.split(command),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True
)
self.process.wait()
logger.info('Reverse SSH to {username}@{host} has exited'.format(username=config.USERNAME, host=config.HOST))
logger.debug('command raw: {command}'.format(command=command))
logger.debug('command joined: {command}'.format(command=(' '.join(command))))
self.thread = Thread(target=threaded_popen)
self.thread.start()
def stop(self):
if self.process is not None:
try:
self.process.communicate(input="exit\n")
self.process.terminate()
except (ValueError, OSError) as e:
logger.warning('Closing reverse SSH raised {error}'.format(error=e.__class__.__name__))
logger.warning(e)
self.process = None
if self.thread is not None:
self.thread.join()
现在每当我调用 start 时,我都会收到以下日志语句:
2017-06-28 14:32:46,343 - module - DEBUG - command raw: ['ssh', '-R 4000:127.0.0.1:22', 'tich@192.168.0.88', '-o StrictHostKeyChecking=no']
2017-06-28 14:32:46,344 - module - DEBUG - command joined: ssh -R 4000:127.0.0.1:22 tich@192.168.0.88 -o StrictHostKeyChecking=no
2017-06-28 14:32:46,797 - module - INFO - Reverse SSH to tich@192.168.0.88 has exited
问题是 ssh 隧道在启动后几乎立即退出。在 Linux 中执行一个简单的pidof ssh 不会产生任何输出,就好像该进程甚至不存在一样。
我也尝试过在启动进程后使用communicate(),你可以看到它建立了连接并接收了输出。然而,在函数退出后不久,子进程也会退出。
我已经为 root 用户和普通用户设置了 RSA 密钥对。将命令复制并粘贴到终端不会产生即时退出错误。
目的是设置反向 SSH 会话,以便远程用户可以登录。但我目前还没有找到提供此功能的现有打包解决方案。
【问题讨论】:
-
使用 paramiko:paramiko.org
-
考虑 paramiko,查看文档,它似乎没有在任何地方提供反向选项。这意味着目标服务器无法 ssh 回源服务器。
标签: python linux ssh subprocess