如何使用python打开SSH隧道?

the*_*row 4 python django ssh-tunnel

我正在尝试使用django连接到远程mysql数据库.
该文档指定首先需要打开SSH隧道才能连接到数据库.
是否有一个python库可以在设置某些设置时打开SSH隧道?

Vin*_*jip 7

你可以尝试paramiko前进功能.有关paramiko概述,请参见此处.


Kar*_*bat 5

这是Python3的代码片段(但你应该可以毫不费力地将它改装成Python2).它在一个单独的线程中运行SSH隧道; 然后主线程通过SSH隧道获取网络流量.

在此示例中,ssh隧道将本地端口2222转发到localhost上的端口80.主要活动包括跑步

curl http://localhost:2222
Run Code Online (Sandbox Code Playgroud)

即,从端口2222获取网页.

SshTunnel类初始化为4个参数,本地和远程端口,远程用户和远程主机.它只是以下列方式启动SSH:

ssh -N -L localport:remotehost:remoteport remoteuser@remotehost
Run Code Online (Sandbox Code Playgroud)

为了使这项工作,你需要一个无密码登录remoteuser @ remotehost(通过远程服务器上已知的〜/ .ssh/id_rsa.pub).这样运行的ssh隧道在一个线程上; 主要任务必须是另一个.ssh隧道线程被标记为守护进程,因此一旦主活动终止,它将自动停止.

我没有提供完整的MySQL连接示例,因为它应该是不言自明的.一旦SshTunnel设置了本地TCP端口,您就可以连接到它 - 无论是通过MySQL客户端,卷曲还是其他任何东西.

import subprocess
import time
import threading

class SshTunnel(threading.Thread):
    def __init__(self, localport, remoteport, remoteuser, remotehost):
        threading.Thread.__init__(self)
        self.localport = localport      # Local port to listen to
        self.remoteport = remoteport    # Remote port on remotehost
        self.remoteuser = remoteuser    # Remote user on remotehost
        self.remotehost = remotehost    # What host do we send traffic to
        self.daemon = True              # So that thread will exit when
                                        # main non-daemon thread finishes

    def run(self):
        if subprocess.call([
            'ssh', '-N',
                   '-L', str(self.localport) + ':' + self.remotehost + ':' + str(self.remoteport),
                   self.remoteuser + '@' + self.remotehost ]):
            raise Exception ('ssh tunnel setup failed')


if __name__ == '__main__':
    tunnel = SshTunnel(2222, 80, 'karel', 'localhost')
    tunnel.start()
    time.sleep(1)
    subprocess.call(['curl', 'http://localhost:2222'])
Run Code Online (Sandbox Code Playgroud)


pah*_*haz 5

尝试使用sshtunnel 包

这很简单:

pip install sshtunnel
python -m sshtunnel -U vagrant -P vagrant -L :3306 -R 127.0.0.1:3306 -p 2222 localhost
Run Code Online (Sandbox Code Playgroud)

披露:我是这个包的作者和维护者。