如何在 Bash 脚本中使用 expect
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10393848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use expect in Bash script
提问by LordZardeck
I am trying to write a script that pulls the latest version of my software from a git repo and updates the config files. When pulling from the repo though, i have to enter a password. I want the script to automate everything, so I need it to automatically fill it in for me. I found this site that explained how to use "expect" to look for the password prompt and send the password. I can't get it to work though. Here's my script:
我正在尝试编写一个脚本,该脚本从 git 存储库中提取最新版本的软件并更新配置文件。但是,当从 repo 中提取时,我必须输入密码。我希望脚本自动完成所有操作,因此我需要它自动为我填写。我发现这个网站解释了如何使用“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
What am I doing wrong? here's the site I got it from: http://bash.cyberciti.biz/security/expect-ssh-login-script/
我究竟做错了什么?这是我从这里得到的网站:http: //bash.cyberciti.biz/security/expect-ssh-login-script/
回答by Tim Pote
This is pretty much taken from the comments, with a few observations of my own. But nobody seems to want to provide a real answer to this, so here goes:
这几乎是从评论中摘取的,加上我自己的一些观察。但似乎没有人想对此提供真正的答案,所以这里是:
Your problem is you have an expectscript and you're treating it like a bashscript. Expect doesn't know what cd
, cp
, and git
mean. Bash does. What you want is a bash script that makes a call to expect. For example:
你的问题是你有一个期望脚本,你把它当作一个bash脚本。期待不知道是什么cd
,cp
和git
平均值。巴什。你想要的是一个 bash 脚本,它可以调用期望。例如:
#!/usr/bin/env bash
password=""
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 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
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
However, as larsks pointed out in the comments, you might be better off using ssh keys. Then you could get rid of the expect
call altogether.
但是,正如 larsks 在评论中指出的那样,您最好使用 ssh 密钥。然后你可以expect
完全摆脱这个电话。