使用格式:
转发到远端:ssh -C -f -N -g -L 本地端口:目标IP:目标端口 用户名@目标IP
ssh -C -f -N -g -L 3307:0.0.0.0:3306 host101
本机可以通过
mysql -uroot -p -P3307 -h 0.0.0.0 通过本机来链接远程数据,很方便
适合场景:
代码在本机调试,数据库在远程,但是端口3306没有对外开放,可以通过ssh映射回来
这里有一个问题 它会自动断开
又写来一个脚本来自动重新建立ssh隧道
这样就不用每次都手动重连了
- #coding:utf-8
- import os
- import time
- import threading
- import MySQLdb
- import sys
- import signal
- flags={'flag':0,'c':0}
- def handler(signum, frame):
- flags['c']+=1#计数器
- print "get an signal:", signum,flags['c']
- flags['flag']=1
- sys.exit()
- signal.signal(signal.SIGINT, handler)
- signal.signal(signal.SIGTERM, handler)
- signal.signal(3, handler)
- #while not flags['flag']:pass
- '''''
- sudo -H -u web ssh -C -f -N -g -L 3309:0.0.0.0:3306 host7
- sudo -H -u web ssh -C -f -N -g -L 3304:0.0.0.0:3306 host3
- sudo -H -u web ssh -C -f -N -g -L 3302:0.0.0.0:3306 host10
- '''
- maps=[
- {'port':3309,'sh':'sudo -H -u web ssh -C -f -N -g -L 3309:0.0.0.0:3306 host7',
- 'user':'search','pass':'searchweb' ,'db':'','kill':'grep ssh | grep host7 | grep 3309 '},
- {'port':3304,'sh':'sudo -H -u web ssh -C -f -N -g -L 3304:0.0.0.0:3306 host3',
- 'user':'search','pass':'searchweb' ,'db':'','kill':'grep ssh | grep host3 | grep 3304 '},
- {'port':3302,'sh':'sudo -H -u web ssh -C -f -N -g -L 3302:0.0.0.0:3306 host10',
- 'user':'search','pass':'searchweb' ,'db':'','kill':'grep ssh | grep host10 | grep 3302 '}
- ]
- def monitor(maps):
- '''''
- 监控各个链接是否正常
- '''
- threads=[]
- for conf in maps:
- t=threading.Thread(target=monitor_one,args=(conf,))
- t.setDaemon(True)
- threads.append(t)
- for t in threads:
- t.start()
- signal.pause()
- for t in threads:
- t.join()
- def monitor_one(conf):
- print 'test',conf
- while not flags['flag']:
- try:
- #测试联通性
- conn=MySQLdb.connect('127.0.0.1',user=conf['user'],passwd=conf['pass'],db=conf['db'] ,port=conf['port'])
- print conn.ping()
- conn.close()
- print 'ok'
- time.sleep(20)
- continue
- except Exception,e:
- print str(e)
- print type(e)
- print 'try connect:',conf['sh']
- kill_sh='ps aux | '+conf['kill']+'| grep -v grep | awk \'{print "kill -9 " ,$2 }\' | sh'
- print kill_sh
- os.system(kill_sh)
- os.system(conf['sh'])
- time.sleep(30)
- monitor(maps)
转载于:https://blog.51cto.com/shendongming/610090