我有一个bash expect脚本,它必须通过ssh连接到远程comp,在那里读取文件,找到带有“hostname”的特定行(如“hostname aaaa1111”)并将此主机名存储到while之后要使用的变量中.如何获取“hostname”参数的值?我认为行内容将在$expect_out(缓冲区)变量中(因此我可以扫描并分析),但事实并非如此.我的脚本是:
#!/bin/bash ----bash part---- /usr/bin/expect << ENDOFEXPECT spawn bash -c "ssh root@$IP" expect "password:" send "xxxx\r" expect ":~#" send "cat /etc/rc.d/rc.local |grep hostname \n" expect ":~#" set line $expect_out(buffer) puts "line = $line,expect_out(buffer) = $expect_out(buffer)" ...more script... ENDOFEXPECT
这里http://en.wikipedia.org/wiki/Expect有一个例子:
# Send the prebuilt command,and then wait for another shell prompt. send "$my_command\r" expect "%" # Capture the results of the command into a variable. This can be displayed,or written to disk. set results $expect_out(buffer)
似乎它在这种情况下不起作用,或者脚本有什么问题?
首先,你的heredoc就像一个双引号字符串,因此$expect_out变量在expect开始之前被shell替换.你需要确保你的heredoc没被shell接触.因此,需要以不同的方式获取任何shell变量.在这里,我假设IP是一个shell变量,我将它传递给环境.
export IP /usr/bin/expect << 'ENDOFEXPECT' set prompt ":~#" spawn ssh root@$env(IP) expect "password:" send "xxxx\r" expect $prompt send "grep hostname /etc/rc.d/rc.local \n" expect $prompt set line $expect_out(buffer) ...more script... ENDOFEXPECT