使用Python ssh tunnel連結Mysql資料庫
阿新 • • 發佈:2018-12-25
#自https://my.oschina.net/1123581321/blog/774704轉載
安裝 sshtunnel
sudo apt-get install libffi-dev
sudo pip install sshtunnel
使用示例:
def test(): from sshtunnel import SSHTunnelForwarder import pymysql import pymysql.cursors with SSHTunnelForwarder( ('52.1.1.2', 22), ssh_username="ubuntu", # ssh_password="sshpasswd", ssh_pkey="/home/kk/key.pem", remote_bind_address=('xx.us-west-1.rds.amazonaws.com', 3306) ) as tunnel: conn = pymysql.connect(host='127.0.0.1', port=tunnel.local_bind_port, user='root', password='password', db='db', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) sql = """ insert into mytbl (channel, w1, is_open) values (%s, %s, %s) on duplicate key update w1=values(w1), is_open=values(is_open) """ for tag in ['A', 'B', 'C', 'D']: for i in xrange(10000): ch = '%s%s' % (tag, i) w1 = 'aabb'; is_open = 1 with conn.cursor() as cur: cur.execute(sql, (ch, w1, is_open)) conn.commit()