我正在编写一个使用 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
关于python - 如何在 python 中关闭 ssh 隧道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31354794/