「python小指令碼」從資料庫獲取檔案路徑透過scp下載本地

寫在前面

我的需求

需要在mysql資料庫中查到相關檔案的在伺服器的路徑,然後透過scp來下載相關檔案,之前是手動操作,我現在要寫成一個指令碼

我需要解決的問題

如何使用python連線mysql資料庫

如何使用python執行scp命令.

我是怎麼做的

使用 pymysql模組連線mysql獲取路徑

使用 paramiko模組執行scp命令

透過使用PyInstaller打包為一個exe,可以直接給運維人員使用

何謂喜歡一個人,遇上她之前不知情為何物,錯過之後,便更不知了 ——烽火戲諸侯《雪中悍刀行》

編寫指令碼的準備

pymysql

pymysql是一個基於python的 MySQL 客戶端庫,官網:

https://pymysql。readthedocs。io/en/latest/user/examples。html,

下面是一個簡單的Demo

import pymysql。cursors# Connect to the databaseconnection = pymysql。connect(host=‘localhost’, user=‘user’, password=‘passwd’, database=‘db’, charset=‘utf8mb4’, cursorclass=pymysql。cursors。DictCursor)with connection: with connection。cursor() as cursor: # Create a new record sql = “INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)” cursor。execute(sql, (‘webmaster@python。org’, ‘very-secret’)) # connection is not autocommit by default。 So you must commit to save # your changes。 connection。commit() with connection。cursor() as cursor: # Read a single record sql = “SELECT `id`, `password` FROM `users` WHERE `email`=%s” cursor。execute(sql, (‘webmaster@python。org’,)) result = cursor。fetchone() print(result)

Paramiko

Paramiko是 SSH協議的純 Python實現 ,提供客戶端和伺服器功能。它為高階 SSH 庫Fabric提供了基礎,可以執行遠端 shell 命令或傳輸檔案。官網:https://www.paramiko.org/

下面是一個簡單的Demo

import paramiko# Connectclient = paramiko。SSHClient()client。connect(host, port, username)# Obtain sessionsession = client。get_transport()。open_session()# Forward local agentAgentRequestHandler(session)# Commands executed after this point will see the forwarded agent on# the remote end。session。exec_command(“git clone https://my。git。repository/”)

實現

#!/usr/bin/env python# -*- encoding: utf-8 -*-‘’‘@File : apps。py@Time : 2021/12/14 16:34:56@Author : Li Ruilong@Version : 1。0@Contact : 1224965096@qq。com@Desc : 一個從mysql資料庫獲取檔案路徑,透過scp遠端下載檔案到本地的指令碼pip install pymysqlpip install paramiko ’‘’# here put the import libimport pymysqlimport osimport timeimport paramiko# mysql資料庫相關配置host = ‘127。0。0。1’port = 3306user = ‘user’password = ‘***********’db = ‘dbname’# ssh相關配置ssh_hostname = “127。0。0。1”ssh_username = “user”ssh_password = ‘***********’def initDB(): ‘’‘連線資料庫的操作 Args: host(str) port(int) user(str) password(str) db(str) Returns: 連線狀態:1成功,0失敗 ’‘’ try: global connection connection = pymysql。connect(host=host, port=port, user=user, password=password, db=db, charset=‘utf8mb4’, cursorclass=pymysql。cursors。DictCursor) global cursor cursor = connection。cursor() print(“資料庫連線成功============================================”, time。strftime( “%Y-%m-%d %H:%M:%S”, time。localtime()), “=========================”, ‘\n’) return 1 except: print(“資料庫連線異常============================================”, time。strftime( “%Y-%m-%d %H:%M:%S”, time。localtime()), “=========================”, ‘\n’) return 0def scp(local_filename, remote_path): ‘’‘建立`scp`連線, Args: local_filename(str): 本地要存放的檔案位置 remote_path(int) 遠端的檔案位置 Returns: void ’‘’ # 建立ssh訪問 ssh = paramiko。SSHClient() ssh。load_system_host_keys() ssh。set_missing_host_key_policy( paramiko。AutoAddPolicy()) # 允許連線不在know_hosts檔案中的主機 ssh。connect(ssh_hostname, port=22, username=ssh_username, password=ssh_password) # 遠端訪問的伺服器資訊 # 建立scp,下載檔案 sftp = paramiko。SFTPClient。from_transport(ssh。get_transport()) sftp = ssh。open_sftp() sftp。get(remote_path, local_filename)def execute(): sql = ‘’‘SELECT a。number,a。path,a。date FROM tablename a WHERE (number LIKE “%{}” OR numbers LIKE “%{}” ) AND year(a。date) =“{}” AND month(a。date) = “{}” ’‘’ print(“查詢sql:”,sql) year = input(“請輸入年份:”) month = input(“請輸入月份:”) number = input(“請輸入電話號碼:”) print(“\n”) sql = sql。format(number, number, year, month) print(“資料查詢中請稍等。。。。。”) resout = cursor。execute(sql) if(resout == 0): print(“沒有需要的資料!!!”, ‘\n’) time。sleep(5) else: date = cursor。fetchall() for i in date: pathName = i[“path”] print(“獲取到的檔案位置:”, pathName, ‘\n’) #/bakrecord/record/2020/05/25/800142/800142_202918189。mp3 # 獲取檔名稱 fileName = str(pathName)。split(“/”)[7] print(“檔名稱:”, fileName, ‘\n’) # 當前工作環境目錄 currentPath = os。getcwd() loadPathName = currentPath+“\\”+fileName try: scp(loadPathName, pathName) print(“下載成功============================================”, time。strftime( “%Y-%m-%d %H:%M:%S”, time。localtime()), “=========================”, ‘\n’) print(“下載後的檔案路徑:”, loadPathName, ‘\n’) except: print(“下載異常!!!!”, ‘\n’) time。sleep(5)if __name__ == ‘__main__’: print(‘資料庫連線’,‘\n’) if (initDB() == 1): while True: boo = input(“是否下載錄音檔案:?y/n\n”) if boo == ‘y’: execute() else: break else: print(“資料庫連結異常”)

打包

可以透過命令列打包,也可以透過寫一個打包檔案的方式打包

from PyInstaller。__main__ import run#### 打包檔案直接執行if __name__ == ‘__main__’: opts = [‘apps。py’, # 主程式檔案 ‘-F’, # 打包單檔案 ‘——ico=favicon。ico’, # 可執行程式圖示 ] run(opts)

打包執行

「python小指令碼」從資料庫獲取檔案路徑透過scp下載本地

「python小指令碼」從資料庫獲取檔案路徑透過scp下載本地