본문 바로가기

리눅스/Ubuntu

RST (Reverse SSH Terminal)

-공인IP 설정된 서버 ssh설정-
/etc/ssh/sshd_config에서
GatewayPorts yes 설정

 

RST 설정 커맨드 

ssh -fN -R [터널 열어줄 포트]:localhost:[열린터널로 사용할 실제포트] [서버계정]@[공인IP할당된서버]

 

 

 

쉘 스크립트 파일 예시 

 

#!/bin/sh

# $REMOTE_PORT is the remote port number that will be used to tunnel
# back to this system
#REMOTE_PORT=${PORT_PREFIX}

# $REMOTE_HOST is the name of the remote system
REMOTE_HOST= 서버 IP 

for PORT in "80" "3306"
do
   # $COMMAND is the command used to create the reverse ssh tunnel
   #COMMAND="autossh -f -N -R *:$REMOTE_PORT:localhost:22 $REMOTE_HOST"
   # COMMAND="ssh -fN -R ${PORT}:localhost:${PORT} 사용자 계정@$REMOTE_HOST"
   SSH="ssh -fN -R 50002:localhost:22 사용자 계정@$REMOTE_HOST"
   API="ssh -fN -R 50000:localhost:50000 사용자 계정@$REMOTE_HOST"
   SECUWEB="ssh -fN -R 50001:localhost:50001 사용자 계정@$REMOTE_HOST"
   MYSQL="ssh -fN -R 50003:localhost:3306 사용자 계정@$REMOTE_HOST"
   echo $COMMAND

   # Is the tunnel up? Perform two tests:

   # 1. Check for relevant process ($COMMAND)
   #pgrep -f -x "$COMMAND" > /dev/null 2>&1 || $COMMAND
   pgrep -f -x "$SSH" > /dev/null 2>&1 || $SSH
   pgrep -f -x "$API" > /dev/null 2>&1 || $API
   pgrep -f -x "$SECUWEB" > /dev/null 2>&1 || $SECUWEB
   pgrep -f -x "$MYSQL" > /dev/null 2>&1 || $MYSQL

   # 2. Test tunnel by looking at "netstat" output on $REMOTE_HOST
   ssh jkkim@$REMOTE_HOST netstat -an | egrep "tcp.*:${REMOTE_PORT}$PORT.*LISTEN" \
      > /dev/null 2>&1
   if [ $? -ne 0 ] ; then
      #pkill -f -x "$COMMAND"
      pkill -f -x "$SSH"
      pkill -f -x "$API"
      pkill -f -x "$SECUWEB"
      pkill -f -x "$MYSQL"
      #$COMMAND
      $SSH
      $API
      $SECUWEB
      $MYSQL
   fi
done

 

위 예시 코드와 같이 스크립트를 만들어준다.

부팅시 자동 시작하도록 rc.local 설정과 crontab 으로 일정 시간마다 끊기지 않게 스크립트를 돌려주면 완성!