在python中解析openvpn状态日志
openvpn-status的Python项目详细描述
openvpn status是一个python库。它解析openvpn状态日志并 它为您导入python数据结构。
它与cpython2.7,3.4,3.5,3.6,3.7和pypy兼容。
安装
pip install openvpn-status
别忘了把它放在setup.py/requirements.txt中。
开始
您可以将openvpn服务器配置为记录客户端状态。在通常情况下 可以通过将status /path/to/openvpn-status.log行添加到 /etc/openvpn/openvpn.conf。例如:
proto udp port 1194 dev tun0 status /var/run/openvpn-status.log
openvpn服务器运行后,将创建并写入日志文件。看起来 例如:
OpenVPN CLIENT LIST Updated,Thu Jun 18 08:12:15 2015 Common Name,Real Address,Bytes Received,Bytes Sent,Connected Since foo@example.com,10.10.10.10:49502,334948,1973012,Thu Jun 18 04:23:03 2015 bar@example.com,10.10.10.10:64169,1817262,28981224,Thu Jun 18 04:08:39 2015 ROUTING TABLE Virtual Address,Common Name,Real Address,Last Ref 192.168.255.134,foo@example.com,10.10.10.10:49502,Thu Jun 18 08:12:09 2015 192.168.255.126,bar@example.com,10.10.10.10:64169,Thu Jun 18 08:11:55 2015 GLOBAL STATS Max bcast/mcast queue length,0 END
现在我们可以用这个库解析日志文件:
fromopenvpn_statusimportparse_statuswithopen('/var/run/openvpn-status.log')aslogfile:status=parse_status(logfile.read())print(status.updated_at)# datetime.datetime(2015, 6, 18, 8, 12, 15)foo_client=status.client_list['169.254.0.1']print(foo_client.common_name)# foo@example.comprint(foo_client.bytes_received)# 334.9 kBprint(foo_client.bytes_sent)# 2.0 MBprint(int(foo_client.bytes_sent))# 2097152
更多细节见API reference。