繁体   English   中英

如何在python中关闭ssh隧道

[英]How to close an ssh tunnel in python

我正在编写一个使用 ssh 隧道访问远程 Mysql 数据库的 Python 应用程序。 我设置了隧道

os.system("ssh -fNg -L 3306:127.0.0.1:3306 username@host")

一切正常。 问题是:

关闭ssh隧道的python代码是什么?

谢谢

os.system('exit') 不起作用

创建隧道的进程仍然在后台运行

>>> command = 'ssh -fNg vagrant@localhost -p2222 -L 8000:localhost:8000'
>>> os.system(command)
>>> os.system('exit')

ps -A | grep ssh
7144 ??         0:00.04 ssh -fNg vagrant@localhost -p2222 -L 8000:localhost:8000

这表明进程仍在运行并且隧道仍在工作,并且os.system不返回进程 ID,因此我们可以使用它来终止进程(它返回退出代码)

使用子进程返回进程的句柄

import subprocess
proc = subprocess.Popen(command, shell=True)
proc.terminate() # this terminates the process
  • 其正确的 sys.exit() 将不存在脚本并保持隧道打开。
  • 下面是我如何使用 Python 关闭 SSH 隧道,进而允许我终止 Python 脚本。
  • 在我的关闭函数中,我传递了我创建的隧道连接:
def close(self, tunnel = None): if tunnel is not None: # close tunnel connection. tunnel.close()
  • 我使用 Paramiko 创建了 SSH 连接作为
def connect(params): # Create an SSH tunnel tunnel = SSHTunnelForwarder( (params['ssh_ip_address'], int(params['ssh_port'])), ssh_username=params['ssh_username'], ssh_private_key=params['ssh_key'], ssh_private_key_password=params['ssh_key_file_password'], remote_bind_address=('localhost', int(params['ssh_remote_forward_port'])), local_bind_address=('localhost',int(params['ssh_local_forward_port'])) tunnel.start() return tunnel

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM