I'm including simple Expect commands within a bash script (I know I could be just writing a pure Expect script but I would like to get it to work from within bash).
The script is below:
#!/bin/bash
OUTPUT=$(expect -c '
spawn ssh mihail911@blah.org
expect "password:"
send "dog\r"
')
Upon ssh'ing to the above address, it will return something of the form mihail911's password:
on the prompt so I think my expect line is valid. When I run this my script does not print anything. It does not even show the password:
prompt. In general, even if I manually provide an incorrect password, I will receive a Incorrect password
-type response prompt. Why is nothing printing and how can I get my script to execute properly? I have tried debugging by using the -d
flag and it seems to show that at least the first expect prompt is being matched properly.
In addition, what values should I expect in the OUTPUT
variable? When I echo
this variable, it simply prints the first the first command of the expect portion of the script and then mihail911's password:
. Is this what it's supposed to be printing?
答案 0 :(得分:5)
#!/bin/bash
OUTPUT=$(expect -c '
# To suppress any other form of output generated by spawned process
log_user 0
spawn ssh dinesh@xxx.xxx.xx.xxx
# To match some common prompts. Update it as per your needs.
# To match literal dollar, it is escaped with backslash
set prompt "#|>|\\$"
expect {
eof {puts "Connection rejected by the host"; exit 0}
timeout {puts "Unable to access the host"; exit 0;}
"password:"
}
send "root\r"
expect {
timeout {puts "Unable to access the host"; exit 0;}
-re $prompt
}
send "date\r"
# Matching only the date cmd output alone
expect {
timeout { puts "Unable to access the host";exit 0}
-re "\n(\[^\r]*)\r"
}
send_user "$expect_out(1,string)\n"
exit 1
')
echo "Expect's return value : $?"; # Printing value returned from 'Expect'
echo "Expect Output : $OUTPUT"
输出
dinesh@MyPC:~/stackoverflow$ ./Meric
Expect's return value : 1
Expect Output : Wed Sep 2 09:35:14 IST 2015
dinesh@MyPC:~/stackoverflow$