A quick little expect script

Sometimes you are in a pinch and have to quickly check for something in 1000 servers. Yes , yes I know you can have puppet facts and mcollective but what if you don’t? What if you have puppet but it takes months or days to get a manifest written tested and run against production server. I wish mcollective would have a way of simply running a command against its inventory but so far I haven’t found a easy way to do so. But there is no need to despair. All you have to do is remember the age old adage that “old is gold” and look at the treasurechest of unix to find a hidden (not so hidden – pretty well known actually) gem called “expect” . If you have expect installed or if you can install expect on a system here is a small script to use expect to automatically run some commands in a remote system. There are some assumptions of course before running the script and they are:

  1. This assumes that your login/password is same in all the hosts. For example if you have a centralized login solution.
  2. Also it assumes that if you want to parse the output of the remote commands later you will capture the output by using either a combination of script or screen command (see below):
  3. The list of remote hosts is in a file called “hostlist”


#!/bin/sh
CMD="sudo grep -i permitroot /etc/ssh/sshd_config"
echo "Enter Password:"
read -s PASS
cat hostlist | while read line
do
HOST=$line
CMD1="echo HOSTNAME:$HOST"
expect - << EOF
set timeout -1
spawn ssh -o StrictHostKeyChecking=no -t $HOST
expect "ssword:$" { send -- "$PASS\r" }
expect "\$ "
send -- "$CMD\r"
expect "ssword:$" { send -- "$PASS\r" }
expect "\$ "
send -- "$CMD1\r"
expect "\$ "
send -- "logout"
EOF
done


To execute this script (lets assume it is called remote_ex.sh) you can do the following:
# screen
# script remote_ex.sh.log
<--- All script output will be colllected in this log file ---->
#./remote_ex.sh
Press Ctrl-a and "d" to detach the screen
<----- Later you can log in and check the progress by attaching back to the screen.

Leave a Reply