期待重定向stdin

时间:2012-04-19 22:41:13

标签: input ssh pipe expect

我正在远程服务器上运行脚本,例如使用此命令:

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

现在我正在尝试使用expect来处理密码提示。这是脚本:

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

spawn -noecho ssh root@host $cmd

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

如果我运行脚本,它没有输出:

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

我知道这不是没有密码使用ssh的方法,但这不是问题所在。


更新我用一个简单的脚本尝试了glenn jackman的想法,但它没有用。这是我正在使用的脚本:

#!/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...

<小时/> 更新我设法让我的脚本运行。这是有效的结果:

#!/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
  }
}

2 个答案:

答案 0 :(得分:5)

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

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

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

答案 1 :(得分:0)

使用expect_user,如手册页所示:

以下脚本读取密码,然后每小时运行一个程序,每次运行时都需要密码。该脚本提供密码,因此您只需键入一次即可。 (请参阅stty命令,该命令演示如何关闭密码回显。)

send_user "password?\ "
expect_user -re "(.*)\n"
for {} 1 {} {
    if {[fork]!=0} {sleep 3600;continue}
    disconnect
    spawn priv_prog
    expect Password:
    send "$expect_out(1,string)\r"
    . . .
    exit
}

这是我目前所拥有的,但仍然在改进它:

#!/usr/local/bin/expect

# For debugging make the following to be line 1:
#!/usr/local/bin/expect -D 1

set timeout 20

send_user "Username?\ "
expect_user -re "(.*)\n"
set user $expect_out(1,string)

send_user "password?\ "
stty -echo
expect_user -re "(.*)\n"
stty echo
set password $expect_out(1,string)

spawn su

expect {

    "Password"  {send "$password\r"}

    "#"         {interact + return}

}
相关问题