Skip to content

Instantly share code, notes, and snippets.

@Derkades
Created November 8, 2023 09:15
Show Gist options
  • Save Derkades/aed54e1e0216f0751cf94c7875bd9d17 to your computer and use it in GitHub Desktop.
Save Derkades/aed54e1e0216f0751cf94c7875bd9d17 to your computer and use it in GitHub Desktop.
NetworkManager script to automatically log into NS "WiFi in de trein" network. Place in `/etc/NetworkManager/dispatcher.d`.
#!/usr/bin/env python3
import syslog
import os
import sys
import requests
import time
from bs4 import BeautifulSoup
def attempt_login():
syslog.syslog('Requesting homepage for CSRF token...')
response = requests.get('http://portal.nstrein.ns.nl')
response.raise_for_status()
soup = BeautifulSoup(response.text, 'lxml')
input = soup.find('input', {'id': 'csrfToken'})
csrf_token = input['value']
syslog.syslog('Making internet request...')
requests.post('http://portal.nstrein.ns.nl/nstrein:main/internet?csrfToken=' + csrf_token).raise_for_status()
def check_connection():
response = requests.get('https://icanhazip.com')
response.raise_for_status()
syslog.syslog('Connected to the internet with external IP address: ' + response.text.strip())
def main():
if sys.argv[2] != 'up':
syslog.syslog('Ignoring non-up action: ' + sys.argv[2])
return
if os.environ['CONNECTION_ID'].lower() != 'wifi in de trein':
syslog.syslog('Ignoring connection: ' + os.environ['CONNECTION_ID'])
return
while True:
try:
attempt_login()
check_connection()
return
except Exception as ex:
print(ex)
time.sleep(5)
main()
@Derkades
Copy link
Author

Derkades commented Nov 8, 2023

Dependencies for Fedora: dnf install python3-requests python3-beautifulsoup4 python3-lxml

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment