我尝试使用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()
现在每当我打电话开始时,我都会收到以下日志声明:
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会话,以便远程用户可以登录。但我目前还没有找到提供此功能的现有打包解决方案。
答案 0 :(得分:0)
你做了一些奇怪的ssh连接。我的建议是使用paramiko一个很棒的ssh包。 另一方面,你只是为了一个linux commamd进行子处理,所以如果你喜欢它,请使用: 安装sshpass(yum install或apt-get) sshpass -p your_password ssh user @ hostname
并更改此设置,而不是发送的标志: 更改ssh_config vi / etc / ssh / ssh_config 将以下密钥从“ask”更改为“no”
StrictHostKeyChecking no