Expect is developed by Don Libes based on the Tcl language and is widely used in interactive operations and automated test scenarios, expect allows shell scripts to automate interactive communication without human intervention.
The core function of expect is to perform the matching action and enter the automatic human-computer interaction according to the well-established matching form.
The following Ubantu on the demo to do the case description:
sudo Install expect
To SSH into this machine under $home to create the Kitty folder as an example, the following is the shell script source code.
#!/usr/bin/expect-F
Set timeout 30set param1 [lindex $argv0]spawnSSH-P222[Email protected]127.0.0.1Expect {"(yes/no)?"{Send"yes\r"; Exp_continue}}
Expect"Password:"Send"a123456\r"
expect"@"Send"cd/home/genter\r"
expect"@"Send"mkdir $param 1\r"
Expect"@"Send"exit\r"expect EOF
[#!/usr/bin/expect-f]: Tell the operating system that the script code is executed using expect
[Set timeout 30]: timeout, unit: seconds. Time-out script will automatically execute down
[Set param1 [lindex $argv 0]]: Receives the arguments passed in when the shell script is executed, the parameters are: $argv 0, 1, 2 ...
[Spawn ssh-p 222 [email protected]]: SSH login, expect use Spawn startup script and command session, here to start the SSH command (SSH command will be generated as a child process)
[Expect {"(yes/no)?" {send "yes\r"; Exp_continue}}] : The expect command is used to determine whether a string is contained in the result of the last execution of the command, exp_continue means to continue with the following match
[Expect "Password:" Send "a123456\r"]: The Send command is used to perform an interactive action, as in the manual input password
Save the above script and assign Execute permission, the following procedure is performed:
": No such file or Directory:shell script is edited under Windows, using a newline character in Windows. Remember: Edit the shell script in Linux
Interact: Keep the interaction state after execution, give control to the console for manual operation, and automatically exit if no such command is completed.
Additional notes:
1, expect execution speed is slow, such as automatically enter the password to wait a short period of time.
2. The shell script needs to be executed with the./script name, cannot use the SH script name, because expect is not executed with bash
Using expect in Linux