我有一个bash + expect脚本,它必须通过SSH连接到远程组件,在那里读取文件,find具有“主机名”的特定行(如“hostname aaaa1111”),并将此主机名存储到variables中,以便在。 我怎样才能得到“主机名”参数的值? 我认为行内容将在$ expect_out(缓冲区)variables(所以我可以扫描和分析),但事实并非如此。 我的脚本是:
#!/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就像一个双引号string,所以$expect_outvariables在expect开始之前被shell取代。 你需要确保你的heredoc没有被shell所触及。 因此,任何shellvariables都需要以不同的方式获取。 在这里,我假设IP是一个shellvariables,我将它传递给环境。
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
你为什么用这个期望?
ssh -i ssh_private_key root@${IP} "grep -E -o 'hostname.*$' /etc/rc.d/rc.local"