Python利用SSH隧道實現(xiàn)數(shù)據(jù)庫訪問
本文介紹通過sshtunnel類庫建立SSH隧道,使用paramiko通過SSH來訪問數(shù)據(jù)庫。
實現(xiàn)了兩種建立SSH方式:公私鑰驗證、密碼驗證。
公私鑰可讀本地,也可讀取Aws S3上的私鑰文件。
本質(zhì)上就是在本機建立SSH隧道,然后將訪問DB轉發(fā)到本地SSH內(nèi)去訪問數(shù)據(jù)庫。
簡單易懂,上代碼:
from sshtunnel import SSHTunnelForwarder
from sqlalchemy import create_engine, text
import paramiko
import io
import socket
#### 都換成你自己的
# SSH配置
ssh_host = '' #主機
ssh_port = 22 #端口
ssh_user = 'ec2-user' #用戶名
ssh_password = '' #密碼(如果是密碼驗證)
ssh_key_path = r'C:\Users\Desktop\test_primi.pem' #私鑰本地地址(如果是公私鑰驗證)
# 數(shù)據(jù)庫配置
database_user = '' #用戶名
database_password = '' #密碼
database_name = '' #數(shù)據(jù)庫名
database_host = '' #主機
database_port = 3306 #端口號
def get_available_port():
"""
獲取可用的本地端口。
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.bind(('127.0.0.1', 0))
port = sock.getsockname()[1]
finally:
sock.close()
return port
try:
#讀取S3上的私鑰
# s3_client = get_s3_client()
# response = s3_client.get_object(Bucket='桶名稱', Key='私鑰在S3上的key')
# private_key_content = response['Body'].read().decode('utf-8')
#private_key = paramiko.RSAKey.from_private_key(io.StringIO(private_key_content))
#讀取本地私鑰
private_key = paramiko.RSAKey.from_private_key_file(ssh_key_path)
local_port = get_available_port()
# 創(chuàng)建 SSH 隧道
tunnel= SSHTunnelForwarder(
(ssh_host, ssh_port),
ssh_username=ssh_user,
ssh_pkey=private_key,
#ssh_password=ssh_password,
remote_bind_address=(database_host, database_port),
local_bind_address=('127.0.0.1', local_port),
host_pkey_directories=[]
)
try:
# 啟動 SSH 隧道
tunnel.start()
# 連接數(shù)據(jù)庫
engine = create_engine(
f'mysql+pymysql://{database_user}:{database_password}@127.0.0.1:{local_port}/{database_name}')
# 測試數(shù)據(jù)庫連接
with engine.connect() as connection:
result = connection.execute(text("SELECT count(*) from activity_logs"))
for row in result:
print(row)
finally:
# 關閉 SSH 隧道
tunnel.stop()
except Exception as e:
print(f"出現(xiàn)錯誤: {e}")執(zhí)行結果:

成功輸出條數(shù)
注意:host_pkey_directories=[] 的意思是 不要在指定的目錄中尋找密鑰,如果沒有將出現(xiàn)如下錯誤,但不影響程序正常執(zhí)行。

可以先在本地用Navicat之類的客戶端測好了,sshtunnel應該是三種驗證方法都支持的,源碼如下


到此這篇關于Python利用SSH隧道實現(xiàn)數(shù)據(jù)庫訪問的文章就介紹到這了,更多相關Python SSH訪問數(shù)據(jù)庫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python內(nèi)置模塊Collections的使用教程詳解
collections 是 Python 的一個內(nèi)置模塊,所謂內(nèi)置模塊的意思是指 Python 內(nèi)部封裝好的模塊,無需安裝即可直接使用。本文將詳解介紹Collections的使用方式,需要的可以參考一下2022-03-03
python異步編程之a(chǎn)syncio低階API的使用詳解
asyncio中低階API的種類很多,涉及到開發(fā)的5個方面,這篇文章主要為大家詳細介紹了這些低階API的具體使用,感興趣的小伙伴可以學習一下2024-01-01

