在远程计算机上运行cat并使用expect发送输出变量

时间:2011-08-12 17:04:08

标签: bash expect cat

我有一个bash + expect脚本,必须通过ssh连接到远程comp(我不能使用ssh密钥,这里需要密码识别),在那里读取文件,找到带有“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 \r"
    expect ":~#"
    set line $expect_out(buffer)
    puts "line = $line, expect_out(buffer) = $expect_out(buffer)"
    ...more script...
    ENDOFEXPECT

当我尝试查看行变量时,我只看到这一点:line = , expect_out(buffer) = (buffer)从文件中获取行到变量的正确方法是什么? 或者是否可以打开远程计算机上的文件 ,扫描文件并获得我需要的变量? 这里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, 
    set results $expect_out(buffer)

似乎在这种情况下不起作用?

1 个答案:

答案 0 :(得分:1)

您可能只想尝试从期望中完成所有操作,因为期望可以控制bash。

以下内容应该按照您的描述进行。不确定这是否正是你想要做的。

#!/bin/sh
# the next line restarts using tclsh \
exec expect "$0" "$@"


spawn bash 
send "ssh root@$IP\r"
expect "password:"
send "xxxx\r"
expect ":~#"
send "cat /etc/rc.d/rc.local |grep hostname \n"
expect ":~#"
set extractedOutput $expect_out(buffer)
set list [split $extractedOutput "\n"]
foreach line $list {
    set re {(?x)
        .*
        (*)              
        -S.*
    }
    regexp $re $line total extractedValue
    if {[info exists extractedValue] && [string length $extractedValue] > 1} {
        set exportValue $extractedValue
        break    # We've got a match!
}

send "exit\r" # disconnect from the ssh session

if {[info exists exportValue] && [string length $exportValue] > 1}{
    send "export VARIABLE $exportValue\r"
} else {
    send_user "No exportValue was found - exiting\n"
    send "exit\r"
    close
    exit 1
}

# now you can do more things in bash if you like