Skip to content

Instantly share code, notes, and snippets.

@rexlManu
Created December 11, 2025 03:47
Show Gist options
  • Select an option

  • Save rexlManu/72f88fe9cb43088d337c716aa9426d1f to your computer and use it in GitHub Desktop.

Select an option

Save rexlManu/72f88fe9cb43088d337c716aa9426d1f to your computer and use it in GitHub Desktop.
Simple but effective way to get a new ip with fritzbox
import time
import sys
import requests
from fritzconnection import FritzConnection
from fritzconnection.core.exceptions import FritzConnectionException
from colorama import init, Fore, Style
# Initialize colorama
init(autoreset=True)
def print_header():
ascii_art = f"""
{Fore.CYAN} ______ _ __ __ __
{Fore.CYAN} / ____/_____(_) /____ / / / /_ ______
{Fore.CYAN} / /_ / ___/ / __/_ / / / / / / / / __ \\
{Fore.CYAN} / __/ / / / / /_ / /_/ /_/ / /_/ / / / /
{Fore.CYAN}/_/ /_/ /_/\\__/ /___/\\____/\\__,_/_/ /_/
{Fore.YELLOW} IP REFRESHER v1.0
"""
print(ascii_art)
print(f"{Style.DIM}---------------------------------------------")
def get_public_ip(connection=None, silent=False):
"""Retrieves the public IP address from myip.wtf."""
try:
return requests.get('https://myip.wtf/text', timeout=5).text.strip()
except Exception as e:
if not silent:
# Only print if we are not in silent mode (e.g. initial check)
# During polling, we expect failures, so we keep it quiet or handle differently
pass
return None
def reconnect(password, address='192.168.178.1'):
"""Forces a reconnection to get a new IP."""
print_header()
print(f"{Fore.BLUE}[*] Connecting to Fritz!Box at {Style.BRIGHT}{address}{Style.RESET_ALL}...")
try:
fc = FritzConnection(address=address, password=password)
except FritzConnectionException as e:
print(f"{Fore.RED}[!] Error connecting to Fritz!Box: {e}")
return
print(f"{Fore.BLUE}[*] Fetching current IP...")
current_ip = get_public_ip()
if current_ip:
print(f"{Fore.GREEN}[+] Current Public IP: {Style.BRIGHT}{current_ip}")
else:
print(f"{Fore.YELLOW}[!] Could not retrieve current IP (Internet might be down).")
print(f"{Fore.BLUE}[*] Triggering reconnection...")
# Try to force termination on WANIPConnection or WANPPPConnection
service_found = False
for service in ['WANIPConnection:1', 'WANPPPConnection:1']:
try:
# print(f"Trying service: {service}") # Debug
fc.call_action(service, 'ForceTermination')
service_found = True
break
except Exception as e:
error_str = str(e)
if "707" in error_str or "DisconnectInProgress" in error_str:
# print(f"Service {service} reported disconnect in progress (707). Proceeding...") # Debug
service_found = True
break
elif "711" in error_str or "ConnectionAlreadyTerminated" in error_str:
# print(f"Service {service} reported connection already terminated (711). Proceeding...") # Debug
service_found = True
break
# print(f"Failed on {service}: {e}") # Debug
continue
if not service_found:
print(f"{Fore.RED}[!] Error: Could not find a valid service to trigger reconnection.")
return
print(f"{Fore.CYAN}[*] Reconnection triggered. Waiting for new IP...")
start_time = time.time()
max_wait = 60 # Wait up to 60 seconds
# Spinner animation
spinner = ['|', '/', '-', '\\']
idx = 0
while time.time() - start_time < max_wait:
# Print spinner and status
sys.stdout.write(f"\r{Fore.YELLOW}{spinner[idx]} Waiting for connection... ")
sys.stdout.flush()
idx = (idx + 1) % len(spinner)
time.sleep(1)
try:
# Check IP using external service, silent=True to avoid spamming errors when offline
new_ip = get_public_ip(silent=True)
if new_ip and new_ip != "0.0.0.0":
if current_ip and new_ip != current_ip:
sys.stdout.write("\r" + " " * 40 + "\r") # Clear line
print(f"{Fore.GREEN}[+] Success! IP address has changed.")
print(f"{Fore.GREEN}[+] New Public IP: {Style.BRIGHT}{new_ip}")
return
elif not current_ip:
sys.stdout.write("\r" + " " * 40 + "\r") # Clear line
print(f"{Fore.GREEN}[+] Success! Public IP is {Style.BRIGHT}{new_ip}")
return
except Exception:
pass
print(f"\n{Fore.RED}[!] Warning: Timed out waiting for a new IP (or IP didn't change).")
# Final check
try:
new_ip = get_public_ip()
if new_ip:
print(f"{Fore.CYAN}[*] Final Public IP: {new_ip}")
except Exception:
pass
if __name__ == "__main__":
# Configuration
FRITZ_PASSWORD = "password"
FRITZ_IP = "192.168.178.1"
reconnect(FRITZ_PASSWORD, FRITZ_IP)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment