piframe/wifi_setup.py

57 lines
2.9 KiB
Python
Raw Normal View History

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os
import subprocess
# Make sure mount point exists
if not os.path.isdir('/var/wifi'):
os.mkdir('/var/wifi')
# Scan unmounted disks/partitions to see if we need to reconfig wifi
blkids = subprocess.run(['/usr/sbin/blkid', '-o', 'device'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
for blkid in blkids.stdout.split('\n'):
blkid = blkid.strip()
if not blkid:
continue
# Verify the disk/partition isn't mounted
findmnt = subprocess.run(['/usr/bin/findmnt', '-n', '-o', 'TARGET', blkid], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
mnt = findmnt.stdout.strip()
if not mnt and not 'zram' in blkid:
print('checking ' + blkid)
try:
# Mount the disk
subprocess.run(['/usr/bin/mount', blkid, '/var/wifi/'], universal_newlines=True)
# Check if the wifi.txt confg file is present (line 1 is essid, line 2 is PSK)
if os.path.exists('/var/wifi/wifi.txt'):
# Get wifi config
essid = ''
password = ''
with open('/var/wifi/wifi.txt', 'r') as f:
essid = f.readline().strip()
password = f.readline().strip()
if essid and password:
print('Found wifi config (' + essid + ' / ' + password + ')')
# Look for existing wifi connections that should be cleaned up
nmcli = subprocess.run(['/usr/bin/nmcli', '-t', 'connection', 'show'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
for connection in nmcli.stdout.split('\n'):
# Ignore empty lines in output
if not connection:
continue
connection_details = connection.split(':')
if connection_details[2] == '802-11-wireless':
# If we cannot clean up a wifi connection assume it's a non-issue
try:
# Cleanup existing wifi connection
print('cleaning up wifi connection ' + connection_details[0])
subprocess.run(['/usr/bin/nmcli', 'connection', 'del', connection_details[1]], universal_newlines=True)
except:
pass
print('Connecting to ' + essid + ' with password ' + password)
subprocess.run(['/usr/bin/nmcli', 'd', 'wifi', 'connect', essid, 'password', password], universal_newlines=True)
# Unmount disk so it's safe to remove
subprocess.run(['/usr/bin/umount', '/var/wifi/'], universal_newlines=True)
except:
# Unmount disk so it's safe to remove
subprocess.run(['/usr/bin/umount', '/var/wifi/'], universal_newlines=True)