1. 程式人生 > 資料庫 >python 通過SSHTunnelForwarder隧道連線redis的方法

python 通過SSHTunnelForwarder隧道連線redis的方法

背景:我司Redis伺服器使用的亞馬遜服務,本地需要通過跳板機,然後才有許可權訪問Redis服務。

連線原理:使用SSHTunnelForwarder模組,通過本地22埠ssh到跳板機,然後本地開啟一個轉發埠給跳板機遠端Redis服務使用。

兩種思路:

1、通過SSHTunnelForwarder,paramiko模組,先ssh到跳板機,然後在跳板機上(或者內部伺服器上),獲取到許可權,然後遠端Redis。

2、使用SSHTunnelForwarder模組,通過本地22埠ssh到跳板機,然後本地開啟一個轉發埠給跳板機遠端Redis服務使用。

思路一:

private_key_path = '/Users/xxx/.ssh/id_rsa'
rsaKey = paramiko.RSAKey.from_private_key_file(private_key_path)

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(跳板機或者內網伺服器IP或者域名,22,username,rsaKey)
stdin,stdout,stderr = ssh.exec_command('redis-cli -h {} -p {} -n {} {}'.format(host,port,db,script))
result = stdout.read(),stderr.read()
for out in result: # 需要通過迴圈拿到stdout,否則為空值
  if out:
    return out

類似:

import paramiko
from sshtunnel import SSHTunnelForwarder

with SSHTunnelForwarder(
  (REMOTE_SERVER_IP,443),ssh_username="",ssh_pkey="/var/ssh/rsa_key",ssh_private_key_password="secret",remote_bind_address=(PRIVATE_SERVER_IP,22),local_bind_address=('0.0.0.0',10022)
) as tunnel:
  client = paramiko.SSHClient()
  client.load_system_host_keys()
  client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  client.connect('127.0.0.1',10022)
  # do some operations with client session
  client.close()

print('FINISH!')

方法二:

# 使用SSHTunnelForwarder隧道,通過跳板機連結Redis
with SSHTunnelForwarder(
    ('xxx.xxx.xx.xx',# 跳板機
    ssh_username=username,ssh_pkey="/Users/xxx/.ssh/id_rsa",remote_bind_address=('xx.xx.xx.xxx',6379),# 遠端的Redis伺服器
    local_bind_address=('0.0.0.0',10022) # 開啟本地轉發埠
) as server:
  server.start() # 開啟隧道
  print(server.local_bind_port)
  # 本地通過local_bind_port埠轉發,利用跳板機,連結Redis服務
  cls.red = redis.Redis(host='127.0.0.1',port=server.local_bind_port,db=db,decode_responses=True)
  server.close() # 關閉隧道

Advice:

一般跳板機是個乾淨的機器,公司內網伺服器大部分不會給許可權或者有redis-client客戶端,因此推薦使用方法2。

SSHTunnelForwarder使用:https://pypi.python.org/pypi/sshtunnel/

以上這篇python 通過SSHTunnelForwarder隧道連線redis的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。