39 lines
1.4 KiB
Python
39 lines
1.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Narrow, non-shell ModemManager control surface.
|
|
|
|
Only enable/disable is supported. Never accepts PIN/PUK or arbitrary mmcli flags.
|
|
Authorization is delegated to ModemManager/polkit.
|
|
"""
|
|
import json
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
|
|
ID = re.compile(r'^(?:[0-9]{1,5}|/org/freedesktop/ModemManager1/Modem/[0-9]{1,5})$')
|
|
|
|
|
|
def control(modem_id, action, runner=subprocess.run):
|
|
if not ID.fullmatch(modem_id):
|
|
return {'ok': False, 'error': 'Invalid modem identifier'}
|
|
if action not in ('enable', 'disable'):
|
|
return {'ok': False, 'error': 'Unsupported modem action'}
|
|
if not shutil.which('mmcli'):
|
|
return {'ok': False, 'error': 'mmcli not installed'}
|
|
try:
|
|
result = runner(['mmcli', '-m', modem_id, '--' + action], capture_output=True,
|
|
text=True, timeout=25, check=False)
|
|
return {'ok': result.returncode == 0,
|
|
'error': '' if result.returncode == 0 else (result.stderr.strip() or 'ModemManager rejected request')[:300]}
|
|
except (OSError, subprocess.TimeoutExpired) as exc:
|
|
return {'ok': False, 'error': str(exc)[:300]}
|
|
|
|
|
|
if __name__ == '__main__':
|
|
if len(sys.argv) != 3:
|
|
result = {'ok': False, 'error': 'Usage: modem_control.py MODEM_ID enable|disable'}
|
|
else:
|
|
result = control(sys.argv[1], sys.argv[2])
|
|
print(json.dumps(result, ensure_ascii=False))
|
|
sys.exit(0 if result['ok'] else 1)
|