Using expect to auto login and execute commands(relieve you from tedious login and typing)
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 '[email protected]'s password:').
3.After log in the remote server using ssh,the script download a script from url you designate.Like http://yourblog.com/mkdir_and_put_files_in_it.sh.After the download,use 'sh ./mkdir_and_put_files_in_it.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];
CMD='curl -o nginx_log.sh http://yourblog.com/mkdir_and_put_files_in_it.sh && sh ./mkdir_and_put_files_in_it.sh'
echo ''>/root/.ssh/known_hosts #first,delete known_hosts to let the expect "*yes*" work
spawn ssh -lroot -p22 $sshhost $CMD
set timeout 60 #1 minute,command will be executed on the remote server even though 60s
Ok.Name the above shell script auto_sh.sh,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 ./auto_sh.sh 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!