Posts Tagged ‘expect shell’

Using expect to auto login and execute commands(relieve you from tedious login and typing)

November 19th, 2010 Comments off

Another imagination:

You have 100 servers.Now you've got a task.The boss needs to create a directory under /root and put some files under it.

What would you do next?Just be honestly and sincerely and start log in ssh then use mkdir to create directory,then use sftp or even ftp to put the files under the directory?

That would tire you so much,sour you hands and mind.Now let one line bash shell script to help you.

Here goes the general idea about the solution:

1.Write a bash script with multiple parameters.Each two of the parameters match the ip address and password to your ssh root account.

2.Now the script runs.It auto get the two parameters as a pair,and use expect to auto answer to interactive output of ssh command('yes' to 'Are you sure you want to continue connecting (yes/no)?',and your password parameter to ''s password:').

3.After log in the remote server using ssh,the script download a script from url you designate.Like the download,use 'sh ./' to run it which has command 'mkdir' and ftp get in it.

Above is the skeleton of the design.Now let's go to the code area:
while [ $# -ne 0];
shift 2
CMD='curl -o && sh ./'
echo ''>/root/.ssh/known_hosts #first,delete known_hosts to let the expect "*yes*" work
/usr/bin/expect <<EOF
spawn ssh -lroot -p22 $sshhost $CMD
set timeout 60 #1 minute,command will be executed on the remote server even though 60s
expect "*yes*"
send "yes\r"
expect "*password*"
send "$password\r"
expect eof
Ok.Name the above shell script,grant it with execute privilege.

Then,create your mkdir and ftp get files(You can refer to here to auto-ftp get files).

Now use ./ first_server_ip first_server_ip_password second_server_ip second_server_ip_password third_server_ip third_server_ip_password forth_server_ip forth_server_ip_password.You can assign as many pairs ip/password to the parameter position as you want.Just be relieved,your work will be perfectly done as you wish!