#!/bin/bash
Passwd= ' Abcd1234 '
/usr/bin/expect <<-eof
Set time of execution timeout any input 30S after exiting
Spawn ssh-p22 [email protected]
Expect {
"*yes/no" {send "yes\r"; Exp_continue}
"*password:" {send "$passwd \ r"}
}
Expect "*#" defines the start of the command
Send "echo Test >>/root/d.txt\r" sends the command to execute
Send "echo Test >>/root/e.txt\r"
Expect "*#"
Send "exit\r"
Interact with exact this instruction is to give control to the user , instead of the Send "logout\r" terminal will not be disconnected
Expect EOF
Eof
1. [Spawn ssh-p22 [email protected]]
Spawn is a expect internal command that can be executed after entering the expect environment, if no expect is installed or the Spawn command is not found directly under the default shell. So don't use commands like "which spawn" to find spawn commands. Like dir in Windows is an internal command that comes with the shell and you can't find an executable file for dir.com or Dir.exe.
Its main function is to add a shell to the SSH running process to pass the interactive instructions.
2. [Expect "Password:"]
Here expect is also a expect internal command, a bit dizzy, expect shell command and internal command is the same, but not a function, habit is good. This command means to determine whether the last output contains the string "Password:", if any, return immediately, or wait for a period of time to return, where the waiting length is the previous set of 30 seconds
3. [Send "df\r"]
This is where the interactive action is performed, which is equivalent to the action of entering the password manually.
Tips: The end of the command string do not forget to add "\ r", if the status of abnormal waiting can be checked.
4. [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. If you just log in past to execute
#!/usr/bin/expect #注意安装的路径, not sure Whereis expect a bit.
This article is from the "Silence" blog, make sure to keep this source http://silencezone.blog.51cto.com/3613477/1881182
Linux expect remote automatic login and execute commands