SSH connection automation

Part of my daily routine involves accessing and managing a considered amount of remote servers through the SSH protocol. I use screen a lot to ease the job by having a couple of windows opened on each server, so avoiding multiple connections to the same server. By using screen not only helps me grouping server windows altogether in one console window/tab but also is a time saver in those days when network connection is not in its glory days allowing me to reattach it and carrying on being productive (*sighs*).

But, before connecting to all those machines, I used to repeat over and over the same setup steps:
  1. send my public key to server
  2. upload my screen configuration file
  3. create an alias (because ssh'ing manually is a truly hassle each time I want to connect!) to connect to the server and reattach or create a new screen session
  4. Change its permissions to 700 (security freak? Oh well...)

Four repetitive and forgettable operations that could all be avoided, sparing me some minutes of my precious time. But no more!

Here is a handy Bash script I wrote the other day (at last!):
#!/bin/bash
# $1 = [remote_user@]remote_host
# $2 = [alias name]
BIN=$HOME/bin
if [ "$#" -lt 1 ] || [ "$#" -gt 2 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
echo "Usage: $0 [user@]machine [alias]" >&2
exit 1
fi
if [ "$#" -eq 2 ]; then
(
cat <<EOF
#!/bin/bash
ssh $1 -t screen -x -R
EOF
) > $BIN/$2
chmod u=rwx,go= $BIN/$2
fi
ssh-copy-id -i ~/.ssh/id_rsa.pub $1 > /dev/null 2>&1
scp ~/.screenrc $1:~/ > /dev/null 2>&1
exit 0

Copy and paste this code to a file in your $PATH (mine is $HOME/bin/setup-machine) and give it execution permission (chmod u=rwx,go= ).
Obvious to some, though may not be to others, here is an usage example:
Macnux:~ carlos$ setup-machine -h
Usage: /Users/carlos/bin/setup-machine [user@]machine [alias]
Macnux:~ carlos$ setup-machine cgoncalves@cgoncalves.info cgoncalves
cgoncalves@cgoncalves.info’s password: *****************
Macnux:~ carlos$ cat bin/cgoncalves
#!/bin/bash
ssh cgoncalves@cgoncalves.info -t screen -x -R
Macnux:~ carlos$ cgoncalves
[SSH connection established and attached to screen]

2 comentários:

João Almeida said...

Convite para hackmeeting no Porto

http://hackmeeting.hacklaviva.net

28,29 e 30 de Outubro de 2011

O primeiro hackmeeting em Portugal, a juntar hackers por toda a Península Ibérica.

Brianna Simmons said...

Lovely blog you have heree

top