使用Python使用SSH隧道连接到远程数据库

时间:2017-03-06 09:30:26

标签: python python-2.7 ssh mysql-python ssh-tunnel

我正在尝试使用SSH隧道连接到远程数据库但是我收到错误。我不确定到底出了什么问题,因为当我从命令行创建ssh隧道时,我能够访问数据库,但是同样不能从python中运行。

创建ssh tunner的命令,工作正常。

ssh -L 30080:phpmyadmin-www:80 root@host

但是,以下代码无效。

def __init__(self, host="127.0.0.1", user="root", password="pass", db="database"):
    sshtunnel.DEFAULT_LOGLEVEL = logging.DEBUG
    with SSHTunnelForwarder(
            ('hubif-delphi-dev.qa-egnyte.com', 22),
            ssh_private_key="/home/egnyte/.ssh/id_rsa",
            ssh_username="root",
            remote_bind_address=('host', 80),
            local_bind_address=('127.0.0.1', 30080)) as server:
        print "successfully connected to ssh"
        con = MySQLdb.connect(user=user, passwd=password, db=db, host='127.0.0.1', port=server.local_bind_port)
        self.cur = con.cursor()

我在尝试创建MySQL连接时遇到以下错误。

2017-03-06 10:20:23,509| ERROR   | Secsh channel 0 open FAILED: Connection refused: Connect failed
2017-03-06 10:20:23,509| ERROR   | Could not establish connection from ('127.0.0.1', 30080) to remote side of the tunnel
---------------------------------------- Stacktrace removed ----------------------------------------
   super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2013, "Lost connection to MySQL server at 'reading initial communication packet', system error: 0")

0 个答案:

没有答案
相关问题