3

我尝试在 bash 中设置一个期望脚本。

#!/bin/bash


/usr/bin/expect <<- EOD

set router 192.168.0.251
set user admin
set pass test  
set timeout 1000  
set filesave [exec date +%m-%d-%Y]  


spawn telnet $router
send "\n"  
expect "Username:"
send "$user\n"
expect "Password:"  
send "$pass\n"  
expect ">"  
send "en\n"  
expect "Password:"  
send "$pass\n"  

send "term len 0\n"  
log_file $router--$filesave.cfg
send "show running-config\n"  
expect "end\r"  
send "\n"  
log_file
send "exit\n"  
EOD

cat /Users/test/Desktop/python/$router--$filesave.cfg | grep end
exit 0

我刚得到这个输出

./script2 
spawn telnet

telnet> telnet> 
4

2 回答 2

1

问题是 bash 正在解释所有$variables之前期望看到的脚本。因此,您只是telnet在没有给出主机名的情况下生成。改变:

/usr/bin/expect <<- EOD

至:

/usr/bin/expect <<- 'EOD'

这具有单引用整个此处文档的效果。
http://www.gnu.org/software/bash/manual/bashref.html#Here-Documents

另请注意,下一个 bash 命令 ( cat /Users/...) 依赖于 Expect 中定义的变量——它们没有在 bash 中定义。尝试这个

#!/bin/bash

export router=192.168.0.251
export filesave=$(date +%m-%d-%Y)

/usr/bin/expect <<- 'EOD'

set router $env(router)
set filesave $env(filesave)
# the rest stays the same
于 2012-11-01T23:57:03.803 回答
1

尝试改变你的shebang:

#!/bin/bash

#!/bin/expect

并删除:

/usr/bin/expect <<- EOD

看看这是否有效。

更新:如果您需要将期望作为 bash 脚本的一部分运行,请使用期望 shebang 将期望代码封装在单独的脚本中并从您的 bash 脚本中获取它,或者按照以下示例对其进行编码:

expect_sh=$(expect -c "
spawn ssh $login@$IP
expect \"password:\"
send \"$password\r\"
expect \"#\"
send \"cd $dest_dir\r\"
expect \"#\"
send \"chmod +x $server_side_script $other_script\r\"
expect \"#\"
send \"./$device_side_script\r\"
expect \"#\"
send \"cat $deploy_count\r\" 
expect \"#\"
send \"exit\r\"
")

echo "$expect_sh"
于 2012-11-01T21:25:04.677 回答