无需额外软件包即可自动响应命令提示

无需额外软件包即可自动响应命令提示

我需要运行一个命令并回答命令提出的几个提示。不幸的是,我无法手动输入提示,所以我正在寻找一种自动执行此操作的方法。

我无法安装像expect或这样的外部包yes,也无法将我的命令移动到 .sh 文件中。

我成功地传递了这样的一个答案:

echo 'response' | command

但我不知道如何为同一个命令发送多个提示。

这可能吗?

编辑:

命令是:

certbot certonly --apache

答案1

使用循环可能会有帮助。

while true; do echo yes; done | command

使用数组:

declare -a arr=("yes" "no" "no"); for i in "${arr[@]}"; do echo $i; done | command

或者按照@steeldriver 建议的:

printf '%s\n' yes yes no | command

假设命令是一个要求输入的脚本:

for i in {1..3}
do
    read -p 'Yes or no' c
    echo $c
done

输出将是:yes第一种情况下为3,第二种情况下为yesyes, 。no

答案2

此外,您可以尝试使用<< EOF逐行EOF构造一些答案:

$ sudo adduser test2 << EOF
> password
> password
> test2name
> 1
> 2
> 3
> 4
> y
> EOF
[sudo] password for user: 
Adding user `test2' ...
Adding new group `test2' (1004) ...
Adding new user `test2' (1003) with group `test2' ...
Creating home directory `/home/test2' ...
Copying files from `/etc/skel' ...
New password: Retype new password: passwd: password updated successfully
Changing the user information for test2
Enter the new value, or press ENTER for the default
        Full Name []:   Room Number []:         Work Phone []:  Home Phone []:  Other []: Is the information correct? [Y/n] 

user@ubuntu:~$ finger test2
Login: test2                            Name: test2name
Directory: /home/test2                  Shell: /bin/bash
Office: 1, 2                            Home Phone: 3
Never logged in.
No mail.
No Plan.

您还可以创建一个answers文件:

$ cat answers 
password
password
test
1
1
1
1
y

然后只需使用cat命令传输文件内容:

$ cat answers | sudo adduser test
Adding user `test' ...
Adding new group `test' (1002) ...
Adding new user `test' (1001) with group `test' ...
Creating home directory `/home/test' ...
Copying files from `/etc/skel' ...
New password: Retype new password: passwd: password updated successfully
Changing the user information for test
Enter the new value, or press ENTER for the default
        Full Name []:   Room Number []:         Work Phone []:  Home Phone []:  Other []: Use of uninitialized value $answer in chop at /usr/sbin/adduser line 621.
Use of uninitialized value $answer in pattern match (m//) at /usr/sbin/adduser line 622.
Is the information correct? [Y/n] 

user@ubuntu:~$ finger test
Login: test                             Name: test
Directory: /home/test                   Shell: /bin/bash
Office: 1, 1                            Home Phone: 1
Never logged in.
No mail.
No Plan.

相关内容