From Notes Wiki
Revision as of 09:25, 6 June 2019 by Saurabh (talk | contribs) (Created page with "<yambe:breadcrumb self="Systemd based reverse SSH service">CentOS_7.x_OpenSSH_server|OpenSSH server</yambe:breadcrumb> In case anydesk/teamviewer are proving unreliable and r...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
Home > CentOS > CentOS 7.x > Remote access > OpenSSH server > Systemd based reverse SSH service


In case anydesk/teamviewer are proving unreliable and reverse ssh is desirable to an internal server behind NAT via a public server, then use following steps to set it up:

  • Create ssh-keys on both servers
  • Establish trusted ssh from local server to public server and vice-versa on both servers
  • Create /etc/systemd/system/files-reverse-ssh.service with following contents on internal server:
     [Unit]
     Description=files-reverse-ssh service
     After=network.target
     
     [Service]
     Type=simple
     ExecStart=/bin/sh /root/files-reverse-ssh.sh
     Restart=always
     User=root
     Group=root
     
     [Install]
     WantedBy=multi-user.target     
  • chmod 744 /etc/systemd/system/files-reverse-ssh.service
  • Create /root/files-reverse-ssh.sh with following contents on internal server:
     #!/bin/bash
     
     SERVER="files.sunilsanjay.com"
     RPORT=3333
     
     while sleep 60; do
	#Count number of existing connections
	COUNT=$(ps aux | grep root@$SERVER | wc -l)
 	if (( "$COUNT" > 2 )); then
	    echo "SSH already connected, not doing anything extra"
	else
	    # Check SSH Connction is available or not	
	    status=$(ssh -o BatchMode=yes -o ConnectTimeout=30 root@$SERVER echo ok 2>&1)
         
	    #If available connect to remote server
	    if [[ $status == ok ]] ; then
	         echo "Going to start new SSH connection in background"
	         /usr/bin/ssh -o StrictHostKeyChecking=no -o ServerAliveInterval=60 -o ServerAliveCountMax=1 -R $RPORT:127.0.0.1:22 root@$SERVER -N &
	    elif [[ $status == "Permission denied"* ]] ; then
	        echo "Not able to connect due to permission denied error"
	    else
	        echo "Error: $status"
         fi
     fi
     done     
     exit 0
  • Set required permissions and start service
chmod 744 /root/files-reverse-ssh.sh
systemctl daemon-reload
systemctl enable files-reverse-ssh
systemctl start files-reverse-ssh
systemctl status files-reverse-ssh


Refer:



Home > CentOS > CentOS 7.x > Remote access > OpenSSH server > Systemd based reverse SSH service