首先在python中使用mysqldb进行ssh [英] ssh first with mysqldb in python

查看:51
本文介绍了首先在python中使用mysqldb进行ssh的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用python中的MySQLdb连接到远程服务器上的MySQL数据库.问题是,首先我需要SSH进入主机,然后从那里开始,我需要连接到MySQL服务器.但是,我遇到的问题是,MySQLdb在连接到SQL Server之前似乎没有建立SSH连接的方法.我已经检查过文档,但是还没有运气.

I'm trying to connect to a MySQL database on a remote server using MySQLdb in python. The problem is that first I need to SSH into the host, and then from there, I need to connect to the MySQL server. The problem I'm having, though, is that MySQLdb does not seem to have a way of establishing an SSH connection before connecting to the SQL server. I've checked the documentation but have not had any luck.

这是我的联系方式:

conn = MySQLdb.connect(host = 'mysqlhost.domain.com:3306', user = 'user', passwd = 'password', db = 'dbname')

但是我真正需要的是这样的东西:

But what I really need is something like this:

conn = MySQLdb.connect(sshhost = 'sshhost.domain.com', sshuser = 'sshusername', sshpasswd = 'sshpasswd', host = 'mysqlhost.domain.com:3306', user = 'user', passwd = 'password', db = 'dbname')

这当然是虚构的.有人可以提出任何建议吗?

Which is of course just made up. Can anyone make any recommendations?

推荐答案

在使用MySQLdb.connect之前,请设置ssh隧道.隧道将使它看起来好像您在本地运行mysql一样,将其设置为类似

Setup an ssh tunnel before you use MySQLdb.connect. The tunnel will make it appear as though you have the mysql running locally, set it up something like this

ssh user@host.com -L 9990:localhost:3306

此处您的本地端口9990将绑定到远程主机上的3306,-L代表本地,则9990:localhost:3306表示LOCALPORT:

conn = MySQLdb.connect(host ='mysqlhost.domain.com:9990',user ='user',passwd ='password',db ='dbname')

here your local port 9990 will bind to 3306 on the remote host, -L stands for local, then 9990:localhost:3306 means LOCALPORT:

conn = MySQLdb.connect(host = 'mysqlhost.domain.com:9990', user = 'user', passwd = 'password', db = 'dbname')

注意9990.

将用户的公共ssh密钥添加到host.com,以便您不必每次都要设置隧道时都使用密码(使用公共密钥身份验证).

Add your public ssh key of user to the host.com so that you dont have to type the password each time you want to setup the tunnel (use public key authentication).

如果您需要在python中执行此操作,则可以在python中调用python-to-ssh绑定库来为您设置隧道.

If you need to do this within python there is python-to-ssh binding libraries you could call from within python to setup the tunnel for you.

这篇关于首先在python中使用mysqldb进行ssh的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆