import re
from lxml import etree
data = open('/tmp/targets.gmp').read()
cmds = re.findall(r'.*?', data, re.S)
pl = etree.fromstring(gmp.send_command('').encode())
plist_id = None
for p in pl.findall('.//port_list'):
if 'All IANA assigned TCP' in (p.findtext('name') or ''):
plist_id = p.get('id')
break
if not plist_id:
raise SystemExit('no IANA TCP port list found')
# clean previous glpi-* targets (idempotent re-import)
existing = etree.fromstring(gmp.send_command('').encode())
for t in existing.findall('.//target'):
if (t.findtext('name') or '').startswith('glpi-'):
gmp.send_command(f'')
ok = fail = 0
for c in cmds:
frag = etree.fromstring(c.encode())
el = etree.SubElement(frag, 'port_list')
el.set('id', plist_id)
root = etree.fromstring(gmp.send_command(etree.tostring(frag).decode()).encode())
st = root.get('status')
if st == '201':
ok += 1
else:
fail += 1
if fail <= 3:
resp = root.findtext('.//response')
print('FAIL', st, (resp or etree.tostring(root).decode())[:180])
print(f'imported={ok} failed={fail}')