Skip to content

Instantly share code, notes, and snippets.

@chripo
Forked from pletch/scrape_pfsense_dhcp_leases.py
Last active October 7, 2021 14:00
Show Gist options
  • Save chripo/e9c197fbd82e695e8668aee2c52492ac to your computer and use it in GitHub Desktop.
Save chripo/e9c197fbd82e695e8668aee2c52492ac to your computer and use it in GitHub Desktop.
Scraps DHCP4 leases form OPNsense status_dhcp_leases.php page
#!/usr/bin/env python3
'''Scraps DHCP4 leases form OPNsense status_dhcp_leases.php page
Forked from pletch/scrape_pfsense_dhcp_leases.py
https://gist.github.com/pletch/037a4a01c95688fff65752379534455f
'''
import sys
import re
import urllib3
import requests
from lxml import html
urllib3.disable_warnings()
def opnsense_get_leases4(url, user, password) -> list[(str, str, str, str)]:
'''
Scraps all DHCP4 leases from an OPNsense instance
Returns: list[(IP, MAC, type, name)]
'''
ips = []
macs = []
types = []
hosts = []
http = requests.session()
resp = http.get(url, verify=False)
csrf = re.search('"X-CSRFToken", "(.*)"',
str(resp.text)).group(1)
hidden = re.search('<input type="hidden" name="(.*)" value="' + csrf,
str(resp.text)).group(1)
payload = {
hidden: csrf,
'login': '1',
'usernamefld': user,
'passwordfld': password
}
http.post(url, data=payload, verify=False)
resp = http.get(url, verify=False)
tree = html.fromstring(resp.content)
tbody = '//body[1]/main/div/section/div/div/section[1]/div/div/table/tbody'
ips.extend(tree.xpath(tbody + '/tr//td[2]/text()'))
types.extend(tree.xpath(tbody + '/tr//td[9]/text()'))
for node in tree.xpath(tbody + '/tr//td[3]/text()[1]'):
macs.append(str(node).strip())
for node in tree.xpath(tbody + '/tr//td[4]'):
if node.text is None:
hosts.append('UNSET')
else:
hosts.append(node.text)
return list(zip(ips, macs, types, hosts))
if __name__ == "__main__":
if len(sys.argv) < 3:
print(f'usage: {sys.argv[0]} HOST LOGIN < PASSWORD', file=sys.stderr)
sys.exit(1)
uri = f'https://{sys.argv[1]}/status_dhcp_leases.php'
leases = opnsense_get_leases4(uri,
sys.argv[2],
input('Submit your password: '))
for ip, mac, typ, host in leases:
print(f'{ip};{mac};{typ};{host}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment