Skip to content

Instantly share code, notes, and snippets.

@terenty-rezman
Created July 23, 2020 10:25
Show Gist options
  • Select an option

  • Save terenty-rezman/6bf26c8c4090cb04fc79a20edbd44a29 to your computer and use it in GitHub Desktop.

Select an option

Save terenty-rezman/6bf26c8c4090cb04fc79a20edbd44a29 to your computer and use it in GitHub Desktop.
print currently connected OpenVPN clients to console
#!/usr/bin/env python3
from telnetlib import Telnet
import telnetlib
import re
# openvpn managment address and port
HOST = "localhost"
PORT = 9969
class ClientInfo:
def __init__(self, name, real_address, received, sent, connected_since):
self.name = name
self.real_address = real_address
self.received = received
self.sent = sent
self.connected_since = connected_since
def __iter__(self):
return iter((self.name, self.real_address, self.received, self.sent, self.connected_since))
def __str__(self):
string = ""
for item in self:
string += str(item) + " "
return string
def read_openvpn_status_telnet(host, port) -> str:
STATUS_CMD = "status"
EXIT_CMD = "exit"
# telenet to managment port of openvpn
tn = telnetlib.Telnet(host, port)
# send status command
tn.write(STATUS_CMD.encode('ascii') + b"\n")
# read the reply
status_reply = tn.read_until(b"END").decode('ascii')
# send exit command
tn.write(EXIT_CMD.encode('ascii') + b"\n")
# close the telenet connetcion
tn.close()
return status_reply
def parse_clients_from_status(status_str: str):
match = re.findall(r"^[^,]+,[^,]+,\d+,\d+,[^(\r\n)]+",
status_str, re.MULTILINE)
clients = []
for client_str in match:
params = client_str.split(',')
client = ClientInfo(params[0], params[1],
params[2], params[2], params[4])
clients.append(client)
return clients
def openvpn_managment_client_list(host, port):
openvpn_status = read_openvpn_status_telnet(host, port)
clients = parse_clients_from_status(openvpn_status)
return clients
if __name__ == "__main__":
clients = openvpn_managment_client_list(HOST, PORT)
print()
for client in clients:
print(client)
print()
@terenty-rezman

Copy link
Copy Markdown
Author

The script connets to OpenVPN management port so you need to enable this port in your open vpn server .conf file by adding smthng like this:
management localhost 9969

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment