http://www.experts-exchang
The bash script is fine if you have set up a keypair between the server you are runing on and all of the remote servers, and that keypair doesn't require a passphrase.
If you need to log in to the remote server, what you need to use is something like "expect" (which should already be on your UNIX box - if not, it should be easy to install it). It only needs to be on the master server (the one from whcih you are connecting).
In the script with the servers, also have the userid and password for each slave server, and the command you want to run (in case it varies from server to server). For example:
server1 user1 password1 command1
server2 user2 pass2 cmd2
and so on.
Then write an expect script like:
#!/usr/bin/expect --
set logindone 0
set targethost [lindex $argv 0]
set targetuser [lindex $argv 1]
set targetpasswd [lindex $argv 2]
set targetcmd [lindex $argv 3]
spawn ssh $targetuser\@$targethost
while 1 {
# Log in and wait for unix prompt - adjust if your prompt is differnt
expect {
"login:" {if $logindone==0 {set logindone 1
send "$targetuser\n"}}
"sword:" {send "$targetpasswd\r"; set logindone 1}
"\\$ $" {break}
"\\# $" {break}
timeout {send_user "Timed out logging in to $targethost as $targetuser\n"; exit}
}
}
if {[string length $targetcmd] != 0} {
# Send command
send $targetcmd\r";
# Allow 30 seconds for command to complete
set timeout 30
# Wait for unix prompt - adjust if your prompt is differnt
expect {
"\\$ " {exit}
"\\# " {exit}
timeout {send_user "Timed out waiting for command $targetcmd to run on $targethost as $targetuser\n"; exit}
}
}
# If no command has been entered, become an interactive shell, and exit when the user logs out of that shell
interact
The expect script logs in to the remote server using Expect, then runs the optional command. If you don't have a command, the script becomes an interactive shell. When you finally log out of that shell, the expect script terminates.
Call the expect script from a shell script such as:
#!/bin/sh
cat ~/file_with_serverst.txt | while read srvr nam psswd cmd
do
expect ~/myssh.exp "$srvr" "$nam" "$psswd" "$cmd" > ${srvr}.out
done
There may well be more succint ways of running the above shell script, but the above has the benefit of clarity and flexibility. A very terse version would be:
awk '{print "expect myssh.exp ",$0," > ",$1,".out";}' file_with_servers.txt | sh
You will of course have to adjust any paths specified (if, for example, your "expect" isn't in /usr/bin.
Main Topics
Browse All Topics





by: TintinPosted on 2009-03-11 at 14:13:30ID: 23862436
The way I would do it is to install cygwin, so that you have bash and a ssh client, then you can write a simple shell script to do the task, eg:
Select allOpen in new window