python导出数据,需要ssh连接导出方法

压测需要从数据库导出一些数据,本地连接mysql 方式,需要经过跳板机,ssh通道。记录一下。

 

# -*- coding:utf-8 -*-
import conf
import pymysql
from sshtunnel import SSHTunnelForwarder

def get_data(env,sql):  # 根据sql语句,获取数据库的数据
    '''
    返回的数据类型为嵌套tuple,长度是sql的查询数据条数
    (('第1条数据字段1的值','第1条字段2的值'), ('第2条数据字段1的值','第2条数据字段2的值'))
    '''
    dbhost = conf.dbconfigs[env]['host']
    uname = conf.dbconfigs[env]['user']
    passwd = conf.dbconfigs[env]['passwd']

    with SSHTunnelForwarder(
            ("x.x.x.x", 22),
            ssh_username="xxxx",
            ssh_pkey="/Users/yuz/Desktop/id_rsa.dat",
            # ssh_private_key_password="secret",
            remote_bind_address=(dbhost, 3306),
            local_bind_address=('0.0.0.0', 10022)
    ) as tunnel:
        conn = pymysql.connect(host='127.0.0.1',
                               port=10022,
                               user=uname,
                               passwd=passwd)

        cur = conn.cursor()
        cur.execute(sql)
        results = cur.fetchall()
        cur.close()
        conn.close()
        return results

def write_txt(content):
    content = str(content)
    f1 = open('order.txt', 'a')
    f1.write(content  + "\n")


if __name__ == "__main__":
    env = 'bench_order_price'
    #sql = "SELECT contact,id_card FROM courier1.couriers WHERE contact LIKE 'M%' and `status` = 0 LIMIT 10000"
    sql = "SELECT id,order_number FROM order9.infos WHERE order_number IN (SELECT order_number from order9.orders WHERE  `status` = 60 )"
    datas = get_data(sql)
    for order in datas:
        write_txt(str(order[0])+","+str(order[1]))
        print(order)

 

你可能感兴趣的:(python学习笔记)