#!/usr/bin/env python3
import sys, os, datetime, time
from fritzconnection import FritzConnection
#
# get environment
#
user = os.getenv('FRITZ_USERNAME')
pw = os.getenv('FRITZ_PASSWORD')
ip = os.getenv('FRITZ_IP')
#
# get commandline parameter
#
for i in range(len(sys.argv)):
match i:
case 1:
ip = sys.argv[i]
case 2:
user = sys.argv[i]
case 3:
pw = sys.argv[i]
#
# test parameter
#
if pw is None or user is None or ip is None:
print ("Not all parameter set!")
print (f"Usage: > {os.path.basename(sys.argv[0])} ip user password [internal_ip]")
print (" or set environmental variables FRITZ_USERNAME FRITZ_PASSWORD FRITZ_IP INTERN_IP")
exit()
#
# establish connection and test
#
fc = FritzConnection(address=ip, user=user, password=pw, use_cache=True)
# state = fc.call_action("WLANConfiguration1", "GetInfo") # kein Fehler
# print(state) # print router model information
#
# get all IPv4 portmappings
#
maxID = fc.call_action("WANPPPConnection1", "GetPortMappingNumberOfEntries")
PortMappingNumberOfEntries = maxID["NewPortMappingNumberOfEntries"]
port_count = 0
for x in range(PortMappingNumberOfEntries):
state = fc.call_action("WANPPPConnection1", "GetGenericPortMappingEntry", NewPortMappingIndex=x)
if state["NewExternalPort"] == 80:
if port_count == 0:
port_count = 1
print ("Portmappings port 80!")
print (f' Internal IP: {state["NewInternalClient"]} Enabled: {state["NewEnabled"]}')
#
# delete all port 80 mappings, because there can be only one
#
if port_count == 1:
print ("Delete all portmappings port 80!")
state = fc.call_action("WANPPPConnection1", "DeletePortMapping", \
NewRemoteHost="0.0.0.0", \
NewExternalPort=80, \
NewProtocol="TCP")
time.sleep(5)
else:
print ("No portmappings found!")