in Servers, Web Development

Developer Shortcut – Bash script menu to connect to servers via SSH

Managing various servers can get quite repetitive entering various IP address’s or even remembering them in the first place! Lets solve that with a simple bash script depending on wether your doing this from a server or on your local environment the location of your bash_profile may be different but the steps are the same.

Your profile is usually in /home/users/yourname/.bash_profile

nano /home/users/yourname/.bash_profile

Open up this file and add a new line at the bottom

alias connect='bash /Users/yourname/menu.sh'

What this is doing is saying when I type connect in the terminal run menu.sh, you could change this word to another word of your choice.

Change the location of menu.sh to suit your needs, save and close.

Make a new file called /Users/yourname/menu.sh and inside put:

#!/bin/bash
# Bash SSH Menu

PS3='Please enter your choice: '
options=("mysql" "web"  "Quit")
select opt in "${options[@]}"
do
    case $opt in
        "web")
            echo "Connecting to web 10.0.0.1"
            ssh [email protected]
            break
            ;;
        "mysql")
            echo "Connecting to mysql 10.0.0.2"
            ssh [email protected]
            break
            ;;
"Quit")
            break
            ;;
        *) echo invalid option;;
    esac
done

Here we are setting up the menu options in the first line, in this case mysql and web which refer to my web and mysql server but these could be named whatever you like, the next part is similar to a switch statement in PHP, for each case print that we are connecting and then SSH to the IP. Finally a quit option and a default option to handle invalid requests.

If you use this in conjunction with SSH keys it will save a lot of time.

Write a Comment

Comment