【问题标题】:Expect In Bash Script期望在 Bash 脚本中
【发布时间】:2016-02-28 06:16:25
【问题描述】:

我正在尝试编写一个自动构建脚本。在构建命令结束时会提示用户输入密码,我想自动发送密码。我现在拥有的是

#!/bin/bash

##stored username and password
userName = [username]
password = [password]

##connect to build server
ssh ${username]@xx.x.xx.xx

##checkout copy from svn
svn co [path of code]

##change directory to build directory
cd [build directory of checked out code]

##start build 
##expect password
/usr/bin/expect << EOF
    expect "Password: "
    spawn make build
    send ${password}
EOF

exit
echo "Build Complete"

另一种在 bash 脚本中执行期望的方法

expect -c \
    "set timeout -1; \
    spawn make build; \
    expect \"password: \"; \
    send -- \[password]\r\"; \
    expect eof"

在第二个例子中,[密码]实际上是一个所需密码的字符串。

当构建命令提示输入密码时,它会一直亮着。我尝试了其他一些示例,但 spawn 似乎根本不起作用,例如

#!/usr/bin/expect
expect "hello"
spawn echo "hello"
send "world"

在我输入“hello”之前什么都不做

任何帮助将不胜感激!

【问题讨论】:

  • 不相关,但您是否期望 svn 以及随后在构建服务器上执行 的内容?它不会;在您退出由ssh 命令启动的shell 之前,这些命令不会执行。
  • 究竟是哪个命令提示输入密码?您的两个脚本分别显示了在 make build 命令之前和之后出现的预期提示。

标签: bash ubuntu scripting automation expect


【解决方案1】:

正如@chepner 评论的那样,您的逻辑是错误的:您在本地机器上完成大部分工作,而不是远程完成。您需要这样的东西来连接到远程服务器并与那里的登录 shell 交互:

#!/usr/bin/expect -f

##stored username and password
set userName "username"
set password "password"
set prompt "pattern to match user's prompt"

##connect to build server
spawn ssh $username@xx.x.xx.xx
expect -re $prompt

##checkout copy from svn
send "svn co [path of code]\r"
expect -re $prompt

##change directory to build directory
send "cd [build directory of checked out code]\r"
expect -re $prompt

##start build 
set timeout -1           ; # wait as long as required for build to finish
send "make build\r"
expect "Password: "
send -- "$password\r"

# get a prompt when build complete
expect -re $prompt
send "exit\r"
expect eof

puts "Build Complete"

【讨论】:

  • 非常感谢!明天早上我会试一试:)
猜你喜欢
  • 1970-01-01
  • 2014-09-20
  • 2014-08-11
  • 2020-04-08
  • 1970-01-01
  • 1970-01-01
  • 2020-07-01
  • 2016-09-06
  • 1970-01-01
相关资源
最近更新 更多