python 通过SSHTunnelForwarder隧道连接redis的方法

yipeiwu_com6年前Python基础

背景:我司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客户端,因此推荐使用方法2。

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

以上这篇python 通过SSHTunnelForwarder隧道连接redis的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

解决tensorflow模型参数保存和加载的问题

终于找到bug原因!记一下;还是不熟悉平台的原因造成的! Q:为什么会出现两个模型对象在同一个文件中一起运行,当直接读取他们分开运行时训练出来的模型会出错,而且总是有一个正确,一个读取...

用Python的urllib库提交WEB表单

复制代码 代码如下:class EntryDemo( Frame ): """Demonstrate Entrys and Event binding""" chosenrange =...

详解python破解zip文件密码的方法

详解python破解zip文件密码的方法

1、单线程破解纯数字密码 注意: 不包括数字0开头的密码 import zipfile,time,sys start_time = time.time() def extract()...

python根据时间生成mongodb的ObjectId的方法

本文实例讲述了python根据时间生成mongodb的ObjectId的方法。分享给大家供大家参考。具体分析如下: mongodb的_id为ObjectId类型,ObjectId内是包含...

对python中使用requests模块参数编码的不同处理方法

对python中使用requests模块参数编码的不同处理方法

python中使用requests模块http请求时,发现中文参数不会自动的URL编码,并且没有找到类似urllib (python3)模块中urllib.parse.quote("中文...