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)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章