期望重定向标准输入 [英] Expect redirect stdin

查看:120
本文介绍了期望重定向标准输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下命令在远程服务器上运行脚本:

I'm running a script on a remote server like using this command:

ssh root@host 'bash -s' < script.sh

现在,我正在尝试使用Expect处理密码提示.这是脚本:

Now I'm trying to use expect to handle the password prompt. This is the script:

#!/usr/bin/expect
set cmd [lindex $argv 0]

spawn -noecho ssh root@host $cmd

expect {
  "password:" {
     send "password\r"
   }
}

如果我运行该脚本,则不会输出任何信息:

If I run the script, it gives no output:

./ssh.exp 'bash -s' < script.sh

我知道,没有密码就无法使用ssh,但这不是这里的问题.

I know that's not the way to use ssh without password, but this is not the question right here.

更新我用一个简单的脚本尝试了glenn jackman的想法,但是它不起作用.这是我正在使用的脚本:

UPDATE I tried the idea of glenn jackman with a simple script but it's not working. This is the script I'm using:

#!/usr/bin/expect
spawn ssh xxx@xxx

expect "*?assword:*"
send "pwd\r"

send "echo hello world"

这是我得到的输出:

[xxx@xxx bin]$ expect -d my.exp
expect version 5.43.0
argv[0] = expect  argv[1] = -d  argv[2] = my.exp
set argc 0
set argv0 "my.exp"
set argv ""
executing commands from command file my.exp
spawn ssh xxx@xxx
parent: waiting for sync byte
parent: telling child to go ahead
parent: now unsynchronized from child
spawn: returns {7599}

expect: does "" (spawn_id exp6) match glob pattern "*?assword:*"? no
xxx@xxx's password:
expect: does "xxx@xxx's password: " (spawn_id exp6) match glob pattern "*?assword:*"? yes
expect: set expect_out(0,string) "xxx@xxx's password: "
expect: set expect_out(spawn_id) "exp6"
expect: set expect_out(buffer) "xxx@xxx's password: "
send: sending "pwd" to { exp6 }
send: sending "echo hello world" to { exp6 }
write() failed to write anything - will sleep(1) and retry...


更新我设法使其运行.这是行得通的结果:


UPDATE I managed it to get my script to run. This is the result which works:

#!/usr/bin/expect

set user [lindex $argv 0]
set host [lindex $argv 1]
set pwd  [lindex $argv 2]

spawn ssh $user@$host bash -s

expect {
  "?asswor?: " {
    send "$pwd\n"
  }
}

while {[gets stdin line] != -1} {
    send "$line\n"
}
send \004

expect {
  "END_TOKEN_OF_SCRIPT" {
    exit 0
  }
  default {
    exit 1
  }
}

推荐答案

您需要将在stdin上读取的脚本发送到远程主机:

You need to send the script you read on stdin to the remote host:

while {[gets stdin line] != -1} {
    send "$line\r"
}

# then you may have to send ctrl-D to signal end of stdin
send \004

这篇关于期望重定向标准输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆