Preface:
SSH command. No password parameter is specified. so that when using the SSH command in the script, you must manually enter the password to continue the execution. this makes the automatic execution of scripts very poor, especially when the number of machines corresponding to SSH is large. this article describes two methods: one is to use the CT script and the other is to use sshpass.
*) Implemented by using CT scripts
1. Keep CT is not a built-in tool and needs to be installed
Yum install keep CT-y
2. Compile CT script rules
1 .[#! /Usr/bin/expect] informs the code in the system script to use that shell for execution. Note: This line must be in the first line of the script. 2. [set timeout <timeout>] Basically anyone who knows English knows that this is a time-out period. Now you only need to remember that the unit of time is second. timeout-1 is never timeout 3. [spawn <command>] spawn is an internal audit CT command that can be executed only after entering the audit CT environment. It mainly shells Subsequent commands to pass interactive commands. 4. [secondary CT "<match_string>"] secondary CT is also an internal command of secondary CT. Don't be surprised. 5. [Send "<response_string> \ r"] the interactive action is executed here, which is equivalent to the action of manually inputting content. Tip: do not forget to add "\ r" to the end of the command string. If the exception waits, check it. 6. [interact] After the execution is complete, the interactive state is maintained, and the control is handed over to the console. to exit, use reverse ct eof instead of 7. $ argv parameter array the reverse CT script can accept parameters passed from Bash. you can obtain it using [lindex $ argv N]. N starts from 0, indicating the first, second, and third .... parameters
Simple Example:
#! /usr/bin/expectspawn sudo apt-get install vimexpect "password"send "<password>\r"expect eof
This avoids entering the sudo password.
3. Case writing
#! /bin/bashfunction auto_ssh() { username_server="$1" password="$2" command="$3" ssh_warpper=" spawn ssh -o StrictHostKeyChecking=no $username_server \"$command\"\n expect { \n -nocase \"password:\" {send \"$password\r\"} \n } \n expect eof \n " echo -e $ssh_warpper | /usr/bin/expect}auto_ssh [email protected] 123456 "ifconfig eth0"
Comments:
Ssh-O stricthostkeychecking = no check is performed on the machine that is logged on for the first time, avoiding manual input of yes/no
Echo-e $ ssh_warpper,-e parameter for subsequent strings, enable escape support switch.
*) Sshpass usage
Address: http://sourceforge.net/projects/sshpass/
1. Install sshpass
Wget http://nchc.dl.sourceforge.net/project/sshpass/sshpass/1.05/sshpass-1.05.tar.gz
Tar zxvf sshpass-1.05.tar.gz
CD sshpass-1.05
./Configure
Make & make install
2. Explanation of the sshpass command
3. Simple sshpass example
Sshpass-P <password> SSH <username >@< server_ip> "<command>"