我正在服务器上通过 SSH 连接到 MySQL 数据库。我设法通过 MySql 工作台和系统 shell 来完成此操作,这意味着密码、用户名和 ip 是正确且允许的。

现在我正在尝试通过 Python 进行连接。我使用 sshtunnel 包,其设置与工作台中的设置相同(在 shell 中均为默认设置) - mysql 端口 3306、ssh 端口 22、mysql 主机名 127.0.0.1 并且它连接了我。 当我尝试通过连接器连接到数据库时,我得到:

mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'myusername'@'localhost' (using password: YES).

我还尝试使用 python 通过 shell 直接连接: os.system("mysql -u myusername -p") 我得到了:

ERROR 1045 (28000): Access denied for user 'myusername'@'localhost' (using password: YES)

我在这里查看:

Can't access MySQL through MySQL Workbench or HeidiSQL, but can access through shell

Accessing MySQL from Python 3: Access denied for user

还有更多,但我发现没有任何帮助。 我的Python版本是3.6.8,MySql版本是5.7.31。 python 访问的 shell 与普通 Unix 访问的 shell 之间还有什么不同?或者通过工作台获得访问权限?

编辑:

请求的代码。所有三个连接都给出完全相同的输出。

with sshtunnel.SSHTunnelForwarder( 
        (ssh_host, ssh_port), 
        ssh_username=ssh_username, 
        ssh_password=ssh_password, 
        remote_bind_address=('localhost', mysql_port)) as tunnel: 
     
 
    # conn = mysql.connector.connect(**mysql_config) 
    conn = MySQLdb.connect(host="localhost",  
    user="myusername", passwd="password", db="mydb") 
    print(conn) 
    # print(os.system("mysql -u myusername -p")) 

请您参考如下方法:

我成功连接到:

tunnel = sshtunnel.SSHTunnelForwarder((ssh_host, 22), ssh_password=ssh_password, ssh_username=ssh_username, 
     remote_bind_address=('localhost', 3306)) 
tunnel.start() 

显然,区别在于保持隧道打开而不是使用“with”语句,尽管我不明白实际发生了什么,并且希望得到解释。


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!