Friday, March 13, 2020

Python Script to Collect AnyConnect Users Traffic Volume

Hello everyone,

This is a quick and dirty script that I put together to SSH into an ASA, do the "show vpn-session anyconnect" command, scrape the output for usernames and traffic usage, sort the output from highest to lowest, and finally print the output and put it in a text file.

This was done in a rush to try and figure out how was using all the bandwidth. I know there are a million ways to improve it and would like to hear suggestions. Also this was only tested on ASA 9.8.

Without further delay, here is the script:

# -*- coding: utf-8 -*- """ Created on Thu Mar 12 11:46:02 2020 @author: jj """ import re from operator import itemgetter from netmiko import Netmiko from getpass import getpass i = 1 userlist = [] gig = 1024**3 meg = 1024**2 data = '' un = input('Username: ') pw = getpass('Password: ') ip = input('IP address: ') device = { 'host': ip, 'username': un, 'password': pw, 'device_type': 'cisco_asa', } try: net_conn = Netmiko(**device) print('Connected to:', ip) data = net_conn.send_command('show vpn- anyconnect') net_conn.cleanup() net_conn.disconnect() print('Closed connection to device') except Exception as e: print(e) lines = data.splitlines() for line in lines: userstats = [] if re.match('\AUser', line): user = line.split()[2] if re.match('\ABytes', line): tx = int(line.split()[3]) rx = int(line.split()[7]) userstats = [user, tx, rx, rx+tx] userlist.append(userstats) sortedlist = sorted(userlist, key=itemgetter(3), reverse=True) with open(ip+'.txt', 'w') as output: for item in sortedlist: if item[3] > gig: string = (str(i)+'- '+item[0]+' Volume of traffic: '+ str(item[3]/(gig))+ ' GBytes') print(string) output.write(string+'\n') else: string = (str(i)+'- '+item[0]+' Volume of traffic: '+ str(item[3]/(meg))+ ' MBytes') print(string) output.write(string+'\n') i+=1 

Hope it helps someone out there,

-JJ



No comments:

Post a Comment