expect - programmed dialogue with interactive programs
yum install expect
# apt-get install expect
| Commands | Note |
|---|---|
| set timeout set timeout 30 | The default timeout period is 10 seconds |
| spawn | creates a new process running program args. |
| send send “COMMAND\n” | Sends string to the current process. |
| expect expect “STRING” | waits until one of the patterns matches the output of a spawned process |
| interact | gives control of the current process to the user, so that keystrokes are sent to the current process, and the stdout and stderr of the current process are returned. |
| log_file log_file FILE | If a filename is provided, log_file will record a transcript of the session in the file. |
| sleep sleep 2 | causes the script to sleep for the given number of seconds. |
If you are execute expect by cron, php, you dont't use interact
Because there isn't standard in. the script is not work.
Please use expect eof and exit.
expect -c " spawn scp file01 user01@xx.xx.xx.xx:/tmp expect eof exit "
Reference
$ -> \$
" -> \"
#!/bin/sh
HOST=192.168.100.230
UNAME=testuser
PASSWD=testuser
TARGET=test.txt
expect -c "
set timeout 20
spawn scp ${TARGET} ${UNAME}@${HOST}:/home/testuser/
expect \"password:\"
send \"$PASSWD\r\"
interact
"
exit 0
#!/bin/bash
hostname=192.168.10.12
username=user01
password=testpass
expect -c "
spawn ssh -l $username $hostname
expect \"password:\" {
send \"$password\n\"
} \"Are you sure you want to continue connecting (yes/no)?\" {
send \"yes\n\"
expect \"password:\"
send \"$password\n\"
}
expect \"$\"
send \"ls\n\"
interact
"
#!/bin/sh
HOST=xxx.xxx.xxx.xxx
PASS=xxxxxxxxxxx
IDENT=/home/user/.ssh/id_rsa
expect -c "
set timeout 10
spawn scp -i $IDENT /tmp/file.txt user@$HOST:/tmp/
expect \"Enter passphrase for key\"
send \"${PASS}\r\"
expect {\"100%\" { exit 0 }} # If 100%, exit
"
#!/usr/local/bin/expect set timeout 5 spawn telnet 10.1.1.1 #Login expect "Password: " send -- "aaa\n" expect ">" send -- "enable\n" expect "Password: " send -- "bbb\n" expect "#" send -- "terminal length 0\n" expect "#" send "show run\n" expect "#" send -- "exit\n" expect eof exit
#!/usr/bin/expect
#./login_pro.sh 192.168.0.100
log_file /var/log/expect.log
set RemoteHost [lindex $argv 0]
set PW [lindex $argv 1]
set Prompt "\[#$%>\]"
set timeout 5
spawn env LANG=C /usr/bin/ssh ${RemoteHost}
expect {
"(yes/no)?" {
send "yes\n"
exp_continue
}
-re "password:" {
send -- "${PW}\n"
}
}
expect {
-glob "${Prompt}" {
interact
exit 0
}
}