home January 01, 2017

OpenSSH Distributed SSH shell


OpenSSH is a set of utilities to allow you to connect to a remote machine through an encrypted tunnel. You can use it as a terminal connection or to tunnel any data through a VPN interface. OpenSSH is a FREE version of the SSH suite of network connectivity tools that increasing numbers of people on the Internet are coming to rely on. Many users of telnet, rlogin, ftp, and other such programs might not realize that their password is transmitted across the Internet unencrypted, but it is. OpenSSH encrypts all traffic (including passwords) to effectively eliminate eavesdropping, connection hijacking, and other network-level attacks.OpenSSH FAQ

Distributed SSH shell script

If you have many machines to take care of you can setup ssh keys on each of them from a central ssh key server. This way you can ssh to the key server and then ssh to any other machine with the key without a password. Working with one machine at a time is fine, but what if you need to work on many machines doing the same task over and over again?

This is a simple shell script you can use to connect to many machines and execute the same commands on all of them from your centralized key server.

#!/usr/local/bin/bash
#
## moneyslow.com Distributed SSH 
##   sh batch_ssh.sh "machine1 machine2" 'uptime'
##   sh batch_ssh.sh "`cat servers.txt`" 'uptime'
#

## global options
TIMEOUT=3
OUTLOG=/tmp/remote-out-$$.log

## command line options
MACHINES=$1;shift
COMMAND=$1;shift

## distribute commands to machines
for machine in $MACHINES
 do
    echo $machine >>$OUTLOG.$machine
    ssh -q -oStrictHostKeyChecking=no -oBatchMode=yes -oCompression=yes \
      -oConnectTimeout=$TIMEOUT -l root $machine $COMMAND >>$OUTLOG.$machine \
      2>>$OUTLOG.$machine &
 done

# wait for all processes to finish
wait

## print logs and delete tmp files
cat $OUTLOG.*
rm -f $OUTLOG.*

How about a Distributed SCP shell script ?

This is a companion script to the distributed SSH script above. The is for scp'ing a local file on your key server to a list of servers. Just provide three arguments in the form of the list of machines, the name of the local file to distribute and the location on the remote server you want the file to be placed.

#!/usr/local/bin/bash
#
## moneyslow.com Distributed SCP 
##   sh batch_scp.sh "machine1 machine2" 'local_file' 'remote_directory'
##   sh batch_scp.sh "`cat servers.txt`" 'myfile.txt' '/root/'
#

## global options
TIMEOUT=3
OUTLOG=/tmp/remote-out-$$.log

## command line options
MACHINES=$1;shift
LOCAL=$1;shift
REMOTE=$1;shift

## distribute commands to machines
for machine in $MACHINES
do
    echo $machine >>$OUTLOG.$machine
    scp -q -oStrictHostKeyChecking=no -oBatchMode=yes -oCompression=yes \
      -oConnectTimeout=$TIMEOUT $LOCAL root@$machine:$REMOTE \
       >>$OUTLOG.$machine 2>>$OUTLOG.$machine &
done

# wait for all processes to finish
wait

## print logs and delete tmp files
cat $OUTLOG.*
rm -f $OUTLOG.*