生产环境中,为了安全起见,大多数的数据库是无法在本地直接访问的,需要先连接跳板机,然后通过跳板机访问。这么做虽然在安全方面稍有保证,但是对于写代码的人来说,增加了一定的难度,以下是我个人对python连接跳板机再连接mysql的一些总结,希望能帮助到各位。
首先,需要下载sshtunnel包,使用pip即可,其次是连接MySQL的包,这个根据自己的喜好来就好,我个人常用的是mysql.connector和pymysql,这里就使用mysql.connector。
代码如下:
server = SSHTunnelForwarder(
(host_jump, int(port_jump)), # 跳板机的配置
ssh_pkey=ssh_pk_jump,
ssh_username=user_name_jump,
remote_bind_address=(host_mysql, int(port_mysql))) # 数据库服务器的配置
server.start()
conn = mysql.connector.connect(host='127.0.0.1', port=server.local_bind_port, user=user_name_mysql, password=password_mysql, database=database)
# do something...
conn.close()
server.close()说明:
1:因为我的跳板机是通过密钥连接的,所以需要ssh_pkey参数,值是密钥的路径,如果需要通过密码连接,将该参数换成ssh_password即可;
2:SSHTunnelForwarder方法返回的server对象必须调用start()方法后才可以正常使用;
3:在连接MySQL时,connect()方法的参数中的host必须为127.0.0.1;
4:由于端口必须为数字类型,所以使用int()方法转换;
5:使用结束后,为了安全起见,调用server的close()方法关闭连接,当然也可以使用with语句,如下:
with SSHTunnelForwarder(
(host_jump, int(port_jump)), # 跳板机的配置
ssh_pkey=ssh_pk_jump,
ssh_username=user_name_jump,
remote_bind_address=(host_mysql, int(port_mysql))) as server: # MySQL服务器的配置
conn = pymysql.connect(host='127.0.0.1', port=server.local_bind_port, user=user_name_mysql, password=password, database=database)此时不仅可以省略close()方法,也可以省略start()方法。