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', 22), # 跳板機

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客戶端,

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章