使用格式:

转发到远端: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隧道

这样就不用每次都手动重连了

 

 
  
  1. #coding:utf-8 
  2. import os 
  3. import time 
  4.  
  5.  
  6. import threading 
  7. import MySQLdb 
  8.  
  9. import sys 
  10. import signal 
  11.  
  12. flags={'flag':0,'c':0
  13.  
  14. def handler(signum, frame): 
  15.     flags['c']+=1#计数器 
  16.     print "get an signal:", signum,flags['c'
  17.     flags['flag']=1 
  18.      
  19.     sys.exit() 
  20.  
  21. signal.signal(signal.SIGINT, handler) 
  22. signal.signal(signal.SIGTERM, handler) 
  23. signal.signal(3, handler) 
  24.  
  25. #while not flags['flag']:pass 
  26.  
  27. ''''' 
  28. sudo  -H -u web ssh  -C -f -N -g -L  3309:0.0.0.0:3306 host7 
  29. sudo  -H -u web ssh  -C -f -N -g -L  3304:0.0.0.0:3306 host3 
  30. sudo  -H -u web ssh  -C -f -N -g -L  3302:0.0.0.0:3306 host10 
  31.  
  32. ''' 
  33. maps=[ 
  34.  
  35. {'port':3309,'sh':'sudo  -H -u web ssh  -C -f -N -g -L  3309:0.0.0.0:3306 host7'
  36. 'user':'search','pass':'searchweb' ,'db':'','kill':'grep ssh | grep host7 | grep 3309 '}, 
  37. {'port':3304,'sh':'sudo  -H -u web ssh  -C -f -N -g -L  3304:0.0.0.0:3306 host3'
  38. 'user':'search','pass':'searchweb' ,'db':'','kill':'grep ssh | grep host3 | grep 3304 '}, 
  39. {'port':3302,'sh':'sudo  -H -u web ssh  -C -f -N -g -L  3302:0.0.0.0:3306 host10'
  40. 'user':'search','pass':'searchweb' ,'db':'','kill':'grep ssh | grep host10 | grep 3302 '
  41.  
  42.  
  43. def monitor(maps): 
  44.     ''''' 
  45.     监控各个链接是否正常 
  46.     ''' 
  47.     threads=[] 
  48.     for conf in maps: 
  49.         t=threading.Thread(target=monitor_one,args=(conf,)) 
  50.         t.setDaemon(True
  51.         threads.append(t) 
  52.     for t in threads: 
  53.         t.start() 
  54.     signal.pause() 
  55.     for t in threads: 
  56.         t.join() 
  57.  
  58.          
  59. def monitor_one(conf): 
  60.     print 'test',conf 
  61.     while not flags['flag']: 
  62.         try
  63.             #测试联通性 
  64.             conn=MySQLdb.connect('127.0.0.1',user=conf['user'],passwd=conf['pass'],db=conf['db'] ,port=conf['port']) 
  65.             print conn.ping() 
  66.             conn.close() 
  67.              
  68.             print 'ok' 
  69.             time.sleep(20
  70.             continue 
  71.         except Exception,e: 
  72.             print str(e) 
  73.             print type(e) 
  74.             print 'try connect:',conf['sh'
  75.             kill_sh='ps aux | '+conf['kill']+'| grep -v grep | awk \'{print "kill -9  " ,$2 }\' | sh' 
  76.             print kill_sh 
  77.             os.system(kill_sh) 
  78.             os.system(conf['sh']) 
  79.             time.sleep(30
  80.      
  81.      
  82. monitor(maps)