[英]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代码是什么?
谢谢
创建隧道的进程仍然在后台运行
>>> 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
def close(self, tunnel = None): if tunnel is not None: # close tunnel connection. tunnel.close()
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.