add listboxes command

This commit is contained in:
2025-04-09 09:44:45 +02:00
parent 16af1ddf2d
commit e48e1302c0

75
listboxes Executable file
View File

@ -0,0 +1,75 @@
#!/usr/bin/env python3
import sys
from pathlib import Path
from configparser import ConfigParser
from socket import gethostbyname, create_connection
# cfgdir = Path('~/boxtools/cfg').expanduser()
cfgdir = Path(__file__).parent / 'cfg'
print(cfgdir, cfgdir.is_dir())
def check_ssh(host, port=22):
try:
addr = gethostbyname(host)
test_socket = create_connection((addr, port), timeout=0.1)
except Exception as e:
if isinstance(e, TimeoutError):
return False, addr
return False, ''
else:
test_socket.close()
return True, addr
opt = sys.argv[-1]
header = ['box name', 'box type', 'frappy', 'R']
if opt != 's':
if opt == 'a':
header.extend(['*online ip ', 'MAC addr'])
else:
header.append('ip')
table = [header]
for file in sorted(cfgdir.glob('*.cfg')):
parser = ConfigParser()
parser.read(file)
info = {k: dict(parser[k]) for k in parser.sections()}
router = info.get('ROUTER')
router = 'R' if router else ''
frappy = info.get('FRAPPY', {}).get('cfg', '')
box = info.get('BOX', {})
row = [file.stem, box.get('type', 'unknown'), frappy, router]
if opt != 's':
row.append('')
if opt == 'a':
row.append(box.get('mac', ''))
table.append(row)
sizes = [max([len(row[i]) for row in table]) for i in range(len(header))]
inside = False
print()
for row in table:
if inside:
if opt != 's':
online, addr = check_ssh(row[0])
if opt == 'a':
addr = ('*' if online else ' ') + addr
elif not online:
continue
row[4] = addr
print(' '.join(v.ljust(l) for v, l in zip(row, sizes)))
if not inside:
print()
inside = True
USAGE = """
Usage:
listboxes o # only boxes online (default)
listboxes a # all boxes, all info
listboxes s # short (without ip and online check)
"""
if opt in 'sao':
print()
else:
print(USAGE)