Bash

Bash 腳本 - 如何將輸出定向到 OpenVPN 中的多個輸入?

  • April 1, 2020

所以我正在嘗試編寫一個腳本來簡化連接到 OpenVPN 伺服器的過程。

所以當我寫:

openvpn --config vpnbook-pl226-udp53.ovpn

它提示我輸入使用者名和密碼:

Wed Apr  1 21:23:28 2020 OpenVPN 2.4.7 x86_64-pc-linux-gnu [SSL (OpenSSL)] [LZO] [LZ4] 
[EPOLL] [PKCS11] [MH/PKTINFO] [AEAD] built on Feb 20 2019
Wed Apr  1 21:23:28 2020 library versions: OpenSSL 1.1.1d  10 Sep 2019, LZO 2.10
Enter Auth Username:            
Enter Auth Password: 

在這裡,我希望我的腳本自動將使用者名和密碼發送到 OpenVPN。

我進行了以下嘗試:

嘗試1:

{ echo "vpnbook"; echo "3vze4vd"; } | openvpn --config vpnbook-pl226-udp53.ovpn

嘗試2:

echo -e "vpnbook\n3vze4vd" | openvpn --config vpnbook-pl226-udp53.ovpn

嘗試 3:

(echo $username; echo $password;) | openvpn --config vpnbook-pl226-udp53.ovpn

但他們都沒有工作,我得到以下輸出:

Wed Apr  1 21:38:14 2020 OpenVPN 2.4.7 x86_64-pc-linux-gnu [SSL (OpenSSL)] [LZO] [LZ4] [EPOLL] [PKCS11] [MH/PKTINFO] [AEAD] built on Feb 20 2019
Wed Apr  1 21:38:14 2020 library versions: OpenSSL 1.1.1d  10 Sep 2019, LZO 2.10

然後什麼也沒有發生。

有人可以給我一個提示嗎?

您可以將使用者名和密碼添加到安全文件(只有所有者可以讀取)。auth-user-pass在您的 OpenVPN 文件中查找通行證以了解詳細資訊 ( man openvpn):

cat > /path/to/secret <<'X'
myusername
verysecret
X
chmod u=rw,go= /path/to/secret

現在auth-user-pass在您的 OpenVPN 配置文件中找到該指令並像這樣擴展它

auth-user-pass /path/to/secret

這看起來像是expect的工作。

出於展示的目的,我編寫了一個簡短的腳本來模擬您的 openvpn 命令的行為:

#! /usr/bin/env bash
echo "Wed Apr  1 21:23:28 2020 OpenVPN 2.4.7 x86_64-pc-linux-gnu [SSL (OpenSSL)] [LZO] [LZ4]"
echo "[EPOLL] [PKCS11] [MH/PKTINFO] [AEAD] built on Feb 20 2019"
echo "Wed Apr  1 21:23:28 2020 library versions: OpenSSL 1.1.1d  10 Sep 2019, LZO 2.10"
read -r -p 'Enter Auth Username: ' USERNAME
read -rs -p 'Enter Auth Password: ' PASSWORD

echo
echo "username was $USERNAME"
echo "password was $PASSWORD"

這是響應這些提示的簡短期望腳本:

#! /usr/bin/env expect

spawn ./fakevpn --config vpnbook-pl226-udp53.ovpn

expect "Enter Auth Username: " { send Hello\r } # \r is the "return" character.
expect "Enter Auth Password: " { send World\r } # It simulates hitting the Enter key.
expect eof # This ensures expect won't exit until there's no more output.

這是輸出的樣子:

[gnubeard@mothership: ~/vpn]$ ./vpn_expect
spawn ./fakevpn --config vpnbook-pl226-udp53.ovpn
Wed Apr  1 21:23:28 2020 OpenVPN 2.4.7 x86_64-pc-linux-gnu [SSL (OpenSSL)] [LZO] [LZ4]
[EPOLL] [PKCS11] [MH/PKTINFO] [AEAD] built on Feb 20 2019
Wed Apr  1 21:23:28 2020 library versions: OpenSSL 1.1.1d  10 Sep 2019, LZO 2.10
Enter Auth Username: Hello
Enter Auth Password:
username was Hello
password was World

編輯:出於安全原因,roiama 的解決方案優於此解決方案。我會留下這個,以防它對試圖弄清楚如何自動化互動式命令的人有所幫助。

引用自:https://unix.stackexchange.com/questions/577334