Bash脚本响应控制台输出?

时间:2018-03-17 08:06:10

标签: linux bash centos

目前尝试在启动时运行bash脚本以自动安装squid,但是我正在运行的命令需要输入。

目前我的脚本是:

#!/bin/sh
PROXY_USER=user1
PROXY_PASS=password1
wget https://raw.githubusercontent.com/hidden-refuge/spi/master/spi && bash spi -rhel7 && rm spi
#After i run this command it asks "Enter username" 
#followed by "Enter password" and "Renter password"
echo $PROXY_USER
echo $PROXY_PASS
echo $PROXY_PASS
echo yes

但是我无法使输入正常工作,并且脚本无法创建用户名和密码。我正在运行centos 7。

2 个答案:

答案 0 :(得分:1)

看看您正在调用一些以交互模式运行的工具,因此在dani-gehtdichnixan处提及passing arguments to an interactive program non interactively时,您可以使用expect实用程序。

在debian安装expect

apt-get install expect

创建一个脚本调用spi-install.exp,如下所示:

#!/usr/bin/env expect
set user username
set pass your-pass

spawn spi -rhel7 
expect "Enter username"
send "$user\r"

expect "Renter password"
send "$pass\r"

然后在主bash脚本中调用它:

#!/bin/bash 
wget https://raw.githubusercontent.com/hidden-refuge/spi/master/spi  && ./spi-install.exp  && rm spi
  

Expect用于自动控制交互式应用程序,如Telnet,FTP,passwd,fsck,rlogin,tip,SSH等。 Expect使用伪终端(Unix)或模拟控制台(Windows),启动目标程序,然后通过终端或控制台界面与人类进行通信。 Tk是另一个Tcl扩展,可用于提供GUI。

https://en.wikipedia.org/wiki/Expect

参考:

[1] passing arguments to an interactive program non interactively

[2] https://askubuntu.com/questions/307067/how-to-execute-sudo-commands-with-expect-send-commands-in-bash-script

[3] https://superuser.com/questions/488713/what-is-the-meaning-of-spawn-linux-shell-commands-centos6

答案 1 :(得分:0)

尝试将值传递给bash&#s; stdin

#!/bin/sh
PROXY_USER=user1
PROXY_PASS=password1
if wget https://raw.githubusercontent.com/hidden-refuge/spi/master/spi; then
    printf "%s\n" "$PROXY_USER" "$PROXY_PASS" "$PROXY_PASS" yes | bash spi -rhel7
    rm spi
fi