今天给大家分享一个python通过SSHTunnelForwarder隧道连接redis的方法。具有很好的参考价值,希望对大家有所帮助。和小编一起来看看吧。背景:我们公司的Redis服务器使用的Amazon服务,需要本地通过跳板访问Redis服务。连接原理:使用SSHTunnelForwarder模块通过本地22端口ssh到跳板机,然后在本地为跳板机远程Redis服务开启一个转发端口。两种思路:1、通过SSHTunnelForwarder和paramiko模块,先ssh到跳板机上,然后在跳板机上(或者内部服务器上)获取权限,然后远程redis。2、使用SSHTunnelForwarder模块通过本地22端口ssh到跳板机,然后在本地为跳板机远程Redis服务开启一个转发端口。外汇返利http://www.kaifx.cn/思路一: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,用户名,rsaKey)stdin,stdout,stderr=ssh.exec_command('redis-cli-h{}-p{}-n{}{}'.format(host,port,db,script))result=stdout.read(),stderr.read()foroutinresult:#需要通过循环获取stdout,否则out则为空:返回类似:importparamikofromsshtunnelimportSSHTunnelForwarderwithSSHTunnelForwarder((REMOTE_SERVER_IP,443),ssh_username="",ssh_pkey="/var/ssh/rsa_key",ssh_private_key_password="secret",remote_bind_address=(local_SERVER_b,2VER_)'0.0.0.0',10022))astunnel:client=paramiko.SSHClient()client.load_system_host_keys()client.set_missing_host_key_policy(paramiko.AutoAddPolicy())client.connect('127.0.0.1',10022)#do与客户端sessionclient.close()print('FINISH!')方法二:#使用SSHTunnelForwarder隧道链接Redis和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)#开启本地转发端口)asserver:server.start()#打开tunnelprint(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()#关闭隧道建议:跳板机一般都是干净的机器,公司内网服务器大多不会授权或者有redis-client客户端。
