When I try to SSH to MySQL with Python 3.7, it hangs and Mahatter, so a memo at that time
I hung up when I tried to log in to MySQL running on an Ubuntu server using Paramiko. When I searched the Web, it was written that sshtunnel could be easily done by using mysql.connector, so I tried it. I tried the sample code but it hangs on a MySQL connection.
After investigating the cause of the hang, it was written that "server.daemon_forward_servers = True" should be set. However, it hangs even if it is set. In addition, the following is written on the page of the sshtunnel project. In short, this setting is unnecessary.
Remove useless daemon_forward_servers = True hack for hangs prevention (is not fully backward compatible)
Furthermore, when I searched the Web, it was written that pymysql can connect normally. However, there are other problems with pymysql, so I decided to use mysql.connector this time.
I was able to connect after specifying the "use_pure = True" parameter in mysql.connector.connect ().
import mysql.connector
from sshtunnel import SSHTunnelForwarder
with SSHTunnelForwarder(
('<Server IP>', 22),
ssh_username="<User name for server login>",
ssh_password="<Password for server login>",
remote_bind_address=('127.0.0.1', 3306)) as server:
db_connect = mysql.connector.connect(
host='127.0.0.1',
port=server.local_bind_port,
user='<User name for MySQL>',
password='<Password for MySQL>',
database='<Database to connect>',
use_pure=True
)
db_curs = db_connect.cursor()
sql_cmd = f"SELECT * FROM nic_devices WHERE mac_address='{mac_address}'"
db_curs.execute(sql_cmd)
result = db_curs.fetchall()
db_curs.close()
db_connect.close()
print(result)
that's all
Recommended Posts