如何在 Bash 脚本中使用 Expect

问题描述 投票:0回答:2

我正在尝试编写一个脚本,从 Git 存储库中提取最新版本的软件并更新配置文件。但从存储库中提取时,我必须输入密码。我希望脚本能够自动化一切,所以我需要它自动为我填充。我发现这个网站解释了如何使用 Expect 查找密码提示并发送密码。但我无法让它工作。

这是我的脚本:

#!/usr/bin/expect -f
set password [lrange $argv 0 0]
set timeout -1

clear
echo "Updating Source..."
cd sourcedest
git pull -f origin master

match_max 100000
# Look for passwod prompt
expect "*?assword:*"
# Send password aka $password
send -- "$password\r"
# send blank line (\r) to make sure we get back to gui
send -- "\r"
expect eof

git checkout -f master
cp Config/database.php.bak Config/database.php
cp webroot/index.php.bak webroot/index.php
cp webroot/js/config.js.bak webroot/js/config.js

我做错了什么?

这是我从中获取的网站:http://bash.cyberciti.biz/security/expect-ssh-login-script/

bash expect
2个回答
22
投票

这基本上取自评论,还有我自己的一些观察。但似乎没有人愿意对此提供真正的答案,所以这里是:

您的问题是您有一个 Expect 脚本,并且您将其视为 Bash 脚本。 Expect 不知道

cd
cp
git
的含义。巴什确实如此。您需要一个调用 Expect 的 Bash 脚本。例如:

#!/usr/bin/env bash

password="$1"
sourcedest="path/to/sourcedest"
cd $sourcedest

echo "Updating Source..."
expect <<- DONE
  set timeout -1

  spawn git pull -f origin master
  match_max 100000

  # Look for password prompt
  expect "*?assword:*"
  # Send password aka $password
  send -- "$password\r"
  # Send blank line (\r) to make sure we get back to the GUI
  send -- "\r"
  expect eof
DONE

git checkout -f master
cp Config/database.php.bak Config/database.php
cp webroot/index.php.bak webroot/index.php
cp webroot/js/config.js.bak webroot/js/config.js

但是,正如 larsks 在评论中指出的那样,您最好使用 SSH 密钥。然后你就可以完全摆脱

expect
调用了。


0
投票

使用 autoexpect 命令生成您的期望脚本工作流程。

创建一个文件:interactive_git_script.sh 将 git 代码保存在其中:

    #! /bin/bash
    
    # interactive git script

    git pull -f origin master
    git checkout -f master

然后使用以下命令生成您的期望脚本:

    # run this in bash commandline
    chmod u+x interactive_git_script.sh

    # run this in bash commandline and answer
    #+    all the interactive prompts you are
    #+    interested in
    autoexpect ./interactive_git_script.sh

生成的文件名为 script.exp 然后创建一个名为 main.sh 的新文件:

    #! /bin/bash

    chmod u+x script.exp
    ./script.exp
    cp Config/database.php.bak Config/database.php
    cp webroot/index.php.bak webroot/index.php
    cp webroot/js/config.js.bak webroot/js/config.js

然后在 bash 命令行上运行您的应用程序:

    # run command 1 on command line
    chmod u+x main.sh
    # run command 2 on command line
    ./main
© www.soinside.com 2019 - 2024. All rights reserved.