简体   繁体   English

Linux Expect Expect_out(buffer)不包含任何内容

[英]Linux Expect expect_out(buffer) does contain nothing

I've been trying to capture the result of grep, logging into a remote machine, using ssl in Expect command. 我一直在尝试捕获grep的结果,使用Expect命令中的ssl登录到远程计算机。 I read "except_out(buffer)" variable to contain the output of the spawned process, but it seemed empty... A pointer'd be greatly appreciated! 我读了“ 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)\"

expect version : 5.43.0 预期版本:5.43.0

That code is a real mess. 那个代码真是一团糟。 In particular, you've got interactions between bash and expect/tcl which are causing you trouble because when bash sees $var for a variable it doesn't know, it replaces it with the empty string. 特别是,您在bash与Expect / tcl之间进行了交互,这给您带来麻烦,因为当bash看到$var的变量时,它将替换为空字符串。

While you could update things by changing how you do quoting, it's actually better to rewrite things to actually use a direct expect/tcl script, like this: 虽然可以通过更改报价方式来更新内容,但实际上最好重写代码以实际使用直接的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)"

However, I'd actually configure the remote host to use RSA keys for logins (indeed, I'd configure the remote host to only use them as they're much more attack-resistant than passwords and easier to manage too) and then just do this (with a local grep so it doesn't need to be filtered): 但是,我实际上将远程主机配置为使用RSA密钥进行登录(实际上,我将远程主机配置为使用它们,因为它们比密码更具攻击性并且更易于管理),然后执行此操作(使用本地grep因此不需要对其进行过滤):

ssh $username@$host ps axuw | grep java

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM