Bash Script for Quick OpenVPN Server Setup on Ubuntu 22.04 LTS

Here's a bash script that automates the installation and configuration of OpenVPN on Ubuntu 22.04, as well as creates a client configuration file that can be used to connect to the server:

Save the below script to a file (e.g., make it executable with chmod +x, and then run it with sudo ./

This script will:

  1. Update and upgrade packages
  2. Install OpenVPN and easy-rsa
  3. Copy the easy-rsa scripts to the OpenVPN directory
  4. Create the Public Key Infrastructure (PKI), including the CA, DH params, and server certificate and key
  5. Create the OpenVPN server configuration file
  6. Enable IP forwarding
  7. Start and enable the

The script:


# Update and upgrade packages
apt update && apt upgrade -y

# Install necessary packages
apt install openvpn easy-rsa -y

# Copy easy-rsa scripts to OpenVPN directory
cp -r /usr/share/easy-rsa/ /etc/openvpn/

# Create the PKI, set up the CA, the DH params, and create a server certificate and key
cd /etc/openvpn/easy-rsa/
source ./vars
./pkitool --initca
./pkitool --server server
openvpn --genkey --secret /etc/openvpn/ta.key

# Create the server configuration file
cat <<EOF > /etc/openvpn/server.conf
dev tun
proto udp
port 1194
ca /etc/openvpn/easy-rsa/keys/ca.crt
cert /etc/openvpn/easy-rsa/keys/server.crt
key /etc/openvpn/easy-rsa/keys/server.key
dh /etc/openvpn/easy-rsa/keys/dh2048.pem
ifconfig-pool-persist ipp.txt
push "dhcp-option DNS"
push "dhcp-option DNS"
push "redirect-gateway def1 bypass-dhcp"
keepalive 10 120
tls-auth /etc/openvpn/ta.key 0
cipher AES-256-CBC
user nobody
group nogroup
status openvpn-status.log
verb 3

# Enable IP forwarding
sed -i 's/#net.ipv4.ip_forward=1/net.ipv4.ip_forward=1/' /etc/sysctl.conf
sysctl -p

# Start and enable OpenVPN service
systemctl start openvpn@server
systemctl enable openvpn@server

# Generate client certificates and keys
cd /etc/openvpn/easy-rsa/
./pkitool client

# Create client configuration file
cat <<EOF > /etc/openvpn/client.conf
dev tun
proto udp
remote $(hostname -I | awk '{print $1}') 1194
resolv-retry infinite
ca /etc/openvpn/easy-rsa/keys/ca.crt
cert /etc/openvpn/easy-rsa/keys/client.crt
key /etc/openvpn/easy-rsa/keys/client.key
tls-auth /etc/openvpn/ta.key 1
cipher AES-256-CBC
verb 3

# Restart OpenVPN service
systemctl restart openvpn@server

echo "OpenVPN server installation and configuration complete."
echo "The client configuration file is located at /etc/openvpn/client.conf"