如何在Bash脚本中使用Expect

9
我正在尝试编写一个脚本,从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/


我不需要那部分。我正在本地机器上运行这个程序。 - LordZardeck
等等,你的意思是每一行都要用 send 吗??? - LordZardeck
不需要。但是你需要在git和cp命令行中使用spawn。我会将git-dir添加到git命令中,而不是使用cd命令。 - bdecaf
看起来不错。就像我写的那样,也许你需要设置 --git-dir。 - bdecaf
2
为什么每次从远程仓库拉取代码时都需要输入密码?这是基于ssh还是http的远程仓库?你确定不可以使用ssh密钥吗?在.netrc文件中存储用户名和密码怎么样?可能有多种方法可以避免使用整个“expect”脚本。 - larsks
显示剩余4条评论
1个回答

22

这基本上是从评论中获取的,加上了我的一些观察。但似乎没有人愿意真正回答这个问题,所以我来试试:

你的问题在于你有一个 Expect 脚本,并且你把它当作 Bash 脚本来使用。Expect 不知道什么是 cdcpgit,Bash 知道。你需要一个调用 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调用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接