5

我正在尝试编写一个连接到数据库的 python 脚本,但是只有在您首先通过 SSH 连接到堡垒主机时才能访问该数据库。从命令行,这是我必须做的设置隧道:

$ ssh -i /path/to/my/key/file.pem -A -L 3307:mydb1.fsd23rqr.us-east-1.rds.amazonaws.com:3306 my_ssh_username1@my-bastion-host.without.2fa
[ec2-user@ip-X-X-X-X ~]$ 

我使用这个sshtunnel 库创建了一个 python 脚本来做同样的事情。有用:

#!/usr/bin/env python
from sshtunnel import SSHTunnelForwarder
import MySQLdb as db
import pandas as pd

print('\nAbout to try connecting')
with SSHTunnelForwarder(
    ('my-ssh-host.without.2fa', 22),
    ssh_username='my_ssh_username1',
    ssh_pkey='/path/to/my/key/file.pem',
    remote_bind_address=('mydb1.fsd23rqr.us-east-1.rds.amazonaws.com', 3306),
    local_bind_address=('0.0.0.0', 3307)
) as tunnel:
    print "Connection Established"
    print pd.read_sql_query(
        "select 'Hello' from dual",
        db.connect(
            host='127.0.0.1',
            port=tunnel.local_bind_port,
            user='my_db_username1',
            passwd='****************',
            db='my_db_instance_1'
        )
    )

产生:

About to try connecting
Connection Established
   Hello
0  Hello

但现在我需要使用不同的数据库和堡垒组合。这个堡垒具有 2 因素身份验证 (2FA) 设置,因此当我 ssh 到它时,它会询问我选择哪种 2FA 方法。如果我选择方法 #1,它会向我的 android 手机发送一个推送通知,我必须批准:

$ ssh -i /path/to/my/key/rsa -A -L 3307:mydb2.fsd23rqr.us-east-1.rds.amazonaws.com:3306 my_ssh_username2@my-bash-host.with.2fa
Duo two-factor login for my_ssh_username2

Enter a passcode or select one of the following options:

 1. Duo Push to XXX-XXX-9671
 2. Phone call to XXX-XXX-9671
 3. SMS passcodes to XXX-XXX-9671 (next code starts with: 1)


Passcode or option (1-3): 1

<WAIT FOR ME TO CLICK APPROVE ON MY ANDROID>

Success. Logging you in...
[my_ssh_username2@ip-X-X-X-1X ~]$

但是,当我尝试使用 sshtunnel 以与启用 2FA 的堡垒完全相同的方式设置隧道时,它会失败:

About to try connecting
Connection Established
Enter DB password:
2018-08-29 15:31:43,985| ERROR   | Could not establish connection from ('127.0.0.1', 3307) to remote side of the tunnel
Traceback (most recent call last):
  <stack-trace snipped>
  File "python2.7/site-packages/MySQLdb/__init__.py", line 81, in Connect
    return Connection(*args, **kwargs)
  File "python2.7/site-packages/MySQLdb/connections.py", line 193, in __init__
    super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2013, "Lost connection to MySQL server at 'reading initial communication packet', system error: 0")

如果 SSH 到该主机需要 2FA,我如何编写 python 脚本通过 SSH 隧道连接到 Mysql DB?

4

1 回答 1

0

您需要设置交互式 SSH 会话才能输入启用 2fa 的服务器提供的选项。简要看一下sshtunnel库的代码 - 似乎他们使用paramiko 连接到网关以及设置隧道。实现这两种方法的方法都没有tty为用户输入提供交互的选项。

例如,执行网关连接的方法是这样说的:

def _connect_to_gateway(self):
    Open connection to SSH gateway
     - First try with all keys loaded from an SSH agent (if allowed)
     - Then with those passed directly or read from ~/.ssh/config
     - As last resort, try with a provided password

如您所见,这里没有执行交互式 ssh 会话命令的选项。

因此,您可以选择扩展代码paramiko来设置交互式会话,或者编写自己的代码paramiko来管理网关连接和隧道设置。例如,paramiko提供此示例来执行交互式会话。

于 2018-09-04T03:52:01.683 回答