Some of the operation under Linux, sometimes need to do some interaction with the machine, such as the user to switch account password, transfer files to enter the account password login remote machine, etc., but sometimes these actions need to be done in the shell script, At this point, you can use expect to automate the interaction, thus avoiding the need for manual intervention to interrupt the execution of the script.
Core command of Expect: Spawn expect send set
Spawn calling the command to execute
Expect waits for the command prompt to appear, which is the prompt to capture user input:
Send sends values that need to be interacted with instead of manually entering content by the user
Set Variable Value
Interact after the completion of the implementation of the interactive State, the control to the console, this time can be manually operated. If this is not done, it will exit instead of remaining on the remote terminal.
Expect EOF this must be added, corresponding to the spawn to indicate that the capture terminal output information is terminated, similar to IF....ENDIF
(Expect scripts must end with interact or expect EOF, and automating tasks usually expect EOF is enough.) )
Example: Build a scp.sh script to transfer files
#!/bin/shsvr = "9.84.214.35" expect <<! spawn SCP -R [email protected] $svr:/db2info.csv/tmp/db2info.txtexpect {{ "(yes/no)?" " yes\n " expect "*assword:" {{send "1qaz2wsx\n" }} *assword: " {send " 1qaz2wsx\n "}} expect "100%" expect EOF !
Execute./scp.sh will use the account Xman, to log on to the remote machine, which is the terminal will give the prompt information asked if continue to yes/no? If yes, enter the password, and the SCP command will begin to pass the file when the login is successful. Where the code inside the expect{} is pre-determined whether the terminal output content (yes/no)? , if there is an automatic input yes, (send "yes\n"), and then determine whether the output in the back contains *password: ", if any, automatically enter the preset password 1qaz2wsx. So as to achieve the purpose of automatic interaction.
Except with expect <<!. ! The method (here document mode) calls expect in SH, and can of course use Expect-c "" to invoke the expect command in the SH script.
linux--using expect for automatic interaction