在上一个命令等待输入时将字符串发送到 bash 脚本中的输入

Send string to input in a bash script while the previous command is awaiting input

是的,这是一个糟糕的标题,我知道。我不知道如何用语言表达。

所以我 运行 linux 并且正在设置一个 openVPN;这很麻烦,所以我决定制作一个 BASH 脚本来为我做这件事。这是我的。

#!/bin/bash
PROMPT_COMMAND=
echo -en "3]0;VPNBook\a"
cd ~/Other/VPN\'s/VPNBook
if ! pgrep openvpn > /dev/null
    then
    echo "VPN is not running"
    read -r -p "Would you like to start the VPN? [Y/n]" response
    response=${response,,}
    if [[ $response =~ ^(no|n)$ ]]
        then
        exit
    else
        echo "Starting VPN"
        # echo "Username: vpnbook"
        # echo "Password: 2Unuhust"
        # sudo echo

        # Line in question
        sudo openvpn --config vpnbook-euro1-tcp443.ovpn
    fi
else
    echo "VPN is running"
    read -r -p "Would you like to stop the VPN? [Y/n]" response
    response=${response,,}
    if [[ $response =~ ^(no|n)$ ]]
        then
        exit
    else
        echo "Stopping VPN"
        sudo kill $(pidof openvpn)
    fi
fi

示例输出:

Wed Mar  2 23:06:52 2016 OpenVPN 2.3.2 x86_64-pc-linux-gnu [SSL (OpenSSL)] [LZO] [EPOLL] [PKCS11] [eurephia] [MH] [IPv6] built on Dec  1 2014
Enter Auth Username:vpnbook
Enter Auth Password:

因此,我希望脚本能够自动输入用户名和密码,而不是手动输入用户名和密码。 所以基本上一旦我输入了 sudo 的密码,脚本就会完成剩下的工作。

我进行了一些谷歌搜索,据我所知,大多数事情都不起作用,要么是因为命令没有接收信息作为参数,要么是因为输入没有通过 STDIN,因为它是密码。

提前谢谢你,很抱歉,我知道这不是一个好问题。

好的,所以我使用 expect 解决了它。这是我的最终代码:

#!/bin/bash
PROMPT_COMMAND=
echo -en "3]0;VPNBook\a"
cd ~/Other/VPN\'s/VPNBook
if ! pgrep openvpn > /dev/null
    then
    echo "VPN is not running"
    read -r -p "Would you like to start the VPN? [Y/n]" response
    response=${response,,}
     if [[ $response =~ ^(no|n)$ ]]
         then
         echo "Doing nothing"
    sleep 1
    exit
else
    echo "Starting VPN" 
    sudo ./startVPN.exp
fi
else
    echo "VPN is running"
    read -r -p "Would you like to stop the VPN? [y/N]" response
    response=${response,,}
    if [[ $response =~ ^(yes|y)$ ]]
        then
        echo "Stopping VPN"
        sudo kill $(pidof openvpn)
        echo "VPN Stopped"
            sleep 1
            exit
        else
            echo "Doing nothing"
            sleep 1
            exit
    fi
fi

和startVPN.exp:

#!/usr/bin/expect

set PASS "2Unuhust"
set USER "vpnbook"
spawn openvpn --config vpnbook-euro1-tcp443.ovpn
expect "Enter Auth Username:"
send "$USER\r"
expect "Enter Auth Password:"
send "$PASS\r"