python mysql通过ssh连接 [英] python mysql connectivity via ssh
问题描述
我使用以下步骤手动连接到我的数据库:
I connect to my db manually using these steps:
1>load a putty session with ip 1.1.1.1 and port 1111
2>login as: login1
3>login1@1.1.1.1's password: pwd1
4>[login1@G ~]$ ssh login1@2.2.2.2
5>[login1@l ~]$ MySQL -h 3.3.3.3 -u login2 -p'pwd2' -D mydb
现在我可以成功查询任何东西,例如 select * from my_table.
Now I can can query anything successfully like select * from my_table.
我有一个 python selenium webdriver 代码,我想从中读取我的数据库.由于 ssh 隧道和涉及 3 个 IP,我无法实现它.
I have a python selenium webdriver code from where I want to read my db. I am not able to achieve it because of ssh tunnelling and 3 IP's involved.
from sshtunnel import SSHTunnelForwarder
import MySQLdb
with SSHTunnelForwarder(
('host', 1111),
ssh_password="pwd1
ssh_username="login1",
remote_bind_address=('2.2.2.2', 1111)) as server:
con = None
con = MySQLdb.connect(user='login2',passwd='pwd2',db='mydb',host=3.3.3.3,port=3306)
cur = con.cursor()
我收到此错误:
推荐答案
实例化SSHTunnelForwarder
时:
参数 host
是你的远程 ssh 2.2.2.2
.remote_bind_address
的参数将用于隧道,端口是您想要隧道的端口,因此您的 mysql 端口.('3.3.3.3', 3306)
The param host
is your remote ssh 2.2.2.2
.
Argument for remote_bind_address
will be for the tunnel, the port is the one you want to tunnel, so your mysql port. ('3.3.3.3', 3306)
然后当连接到 mysql 时,您希望它通过隧道访问 mysql 实例.隧道端口为 server.local_bind_port
.
Then when connecting to mysql, you want it to pass though the tunnel to access the mysql instance. The tunnel port is server.local_bind_port
.
from sshtunnel import SSHTunnelForwarder
import MySQLdb
with SSHTunnelForwarder(
('2.2.2.2', 1111),
ssh_password="pwd1"
ssh_username="login1",
remote_bind_address=('3.3.3.3', 3306)) as server:
con = MySQLdb.connect(
user='login2',passwd='pwd2',
db='mydb',host=1.1.1.1,
port=server.local_bind_port)
这篇关于python mysql通过ssh连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!