下面是我的脚本,该脚本在command.txt中具有命令,并且使用spawn来对防火墙执行ssh,但它无法执行echo命令来输入防火墙名称,所以不明白什么地方出了错。
!/bin/bash
expect <<'END'
# Set variables
set username $env(USER)
set password [lindex $argv 1]
echo 'Please enter FQDN/IP address of the FW'
read -p 'Firewall FQDN/IP: ' hostname
# Announce which device we are working on and at what time
send_user "\n"
send_user ">>>>> Working on $hostname @ [exec date] <<<<<\n"
send_user "\n"
# Don't check keys
spawn ssh -o StrictHostKeyChecking=no $username\@$hostname
# send bulk commands to hostname from a file commands.txt
for commands in `cat $commands.txt`; do
send "$commands";
done
send -- "exit\n"
END
答案 0 :(得分:1)
echo
和read
是Shell命令,但是您在期望的代码中包含了它们。您的for
循环也有同样的问题。
您可以简单地在整个任务中使用Expect,而不是混合shell和Expect代码:我还让用户键入密码,而不是在命令行中提供密码。
#!/usr/bin/expect -f
set username $env(USER)
# read the hostname from the user
send_user "Enter the hostname: "
expect_user -re "(.*)\n"
set hostname $expect_out(1,string)
# read the password from the user, without echoing to the screen
stty -echo
send_user -- "Password for $username@$hostname: "
expect_user -re "(.*)\n"
send_user "\n"
stty echo
set password $expect_out(1,string)
# Announce which device we are working on and at what time
send_user "\n"
send_user ">>>>> Working on $hostname @ [timestamp -format "%a %b %d %Y, %T"] <<<<<\n"
send_user "\n"
# Don't check keys
spawn ssh -o StrictHostKeyChecking=no $username@$hostname
expect {
"assword:" {send -- "$password\r"}
timeout {error "Did not see password prompt in $timeout seconds"}
}
set fh [open commands.txt r]
while {[gets $fh command] != -1} {
# Here, waiting for your prompt.
# If it does not end with dollar and space, change this pattern
expect -re {\$ $}
send "$command\r";
}
close $fh
expect -re {\$ $}
send -- "exit\n"
expect eof