我正在尝试使用sshtunnel
中的MySQLdb
和python2.7
来隧道连接并面临以下问题:
我用Sequel Pro连接mysql没关系,但是python代码没有用!
Sequel Pro是这样的:
和代码是这样的:
`from sshtunnel import SSHTunnelForwarder
import MySQLdb
with SSHTunnelForwarder(
('2.2.2.2', 22),
ssh_username='name2',
ssh_password='mypassword',
remote_bind_address=('127.0.0.1', 3306)
) as tunnel:
connection = MySQLdb.connect(
user='name1',
password='mypassword',
host='1.1.1.1',
database='mydata',
port=3306)
我搜索了一些示例代码:
from sshtunnel import SSHTunnelForwarder
import MySQLdb
with SSHTunnelForwarder(
(_host, _ssh_port),
ssh_username=_username,
ssh_password=_password,
remote_bind_address=(_remote_bind_address, _remote_mysql_port),
local_bind_address=(_local_bind_address, _local_mysql_port)
) as tunnel:
connection = MySQLdb.connect(
user=_db_user,
password=_db_password,
host=_local_bind_address,
database=_db_name,
port=_local_mysql_port)
我想知道我是否以正确的方式构建ssh或连接到mysql?感谢帮助!
更新 错误信息:
2017-06-15 17:52:58,415| ERROR | Could not connect to gateway 1.1.1.1:22 : 110
Traceback (most recent call last):
File "<stdin>", line 6, in <module>
File "build/bdist.linux-x86_64/egg/sshtunnel.py", line 1483, in __enter__
File "build/bdist.linux-x86_64/egg/sshtunnel.py", line 1225, in start
File "build/bdist.linux-x86_64/egg/sshtunnel.py", line 1037, in _raise
sshtunnel.BaseSSHTunnelForwarderError: Could not establish session to SSH gateway
答案 0 :(得分:1)
更新代码以添加local_bind_address:
from sshtunnel import SSHTunnelForwarder
import MySQLdb
with SSHTunnelForwarder(
('2.2.2.2', 22),
ssh_username='name2',
ssh_password='mypassword',
remote_bind_address=('127.0.0.1', 3306),
local_bind_address = ('1.1.1.1', 3306)
) as tunnel:
connection = MySQLdb.connect(
user='name1',
password='mypassword',
host='1.1.1.1',
database='mydata',
port=3306)
除非您指定Localhost(在您的情况下为'1.1.1.1')&amp;港口;本地主机无法使用MYSQL服务。 我希望这有帮助。