使用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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值