我试图在python2.7中使用pymysql
和sshtunnel
来隧道连接,以便我可以连接到只能通过堡垒服务器访问的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
有谁可以指出我做错了什么?
答案 0 :(得分:0)
下面提到我在谷歌搜索之后可能弄清楚的可能原因:
尝试以root /etc/hosts
文件打开,并添加如下所示的行
# IP ADDR HOSTNAME
192.168.1.1 your_desired_hostname
并且名称应该解决。
使用您的IP地址更新192.168.1.1
。
Here
local_if = socket.gethostbyname_ex(socket.gethostname())[-1]
与
try:
local_if = socket.gethostbyname_ex(socket.gethostname())[-1]
except:
local_if = []
答案 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