The first part: expect explanation
Expect allows us to automatically log on to remote machines, and can implement automatic remote execution of commands. Of course, if you use key authentication without a password, you can also implement automatic logon and automatic remote command execution. But when we can't use key verification, we don't have a choice. So, just know the other machine's account number and password can be implemented through the expect script login and remote command.
Expect can be implemented: 1 remote sync files with the rsync command
2 Remote Execute command, use SSH remote login Execute command
Before using expect, you need to install expect:
Yum Install-y expect
#!/usr/bin/expect #抬头和SHELL类似
Set Host "192.168.11.102" #expect语句, equivalent to host=192.168.11.102
set passwd "123456" #passwd =123456
spawn ssh [email protected] $host #expect语句, behind the command of the shell landing machine.
expect { #expect语句模块, the first time you log in, you will be prompted yes or No. Automatic execution
"yes/no" {send "yes\r"; Exp_continue} does not execute if it is not the first time it is logged in.
"Assword:" {send "$passwd \ r"} #匹配最后几个字符assword, sending the password variable.
}
Interact
The above is a fixed syntax for expect, where the Expect statement module is required.
Script saved to 1.expect
Increase execution Permissions chmod +x 1.expect
Executes the script./1.expect ( Note that there are no spaces and requires X permission ) or Expece 1.expect ( x permission not required )
Note that the \ r in the script means a carriage return
1.7-Automatic Login Expect script