Linux Expect expect_out(缓冲区)确实不包含任何内容

时间:2011-04-22 07:34:38

标签: bash ssh tcl expect sh

我一直在尝试捕获grep的结果,使用Expect命令中的ssl登录到远程计算机。 我读了“except_out(buffer)”变量来包含生成进程的输出,但它似乎是空的...... 非常感谢指针!

#!/bin/bash

username=hoge
password=hoge
hostname=machine20

prompt="\[$username@$hostname ~\]$"

expect -c "
set timeout -1
spawn ssh -l $username $hostname
expect {
   \"$username@$hostname's password:\" {
  send \"$password\n\"
  } \"Are you sure you want to continue connecting (yes/no)?\" {
  send \"yes\n\"
  expect \"$username@$hostname's password:\"
  send \"$password\n\"
  }
}

expect \"$prompt\"
sleep 2

expect \"$prompt\"
send \"ps axuw | grep java | grep -vc grep\n\"

expect -re -indices \"(.*)\"
send \"echo result : $expect_out(buffer)\"

期待版本:5.43.0

1 个答案:

答案 0 :(得分:1)

那段代码真的很乱。特别是,你有bash和expect / tcl之间的交互,这会导致你遇到麻烦,因为当bash看到$var一个它不知道的变量时,它会用空字符串替换它。

虽然您可以通过更改引用方式来更新内容,但实际上最好重写实际使用直接expect / tcl脚本的内容,如下所示:

#!/usr/bin/env expect

set username "hoge"
set password "hoge"
set hostname "machine20"

set prompt "\[$username@$hostname ~\]$"

set timeout -1
spawn ssh -l $username $hostname
expect {
    "$username@$hostname's password:" {
        send "$password\r"
    }
    "Are you sure you want to continue connecting (yes/no)?" {
        send "yes\r"
        exp_continue
    }
}

# These next two lines look suspicious, BTW...
expect "$prompt"
sleep 2

expect "$prompt"
send "ps axuw | grep java | grep -vc grep\r"

expect -re -indices "(.*)"
send "echo result : $expect_out(buffer)"

但是,我实际配置远程主机使用RSA密钥进行登录(实际上,我将远程主机配置为使用它们'比密码更耐攻击,也更容易管理)然后只需执行此操作(使用本地grep,因此不需要过滤):

ssh $username@$host ps axuw | grep java