【问题标题】:Why can I connect to MySQL through shell, but can't do it through Python?为什么我可以通过shell连接到MySQL,但不能通过Python连接?
【发布时间】:2020-12-25 16:42:57
【问题描述】:

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

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

mysql.connector.errors.ProgrammingError: 1045 (28000): 拒绝访问 对于用户'myusername'@'localhost'(使用密码:YES)。

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

错误 1045 (28000): 拒绝用户 'myusername'@'localhost' 的访问 (使用密码: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"))

【问题讨论】:

标签: python mysql shell ssh


【解决方案1】:

我设法联系到:

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

显然不同之处在于保持隧道打开而不是使用“with”语句,尽管我不明白实际发生了什么,我希望能解释一下。

【讨论】:

    猜你喜欢
    • 2019-10-25
    • 1970-01-01
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多