simplify your daily ssh usage… even more…

On MeyerMillerSmith.com I recently posted this one:

Typing ssh commands can be very annoying but it doesn’t has to. There’s a quite nice way to simplify your daily admin life: shell scripts.

Okay, let’s say we have a dozen servers which we regularly connect to. Let’s assume that they have quite long names and we don’t want to type them every time. Surely, we could simply use Ctrl-i, but if the server name is not in the history any more, we will have to type again – and loose time.

The solution is quite easy. Create the following script connect-to-server.sh and save it i.e. under /usr/local/bin

ssh `basename $0`

Don’t forget to

chmod +x /usr/local/bin/connect-to-server.sh

Done? Great! Now we just need symlinks like this

ln -s /usr/local/bin/connect-to-server.sh \
this-is-the-name-of-the-server.my-companies-name.com

So if you want to connect to you server just enter the first letters of the server’s name and hit Tab to autocomplete, then Enter and you’re done.


Okay. This was quite cool… but not cool enough… I still had to manually symlink.

Now I wanted to extend the little script to add a new host:

#!/bin/bash
if [ $1 ]
then
 echo "adding new host: $1"
 if [ `id -u` == "0" ]
 then
 ln -s $0 `dirname $0`/$1
 else
 echo "need root privileges... using sudo..."
 sudo ln -s $0 `dirname $0`/$1
 fi
else
 echo "connecting to `basename $0`"
 ssh `basename $0`
fi

So what does it? If we don’t get a parameter, we assume that we’re in SSH mode and connect to the host represented through the filename. If we have a parameter, we assume that this is the new host to connect to and add a new host. As we are writing in /usr/local/bin we have to check whether we have root privileges. If not, we use sudo. That’s all.

Here you can download the script if you don’t want to copy & paste.

This entry was posted in howto, Linux and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>