What could be better than regex? Of course TTP – Template Text Parser – Python module for parsing of semi-structured text data using templates.
Installation:
pip install ttp
Here is an example to use TTP for VPN sessions information
from ttp import ttp
We have command output from the ASA. To make it easier we can collect specific output using command “show vpn-sessiondb l2l | i Connection|Login Time|Duration|Protocol“
Connection : 5.5.5.5 Protocol : IKEv2 IPsec Login Time : 01:01:01 CDT Sun Sep 27 2020 Duration : 1d 00h:01m:s Connection : 7.7.7.7 Protocol : IKEv2 Login Time : 00:00:00 CDT Thu Sep 26 2020 Duration : 2d 8h:31m:08s
TTP is easy to use when we have structured and specific output.
Create a Template – just mimic the output and assign to variable.
vpn_sessions_template = """ Connection : {{remote_ip}} Protocol : {{protocol | _line_}} Login Time : {{logintime | _line_}} Duration : {{duration | _line_}} """
Create parser object and parse data using template:
parser = ttp(data=vpn_sessions_data, template=vpn_sessions_template) parser.parse()
Print result in JSON format:
vpn_sessions_results = parser.result(format='json')[0]

Once it’s done – json.loads and now we have access to all variable for each session:

More about TTP in documentation.