简体   繁体   中英

Redirect expect stdin to spawn call

Is there a way to redirect stdin sent to expect such that it is fed to a spawn call within expect? In my example below I am embedding expect within a shell function to which I want to pipe another shell script via heredoc and supressing the output by capturing it to a shell variable.

    psshstdin() {
      local user=$1 pass=$2 hosts=$3
      out=$(expect -c '
      set timeout 15
      spawn pssh -i -h '"$hosts"' -p 100 -l '"$user"' -A -o ./ -x-oStrictHostKeyChecking=no <EXPECT_STDIN_HERE
      expect "assword:" { send '\""$pass\r\""' }
      interact
    '<<EOF
    echo "hello"
    echo "world"
    EOF
    )
    }

SOLUTION: I had to post this here since I don't have enough reputation points to answer my own question so quickly.

I was able to resolve it by trying the same techniques applied in this issue . I didn't think that solution was applicable initially, but it was. The working code is shown below.

psshstdin() {
  local user=$1 pass=$2 hosts=$3
out=$(expect -c '
set timeout 30
spawn pssh -I -h '"$hosts"' -p 100 -l '"$user"' -A -o ./ -x-oStrictHostKeyChecking=no
while {[gets stdin line] != -1} {
  send "$line\n"
}
send \004
expect "assword:" { send '\""$pass\r\""' }
expect {
  "END_TOKEN_OF_SCRIPT" {
    exit 0
  }
  default {
    exit 1
  }
}'<&0)
}

I can call it with something like:

psshstdin myusername mypassword ssh_hosts_file<<EOF
echo "hello"
echo "world"
EOF

You can capture stdin to a variable with stdin=$(cat -)

Update: let expect collect the stdin:

untested, but perhaps:

psshstdin() {
  local user=$1 pass=$2 hosts=$3
  out=$(expect -c '
    set stdin [read stdin]
    puts "debug: sending the following stdin to pssh:\n$stdin\n--END--"
    set timeout 15
    spawn echo "$stdin" | pssh -i -h '"$hosts"' -p 100 -l '"$user"' -A -o ./ -x-oStrictHostKeyChecking=no
    expect "assword:" { send "'"$pass"'\r" }
    interact
  '<<EOF
echo "hello"
echo "world"
EOF
)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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