Disposable sys-net: Automatically connect wifi (config file or RPC service)

I should have posted this before but based on @ddevz’s work, I use this Python script:

#!/usr/bin/env python3
"""Check for credentials with qubesdb and connect wifi

Through the qube's features, a list of wifis should be provided
to get the script trying to connect to it. I.e.:

.. code:: console

   [user@dom0] $ qvm-features sys-net
   [...]
   vm-config.wifis name2 1 3
   vm-config.wifis.1.ssid WifiHotspotSSID
   vm-config.wifis.1.password <P455W0RD>
   vm-config.wifis.name2.ssid OtherHotspot
   [...]

The vm-config.wifis feature list the wifis identifiers, by order of priority.
Then, for each wifi ID, SSID and password are provided, as
vm-config.wifis.<IDENTIFIER>.<KEY>
"""

import subprocess

import qubesdb

db = qubesdb.QubesDB()

ROOT_FEATURE_KEY = '/vm-config/wifis'

def connect_wifi(wifi_id: str) -> int:
    """Read the keys of wifi_id and run the appropriate nmcli command

    Return the exit code of nmcli or -1 if there is no SSID associated with the
    wifi_id."""
    key = '.'.join((ROOT_FEATURE_KEY, wifi_id, '{}'))
    ssid = db.read(key.format('ssid')).decode()
    password = db.read(key.format('password')).decode()

    if ssid is None:
        return -1

    process = subprocess.run(['nmcli', 'device', 'wifi', 'connect', f'{ssid}', 'password', f'{password}'])
    return process.returncode

def main():
    raw_wifis = db.read(ROOT_FEATURE_KEY).decode()
    if raw_wifis is None:
        return

    for wifi_id in raw_wifis.split():
        print(f"Try to connect wifi #{wifi_id}")

        if not connect_wifi(wifi_id):
            print(f"\tSuccess")
            return

        print(f"\tFailure")

if __name__ == "__main__":
    main()

The main differences is that it works with more than one pair of credentials and doesn’t check the hostname. The documentation is included in the comments. I combine this with this excellent guide from @Atrate:

Anyway, I think that your post would be a great 3rd solution to this guide. I would just skip the explanations (with a proper link to the other guide explaning the use of vm-config).

1 Like