#!/usr/bin/expect -f # Author: Kevin P. Inscoe . # File: doroot.exp # Date of creation: May 5, 2004. # Warranty: None expressed or implied. # License: The Open Software License. V1.1 http://www.opensource.org/licenses/osl.php # # OSI Certified Open Source Software. http://www.opensource.org/licenses/ # # Prerequisites: Expect 5.0 (minimum). exp_version -exit 5.0 # The purpose of this program is # # ssh to remote host and executes command sending output to stdout. # if {$argc!=3} { send_user "usage: doroot.exp hosttab-file non-root-user-id "command"\n" exit } # Grab cmd line arguments set file [lindex $argv 0] set luser [lindex $argv 1] set cmd [lindex $argv 2] # Prompt for non-root password set timeout -1 # set no echo stty -echo send_user "Non-root password?\ " expect_user -re "(.*)\n" # return echo stty echo send_user "\n" set lpass $expect_out(1,string) # Proc proc do_root {luser host lpass passwd cmd} { # sign on to remote host as low-level account and pull the file from this host # Variables set prompt "*doroot*" set rprompt "root*doroot*" set timeout 5 spawn ssh -l $luser $host expect "Are you sure you want to continue connecting" { send "yes\r" } expect "password:" { send "$lpass\r" } exec sleep 3 send "sh\r" exec sleep 3 # set a known prompt so we can expect it send "PS1=$prompt; export PS1\r" exec sleep 3 expect "$prompt" send "su -\r" expect "Password:" send "$passwd\r" exec sleep 3 send "sh\r" exec sleep 3 send "PS1=$rprompt; export PS1\r" exec sleep 3 expect "$rprompt" send_user "\n+++ Beginning Command as root: $host +++\n" # Need to capture output and display send "$cmd\r" expect "$rprompt" send_user "\n+++ Ended Command as root: $host +++\n" # Display command output expect "$rprompt" # Exit sh from root send "exit\r" exec sleep 3 # Exit root send "exit\r" # Now back at non-root login expect "$prompt" # Exit sh from non-root send "exit\r" exec sleep 3 # Exit from non-root send "exit\r" exec sleep 5 close; wait send_user "\n" } # process hosttab set in [open $file r] while {[gets $in line] != -1} { set host [lindex [split $line ":"] 0] set passwd [lindex [split $line ":"] 3] do_root $luser $host $lpass $passwd $cmd } close $in send_user "\ndoroot.exp: Complete.\n" exit