【问题标题】:Linux Expect expect_out(buffer) does contain nothingLinux Expect_out(buffer) 不包含任何内容
【发布时间】:2011-04-23 03:25:01
【问题描述】:

我一直在尝试捕获 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

【问题讨论】:

  • 也许你会对this感兴趣。
  • 不要转义所有这些双引号。您希望连续两次提示,中间只有一次睡眠——这肯定是错误的
  • @glenn:这是因为它都在一个 bash 脚本中,这极大地使事情变得更加复杂。

标签: bash ssh tcl expect sh


【解决方案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 密钥进行登录(实际上,我将远程主机配置为像他们一样使用它们' re 比密码更耐攻击,也更容易管理),然后执行此操作(使用本地 grep,因此不需要过滤):

ssh $username@$host ps axuw | grep java

【讨论】:

  • 您好,多纳尔,谢谢您的评论。它真的帮助了我......我终于按照你说的那样使用 RSA 密钥重写了这段代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-14
相关资源
最近更新 更多