使用Python ssh tunnel链接Mysql数据库

#自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()

猜你喜欢

转载自blog.csdn.net/daiyu__zz/article/details/84704860