使用autossh实现开机创建ssh tunnel的方法以及shell脚本.


 有时候回需要到ssh tunnel,手动使用ssh 创建这些并没有太大的问题,可是如果尝试开机启动,写个shell脚本并在rc.local里面运行这个脚本并不成功,原因也不得而知。 

后来发现了autossh这东东,不单单能够静默模式创建ssh tunnel还能设置自动检测,并自动尝试链接的选项。


本文附件提供的脚本,需要放置在/etc/ini.d/目录下,并使用chmod +x 修改权限。然后也有必要使用update-rc.d service defaults添加入开机启动服务。

当然不要忘记修改脚本中的配置信息。

然后就能够在开机时候自动创建ssh tunnel了。 enjoy it.


#! /bin/bash

# For each tunnel; make a uniquely named copy of this template.


## SETTINGS
#
# autossh monitoring port (unique)
MPORT=54321
# the ssh tunnel to setup
TUNNEL="-L 2003:localhost:2003"
# remote user
RUSER="socieer"
# remote server
RSERVER="socieer.axxeo.de"
# You must use the real autossh binary, not a wrapper.
DAEMON=/usr/lib/autossh/autossh
#
## END SETTINGS

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

NAME=`basename $0`
PIDFILE=/var/run/${NAME}.pid
SCRIPTNAME=/etc/init.d/${NAME}
DESC="the tunnel"

test -x $DAEMON || exit 0

export AUTOSSH_PORT=${MPORT}
export AUTOSSH_PIDFILE=${PIDFILE}
ASOPT=${TUNNEL}" -f -N "${RUSER}"@"${RSERVER}

#  Function that starts the daemon/service.
d_start() {
   start-stop-daemon --start --quiet --pidfile $PIDFILE       --exec $DAEMON -- $ASOPT
   if [ $? -gt 0 ]; then
       echo -n " not started (or already running)"
   else
       sleep 1
       start-stop-daemon --stop --quiet --pidfile $PIDFILE       --test --exec $DAEMON > /dev/null || echo -n " not started"
   fi

}

#  Function that stops the daemon/service.
d_stop() {
   start-stop-daemon --stop --quiet --pidfile $PIDFILE       --exec $DAEMON       || echo -n " not running"
}


case "$1" in
  start)
   echo -n "Starting $DESC: $NAME"
   d_start
   echo "."
   ;;
  stop)
   echo -n "Stopping $DESC: $NAME"
   d_stop
   echo "."
   ;;

  restart)
   echo -n "Restarting $DESC: $NAME"
   d_stop
   sleep 1
   d_start
   echo "."
   ;;
  *)
   echo "Usage: $SCRIPTNAME {start|stop|restart}" >&2
   exit 3
   ;;
esac

exit 0


本文出自 “EIT流浪汉” 博客,请务必保留此出处http://zicowarn.blog.51cto.com/3815716/1653604

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。