正确使用SSHTunnel

时间:2016-11-04 15:54:51

标签: python ssh-tunnel pymysql

我试图在python2.7中使用pymysqlsshtunnel来隧道连接,以便我可以连接到只能通过堡垒服务器访问的mysql实例。堡垒服务器的主机名为BASTIONIP,该服务器可以毫无问题地连接到MYSQLHOST。但是,python似乎无法通过隧道连接。以下是我的代码:

    with sshtunnel.SSHTunnelForwarder(
            (BASTIONIP, 22),
            ssh_username='dataengineer',
            ssh_pkey="/Users/USERNAME/.ssh/id_rsa",
            remote_bind_address=(MYSQLHOST, 3306),
            local_bind_address=(MYSQLHOST, 3306)
    ) as tunnel:
        self.DB = {'con': pymysql.connect(host=MYSQLHOST,
                                          user=USERNAME,
                                          passwd=PASSWORD,
                                          db=DBNAME,
                                          port=tunnel.local_bind_port,
                                          charset='utf8',
                                          autocommit=True)}
        self.DB['cursor'] = self.DB['con'].cursor(pymysql.cursors.DictCursor)

但是,当我尝试连接时,我收到以下错误:

  File "/Library/Python/2.7/site-packages/sshtunnel.py", line 1378, in _get_local_interfaces
    local_if = socket.gethostbyname_ex(socket.gethostname())[-1]
gaierror: [Errno 8] nodename nor servname provided, or not known

有谁可以指出我做错了什么?

2 个答案:

答案 0 :(得分:0)

下面提到我在谷歌搜索之后可能弄清楚的可能原因:

  1. 不确定,这是由_get_local_interfaces尝试解析本地主机名失败(可能只是一个糟糕的/ etc / hosts文件或其他东西)引起的。
  2. 尝试以root /etc/hosts文件打开,并添加如下所示的行

    # IP ADDR      HOSTNAME
    192.168.1.1    your_desired_hostname
    

    并且名称应该解决。 使用您的IP地址更新192.168.1.1Here

    1. 另一项决议案: 替换:
    2. local_if = socket.gethostbyname_ex(socket.gethostname())[-1]

        try:
          local_if = socket.gethostbyname_ex(socket.gethostname())[-1]
      except:
          local_if = []
      

      Here

答案 1 :(得分:0)

像魅力一样工作。

In [1]: from sshtunnel import SSHTunnelForwarder
   ...:     ...: 
   ...:     ...: with SSHTunnelForwarder(
   ...:     ...:     ('xx.xx.xx.xx', 22),
   ...:     ...:     ssh_username='deploy',
   ...:     ...:     ssh_pkey='~/.ssh/id_rsa',
   ...:     ...:     remote_bind_address=('127.0.0.1', 3306),
   ...:     ...:     local_bind_address=('0.0.0.0', 3307)
   ...:     ...: ) as tunnel:
   ...:     ...:     print('pass')
   ...: 
   ...:     
pass