简体   繁体   English

Python并通过SSH连接到MySQL

[英]Python and Connecting to MySQL over SSH

I am trying to connect to a MySQL database on someone else's "machine". 我试图连接到别人的“机器”上的MySQL数据库。 When I use Navicat for MySQL, I have no problem connecting to it. 当我使用Navicat for MySQL时,我没有问题连接到它。 I am trying to do the same with Python so that I do not have to use the GUI interface. 我试图用Python做同样的事情,所以我不必使用GUI界面。 I know all my info below is correct (even though I swap fake info) -- can anyone spot where I went wrong? 我知道下面的所有信息都是正确的(即使我交换了假信息) - 有人能发现我哪里出错吗? The error I get is OperationalError: (2005, "Unknown MySQL server host 'FTP_hostname' (0)") 我得到的错误是OperationalError: (2005, "Unknown MySQL server host 'FTP_hostname' (0)")

My code (using paramiko for the SSH): 我的代码(使用paramiko for SSH):

import MySQLdb
import paramiko
import time

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('SSH_hostname', 22, username='me', password='pswrd')

time.sleep(1)

db = MySQLdb.connect(host="FTP_hostname", 
                     user="root", 
                     passwd="pswrd2",
                     db="MyDB")
cur = db.cursor()

Again, I put all this into Navicat and connect no problem. 再次,我将所有这些都放入Navicat并且连接没有问题。 Hoping you can help! 希望你能帮忙! Thanks! 谢谢!

MySQL, like most databases, by default runs locally and disallows access from outside networks. 与大多数数据库一样,MySQL默认在本地运行,不允许从外部网络访问。 As such, you cannot connect to it from an external computer. 因此,您无法从外部计算机连接到它。

Navicat, being a software explicitely for remote administration of databases, likely connects via SSH and tunnels the MySQL connection over it. Navicat是一种明确用于数据库远程管理的软件,可能通过SSH连接并通过它连接MySQL连接。 That way it can act as if the database was installed locally, and for the database it looks as if it was accessed locally. 这样它就可以像在本地安装数据库一样,对于数据库,它看起来好像是在本地访问的。

You could try to do the same by creating a tunnel using Paramiko; 您可以尝试通过使用Paramiko创建隧道来做同样的事情; see also this question . 另见这个问题

If you still in need of connecting to a remote MySQL db via SSH I have used a library named sshtunnel, that wraps ands simplifies the use of paramiko (a dependency of the sshtunnel). 如果您仍然需要通过SSH连接到远程MySQL数据库,我使用了一个名为sshtunnel的库,它包装和简化了paramiko(sshtunnel的依赖项)的使用。

You can check my answer in another similar question with some sample code to use it. 您可以使用一些示例代码在另一个类似问题中查看我的答案以使用它。

db = MySQLdb.connect(host="FTP_hostname", db = MySQLdb.connect(host =“FTP_hostname”,

Would the host not need to be 127.0.0.1 (localhost) as the tunnel is making the MySQL DB local to the machine that the python script is running on? 主机不需要是127.0.0.1(localhost),因为隧道正在使MySQL数据库本地运行到运行python脚本的机器上吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM