python詳解如何通過sshtunnel pymssql實現(xià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):
# 遠程連接
# 跳板機地址 端口,服務(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", '目標數(shù)據(jù)庫地址'), self.connect_config.get("ssh_mssql_port", ‘數(shù)據(jù)庫端口'))
)
server.start()
return server # 遠程主機上的mssql通過ssh連接映射到本地的端口
pymssql 連接數(shù)據(jù)庫核心代碼
def get_mssql_connector(self):
return get_mssql_connector({
"port": self.server.local_bind_port, #非常重要
"username": ‘目標數(shù)據(jù)庫賬號',
"password": ‘目標數(shù)據(jù)庫密碼',
"db": self.connect_config.get('db', ‘目標數(shù)據(jù)庫')
})
def __get_mssql_connector(database_config):
host = database_config.get('host', '127.0.0.1')
port = database_config.get('port', ‘數(shù)據(jù)庫端口')
user = database_config.get('username', ‘目標數(shù)據(jù)庫賬號')
passwd = database_config.get('password', ‘目標數(shù)據(jù)庫密碼')
db = database_config.get('db', ‘目標數(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)遠程連接數(shù)據(jù)庫的文章就介紹到這了,更多相關(guān)python 遠程連接數(shù)據(jù)庫內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學習參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信