From a2f81e279de1a6f8b31d00781fc6e3546d3e877e Mon Sep 17 00:00:00 2001 From: Orion Poplawski Date: Thu, 6 Feb 2025 21:36:22 -0700 Subject: [PATCH] [pfsensible-generate-module] Some more error handling around connecting/logging in --- GENERATING_MODULES.md | 1 + misc/pfsensible-generate-module | 18 ++++++++++++++++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/GENERATING_MODULES.md b/GENERATING_MODULES.md index a76230a..7c3d810 100644 --- a/GENERATING_MODULES.md +++ b/GENERATING_MODULES.md @@ -3,6 +3,7 @@ The process of writing basic pfsensible modules is hopefully greatly simplified by using the pfsensible-generate-module script. The basic workflow is as follows: +* You need a test pfSense instance with ssh access enabled. * Navigate in the pfSense web interface to the area you want to write a module for. This should be a page where you can edit settings or one where you are adding an item. * Copy the URL of the page - you will pass it to the `--url` option of the script. diff --git a/misc/pfsensible-generate-module b/misc/pfsensible-generate-module index 580ee87..29b94d3 100755 --- a/misc/pfsensible-generate-module +++ b/misc/pfsensible-generate-module @@ -105,16 +105,30 @@ if args.url is not None: client = requests.Session() # Retrieve the CSRF token first - r = client.get(login_url, verify=False) + try: + r = client.get(login_url, verify=False) + except requests.exceptions.ConnectionError as e: + print(f'Failed to connect to {login_url}: {e}', file=sys.stderr) + sys.exit(1) + csrf = re.search(".*name='__csrf_magic' value=\"([^\"]+)\".*", r.text, flags=re.MULTILINE).group(1) # Login to the web interface login_data = dict(login='Login', usernamefld=args.user, passwordfld=args.password, __csrf_magic=csrf) r = client.post(login_url, data=login_data, verify=False) - csrf = re.search(".*name='__csrf_magic' value=\"([^\"]+)\".*", r.text, flags=re.MULTILINE).group(1) + if (args.verbose >= 4): + print(f'Login URL returned {r} {r.text}') + html = lxml.html.fromstring(r.text) + #

Username or Password incorrect

+ alert = html.xpath('//div[contains(@class,"text-danger")]/*[1]/text()') + if len(alert) > 0: + print(f'Login failed with "{alert[0]}"', file=sys.stderr) + sys.exit(1) # Retrieve the configuration web page and parse it r = client.get(args.url, verify=False) + if (args.verbose >= 4): + print(f'{args.url} returned {r} {r.text}') html = lxml.html.fromstring(r.text) elif args.urlfile is not None: