Python代码建立到远程服务器的ssh然后连接到MYSQL [英] Python code to establish an ssh to remote server and then connect to MYSQL

查看:30
本文介绍了Python代码建立到远程服务器的ssh然后连接到MYSQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一些 python 代码来建立到远程服务器的 ssh 连接,然后执行一些 MYSQL 查询(为了简单起见,我已经将它们排除在示例之外).据我所知,ssh 正在工作,但我似乎无法进入数据库.有人可以帮忙吗?

I am trying to write some python code to establish an ssh connection to a remote server and then execute some MYSQL queries (I have left these out of the example for simplicity). As far as I can gather the ssh is working but I can't seem to get into the database. Can anyone help?

import MySQLdb
import decimal
import operator
import os
import paramiko



mykey = paramiko.RSAKey.from_private_key_file("C:/Users/Desktop/keyname.pem")

ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect('ec2-blah-blah.compute.amazonaws.com', username='ec2-user', pkey = mykey) 

conn = MySQLdb.connect(
    host="127.0.0.1",
    port = 3306,
    user="root",
    passwd="password",
    db="MyDB")

我得到的错误是:

文件C:\Python27\lib\site-packages\MySQLdb__init__.py",第 81 行,在 Connect 中返回连接(*args,**kwargs)文件C:\Python27\lib\site-packages\MySQLdb\connections.py",第 187 行,在 中它super(Connection, self).init(*args, **kwargs2)_mysql_exceptions.OperationalError: (2003, 无法连接到 '12 上的 MySQL 服务器7.0.0.1' (10061)")

File "C:\Python27\lib\site-packages\MySQLdb__init__.py", line 81, in Connect return Connection(*args, **kwargs) File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 187, in in it super(Connection, self).init(*args, **kwargs2) _mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on '12 7.0.0.1' (10061)")

推荐答案

您在连接对象中使用的 ip 地址127.0.0.1"指的是 localhost,也就是程序所在的计算机继续运行.您无法远程连接到另一台计算机的本地主机.您需要将主机ip地址替换为远程服务器的ip地址.

The ip address "127.0.0.1" that you use in your connection object refers to localhost, which is the computer the program is running on. You can't remotely connect to the localhost of another computer. You need to replace the host ip address with the ip address of the remote server.

此外,如果连接正确,您应该只需要 MySQLdb.connect 对象,而不是 ssh 对象.

Also you should only need the MySQLdb.connect object, not the ssh object if you connect correctly.

这篇关于Python代码建立到远程服务器的ssh然后连接到MYSQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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