起動時にvpnclientをvpnserverに自動接続させる

Amazon Linux

約 8 分で読めます。



以前これらの記事でSoftetherを使った仮想LANの構築手順を書きました。



今まではvpnclientを起動したはいいものの、vpnserverへの接続はSSHログインして実行していて面倒だったので、それを自動化したという話です。

やったこと

このシェルスクリプトを作り、/opt/vpnclient/vpnclient.shとして置きます。
/bin/shだとうまくいかなかったので、bashにしています。

#!/bin/bash

status(){
        echo "==========status======="
}

start() {
        echo "==========start==========="
        /opt/vpnclient/vpnclient start
        echo -e $'\n' | /opt/vpnclient/vpncmd /CLIENT /CMD AccountConnect virtual_connection
        ip address add 192.168.100.150/24 dev vpn_virtual_nic
}

stop() {
        echo "===========stop============"
        echo -e $'\n' | /opt/vpnclient/vpncmd /CLIENT /CMD AccountDisconnect virtual_connection
        /opt/vpnclient/vpnclient stop
}

restart() {
        stop;
        echo "sleeping.........";
        sleep 3;
        start;
}
case "$1" in
        'start')
                start
                ;;
        'stop')
                stop
                ;;
        'status')
                status
                ;;
        'restart')
                restart
                ;;
        *)
                echo "usage: $0 {start|stop|restart|status}"
                exit 1
                ;;
esac



vpncmdは通常インタラクティブに指示を渡す必要がありますが、コマンドラインオプションで指定することで、ユーザー入力無しでコマンドを実行することができるようになります。

公式サイトはこちらになります。
ご興味がお有りの方はぜひ一度見てみると良いと思います。
 ↓の6.2.3あたり。

6.2 vpncmd の一般的な使用方法 - SoftEther VPN プロジェクト



また、vpncmdを起動するとき、以下のように「どのvpnclientに接続するのか」聞かれますが、自分の場合はlocalhostなので、そのままEnterを入力します。
今回それを自動入力するためにecho -e $’\n’を標準入力で渡し、ユーザー入力不要にしています。

sudo /opt/vpnclient/vpncmd
vpncmd command - SoftEther VPN Command Line Management Utility
SoftEther VPN Command Line Management Utility (vpncmd command)
Version 4.39 Build 9772   (English)
Compiled 2022/04/26 18:00:50 by buildsan at crosswin
Copyright (c) SoftEther VPN Project. All Rights Reserved.

By using vpncmd program, the following can be achieved. 

1. Management of VPN Server or VPN Bridge 
2. Management of VPN Client
3. Use of VPN Tools (certificate creation and Network Traffic Speed Test Tool)

Select 1, 2 or 3: 2

Specify the host name or IP address of the computer that the destination VPN Client is operating on. 
If nothing is input and Enter is pressed, connection will be made to localhost (this computer).
Hostname of IP Address of Destination: 



で、このスクリプトを起動するように/etc/systemd/system/vpnclient.serviceで指定。

[Unit]
Description=SoftEther VPN Client
After=network.target

[Service]
ExecStart=/opt/vpnclient/vpnclient.sh start
ExecStop=/opt/vpnclient/vpnclient.sh stop
Type=forking
Restart=always

[Install]
WantedBy=graphical.target



これだけです。

うまくいけば電源ONした後に接続できていると思います。

終わりに

いかがでしたか。



ちょっとの手間ですが、毎回再起動時に省けるのは良いですよね!

Comments

タイトルとURLをコピーしました