python 使用mysqldb模块通过ssh隧道连接mysql

 出于安全考虑,数据库服务器只允许堡垒机通过ssh访问,这对日常的使用带来了麻烦。昨天的工作中,就遇到了这样的问题,mysql数据库放在了服务器A上,只允许服务器B来访问,而我在机器C上,可以通过ssh连接服务器B。为了解决在机器C上连接mysql这个问题,用百度搜索解决方法,遗憾的是,找不到什么靠谱的,最后,还是翻墙用了google,终于找到了一种简单可靠的方法。把google赶出中国,让中国的IT技术退步了10分钟。

         献上代码:

        

[python]  view plain  copy
  1. import MySQLdb  
  2. from sshtunnel import SSHTunnelForwarder  
  3.   
  4. with SSHTunnelForwarder(  
  5.          ('sshhost.domain.com'22),    #B机器的配置  
  6.          ssh_password="sshpasswd",  
  7.          ssh_username="sshusername",  
  8.          remote_bind_address=('mysqlhost.domain.com'3306)) as server:  #A机器的配置  
  9.   
  10.     conn = MySQLdb.connect(host='127.0.0.1',              #此处必须是是127.0.0.1  
  11.                            port=server.local_bind_port,  
  12.                            user='user',  
  13.                            passwd='password',  
  14.                            db='dbname')  

         

原文链接 http://blog.csdn.net/KWSY2008/article/details/51440952

猜你喜欢

转载自blog.csdn.net/wuchenlhy/article/details/79640212