-1

我有一个 bash+expect 脚本,它必须通过 ssh 连接到远程 comp(我不能使用 ssh 密钥,这里需要密码识别),在那里读取文件,找到带有“主机名”的特定行(比如“主机名 aaaa1111") 并将此主机名存储到变量中,以便稍后使用。如何获取“主机名”参数的值?我认为行内容将在 $expect_out(buffer) 变量中(因此我可以对其进行扫描和分析),但事实并非如此。我的脚本是:

    #!/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)

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

4

1 回答 1

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
于 2011-08-16T07:32:44.490 回答