python詳解如何通過sshtunnel pymssql實現(xiàn)遠(yuǎn)程連接數(shù)據(jù)庫
最近幾天在做Python相關(guān)項目,有個需求 ,是希望在任何機器上都可以ssh到某臺在數(shù)據(jù)庫白名單的機器上,然后訪問數(shù)據(jù)庫,不然的話就要去服務(wù)器安裝Python環(huán)境,運行程序,比較麻煩,翻閱多篇博客文章,決定自己去實現(xiàn)。
涉及庫:pymssql、sshtunnel
涉及數(shù)據(jù)庫:SQLSERVER
場景如下:

跳板機核心代碼
def __get_ssh_connector(self):
# 遠(yuǎn)程連接
# 跳板機地址 端口,服務(wù)器賬號,密碼配置
server = SSHTunnelForwarder(
(
self.connect_config.get("ssh_host", ‘白名單服務(wù)器地址'),
self.connect_config.get("ssh_port", 22)
),
ssh_username=self.connect_config.get("ssh_username", ‘白名單服務(wù)器賬號 '),
ssh_password=self.connect_config.get("ssh_password", ‘白名單服務(wù)器密碼 '),
# 內(nèi)網(wǎng)數(shù)據(jù)庫地址和端口
remote_bind_address=(self.connect_config.get("dbserver", '目標(biāo)數(shù)據(jù)庫地址'), self.connect_config.get("ssh_mssql_port", ‘?dāng)?shù)據(jù)庫端口'))
)
server.start()
return server # 遠(yuǎn)程主機上的mssql通過ssh連接映射到本地的端口
pymssql 連接數(shù)據(jù)庫核心代碼
def get_mssql_connector(self):
return get_mssql_connector({
"port": self.server.local_bind_port, #非常重要
"username": ‘目標(biāo)數(shù)據(jù)庫賬號',
"password": ‘目標(biāo)數(shù)據(jù)庫密碼',
"db": self.connect_config.get('db', ‘目標(biāo)數(shù)據(jù)庫')
})
def __get_mssql_connector(database_config):
host = database_config.get('host', '127.0.0.1')
port = database_config.get('port', ‘?dāng)?shù)據(jù)庫端口')
user = database_config.get('username', ‘目標(biāo)數(shù)據(jù)庫賬號')
passwd = database_config.get('password', ‘目標(biāo)數(shù)據(jù)庫密碼')
db = database_config.get('db', ‘目標(biāo)數(shù)據(jù)庫')
return pymssql.connect(host=host, port=port, user=user, password=passwd, database=db, charset="UTF-8")
MySql 和SQLSERVER方法一樣,不一樣的地方pymssql.connect改成pymysql.connect
人生第一篇技術(shù)博客,第一次奉獻給 大家
到此這篇關(guān)于python詳解如何通過sshtunnel pymssql實現(xiàn)遠(yuǎn)程連接數(shù)據(jù)庫的文章就介紹到這了,更多相關(guān)python 遠(yuǎn)程連接數(shù)據(jù)庫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python開發(fā)一個解析protobuf文件的簡單編譯器
這篇文章主要介紹了python如何開發(fā)一個解析protobuf文件的簡單編譯器,幫助大家更好的理解和學(xué)習(xí)python,感興趣的朋友可以了解下2020-11-11
Python使用turtle和matplotlib繪制圓和愛心的示例代碼
這篇文章主要是帶大家用Python的turtle和matplotlib畫出圓滿和愛心,文中的示例代碼講解的非常詳細(xì),對我們學(xué)習(xí)Python有一定幫助,感興趣的可以了解一下2023-06-06
windows下python使用ffmpeg實現(xiàn)rtsp推流
這篇文章主要為大家詳細(xì)介紹了在windows環(huán)境下python如何使用ffmpeg實現(xiàn)rtsp推流,文中的示例代碼講解詳細(xì),有需要的小伙伴可以了解一下2023-09-09

