Version corrgida

This commit is contained in:
Miguel 2025-04-03 11:05:04 +02:00
parent bd5680aa45
commit 9d62219325
3 changed files with 1 additions and 158 deletions

View File

@ -40,17 +40,10 @@ def run_command(logger, cmd: str) -> bool:
logger.info(f"Command output: {result.stdout}")
if result.stderr:
logger.error(f"Command error: {result.stderr}")
<<<<<<< HEAD
if result.returncode != 0:
logger.error(f"Command failed with return code: {result.returncode}")
=======
if result.returncode != 0:
logger.error(f"Command failed with return code: {result.returncode}")
>>>>>>> 60f083413a5d4bfd498d24468d6ca2eaa23a5d9d
return result.returncode == 0
except Exception as e:
@ -76,13 +69,9 @@ def main():
logger.info("Usage: ip_changer_admin.py <interface> <ip|dhcp|command>")
logger.info("Example for static IP: ip_changer_admin.py Ethernet 192.168.1.100")
logger.info("Example for DHCP: ip_changer_admin.py Ethernet dhcp")
<<<<<<< HEAD
logger.info(
'Example for command: ip_changer_admin.py Ethernet "netsh interface ip set address..."'
)
=======
logger.info("Example for command: ip_changer_admin.py Ethernet \"netsh interface ip set address...\"")
>>>>>>> 60f083413a5d4bfd498d24468d6ca2eaa23a5d9d
return 1
interface = sys.argv[1]
@ -92,18 +81,13 @@ def main():
logger.info(f"Parameter: {param}")
# Check if the second parameter is a full command (starts with netsh)
<<<<<<< HEAD
if param.lower().startswith("netsh"):
=======
if param.lower().startswith('netsh'):
>>>>>>> 60f083413a5d4bfd498d24468d6ca2eaa23a5d9d
cmd = param
elif param.lower() == "dhcp":
cmd = f'netsh interface ip set address "{interface}" dhcp'
else:
# Assume it's an IP address (for backward compatibility)
ip = param
<<<<<<< HEAD
# If more parameters are provided, use them for subnet mask
if len(sys.argv) > 3:
@ -115,19 +99,6 @@ def main():
gateway = ".".join(ip.split(".")[:3] + ["1"])
cmd = f'netsh interface ip set address "{interface}" static {ip} {subnet_mask} {gateway}'
=======
# If more parameters are provided, use them for subnet mask
if len(sys.argv) > 3:
subnet_mask = sys.argv[3]
else:
subnet_mask = "255.255.255.0"
# Extract first three octets for gateway
gateway = '.'.join(ip.split('.')[:3] + ['1'])
cmd = f'netsh interface ip set address "{interface}" static {ip} {subnet_mask} {gateway}'
>>>>>>> 60f083413a5d4bfd498d24468d6ca2eaa23a5d9d
logger.info(f"Command to execute: {cmd}")
success = run_command(logger, cmd)

View File

@ -1 +1 @@
{"last_interface": "Ethernet", "last_ip_prefix": "10.1.22", "previous_config": {"name": "Ethernet", "ip_address": "10.1.22.249", "subnet_mask": "255.240.0.0", "gateway": "10.1.22.1", "dhcp_enabled": false}}
{"last_interface": "Ethernet", "last_ip_prefix": "10.1.22", "previous_config": {"name": "Ethernet", "ip_address": "10.1.22.249", "subnet_mask": "255.224.0.0", "gateway": "10.1.22.1", "dhcp_enabled": false}}

View File

@ -183,7 +183,6 @@ class IPChangerApp:
"""Set up traces for subnet mask and CIDR fields safely"""
# First initialize variables
self.subnet_mask.set(self.subnet_mask.get()) # Ensure current value is valid
<<<<<<< HEAD
self.cidr_bits.set(self.cidr_bits.get()) # Ensure current value is valid
# Add traces using a different approach - using add not trace_add
@ -192,16 +191,6 @@ class IPChangerApp:
self.log_message("Subnet mask traces initialized")
=======
self.cidr_bits.set(self.cidr_bits.get()) # Ensure current value is valid
# Add traces using a different approach - using add not trace_add
self.subnet_mask.trace("w", self.on_subnet_mask_changed)
self.cidr_bits.trace("w", self.on_cidr_bits_changed)
self.log_message("Subnet mask traces initialized")
>>>>>>> 60f083413a5d4bfd498d24468d6ca2eaa23a5d9d
def remove_mask_traces(self):
"""Not needed - we'll use a different approach"""
pass # Intentionally empty
@ -291,11 +280,7 @@ class IPChangerApp:
self.ip_frame, textvariable=self.last_octet, width=5
)
self.last_octet_entry.grid(row=0, column=3, sticky="w", padx=5)
<<<<<<< HEAD
=======
>>>>>>> 60f083413a5d4bfd498d24468d6ca2eaa23a5d9d
# Add subnet mask configuration
ttk.Label(self.ip_frame, text="Subnet Mask:").grid(
row=1, column=0, sticky="w", padx=5
@ -305,26 +290,14 @@ class IPChangerApp:
self.ip_frame, textvariable=self.subnet_mask, width=15
)
self.subnet_entry.grid(row=1, column=1, sticky="w", padx=5)
<<<<<<< HEAD
=======
>>>>>>> 60f083413a5d4bfd498d24468d6ca2eaa23a5d9d
ttk.Label(self.ip_frame, text="CIDR (/bits):").grid(
row=1, column=2, sticky="w", padx=5
)
self.cidr_bits = tk.StringVar(value="24")
<<<<<<< HEAD
self.cidr_entry = ttk.Entry(self.ip_frame, textvariable=self.cidr_bits, width=5)
self.cidr_entry.grid(row=1, column=3, sticky="w", padx=5)
=======
self.cidr_entry = ttk.Entry(
self.ip_frame, textvariable=self.cidr_bits, width=5
)
self.cidr_entry.grid(row=1, column=3, sticky="w", padx=5)
>>>>>>> 60f083413a5d4bfd498d24468d6ca2eaa23a5d9d
# Don't add traces here, we'll do it after widget creation is complete
# Sección de historial
@ -462,9 +435,6 @@ class IPChangerApp:
self.config.last_ip_prefix = ip_prefix
self.config.save_config()
self.log_message(f"Selected IP prefix from history: {ip_prefix}")
# Update ping target for the new IP prefix
self.update_ping_target(ip_prefix)
# Update ping target for the new IP prefix
self.update_ping_target(ip_prefix)
@ -587,11 +557,7 @@ class IPChangerApp:
if interface.ip_address:
prefix = ".".join(interface.ip_address.split(".")[:3])
self.ip_prefix.set(prefix)
<<<<<<< HEAD
=======
>>>>>>> 60f083413a5d4bfd498d24468d6ca2eaa23a5d9d
# Update ping target for the new IP prefix
self.update_ping_target(prefix)
@ -606,11 +572,7 @@ class IPChangerApp:
prefix = self.ip_prefix.get().strip()
last_octet = self.last_octet.get().strip()
subnet_mask = self.subnet_mask.get().strip()
<<<<<<< HEAD
=======
>>>>>>> 60f083413a5d4bfd498d24468d6ca2eaa23a5d9d
# Validar formato del prefijo
if not re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}", prefix):
return False, "IP prefix must be in format: xxx.xxx.xxx"
@ -618,19 +580,11 @@ class IPChangerApp:
# Validar último octeto
if not last_octet.isdigit() or not 0 <= int(last_octet) <= 255:
return False, "Last octet must be between 0 and 255"
<<<<<<< HEAD
# Validar máscara de subred
if not self.is_valid_subnet_mask(subnet_mask):
return False, "Invalid subnet mask format"
=======
# Validar máscara de subred
if not self.is_valid_subnet_mask(subnet_mask):
return False, "Invalid subnet mask format"
>>>>>>> 60f083413a5d4bfd498d24468d6ca2eaa23a5d9d
# Construir y validar IP completa
ip = f"{prefix}.{last_octet}"
ipaddress.IPv4Address(ip)
@ -641,15 +595,11 @@ class IPChangerApp:
return False, f"Invalid IP address: {str(e)}"
def execute_admin_script(
<<<<<<< HEAD
self,
interface: str,
mode: str,
debug: bool = True,
subnet_mask: str = "255.255.255.0",
=======
self, interface: str, mode: str, debug: bool = True, subnet_mask: str = "255.255.255.0"
>>>>>>> 60f083413a5d4bfd498d24468d6ca2eaa23a5d9d
) -> bool:
"""
Ejecuta el script administrativo con los argumentos proporcionados
@ -669,13 +619,9 @@ class IPChangerApp:
# Construir la línea de argumentos - pass both IP and subnet as a single parameter
if mode != "dhcp":
# For static IP, create the netsh command with subnet mask
<<<<<<< HEAD
gateway = (
f"{self.get_ip_prefix(mode)}.1" # Use the first three octets of the IP
)
=======
gateway = f"{self.get_ip_prefix(mode)}.1" # Use the first three octets of the IP
>>>>>>> 60f083413a5d4bfd498d24468d6ca2eaa23a5d9d
netsh_cmd = f'netsh interface ip set address "{interface}" static {mode} {subnet_mask} {gateway}'
args = f'"{script_path}" "{interface}" "{netsh_cmd}"'
else:
@ -801,11 +747,7 @@ class IPChangerApp:
# Save the ping target when used
self.save_current_ping_target()
<<<<<<< HEAD
=======
>>>>>>> 60f083413a5d4bfd498d24468d6ca2eaa23a5d9d
self.log_message(f"Pinging {target}...")
# Crear un hilo para el ping para no bloquear la interfaz
@ -955,17 +897,10 @@ class IPChangerApp:
if not interface:
self.show_error("Please select a network interface")
return
<<<<<<< HEAD
# Guardar configuración actual antes de cambiarla
self.save_previous_config(interface)
=======
# Guardar configuración actual antes de cambiarla
self.save_previous_config(interface)
>>>>>>> 60f083413a5d4bfd498d24468d6ca2eaa23a5d9d
# Validar IP
is_valid, result = self.validate_ip_input()
if not is_valid:
@ -974,22 +909,14 @@ class IPChangerApp:
ip = result
subnet_mask = self.subnet_mask.get()
<<<<<<< HEAD
# Guardar IP actual en el historial
self.add_to_history(self.ip_prefix.get())
=======
# Guardar IP actual en el historial
self.add_to_history(self.ip_prefix.get())
>>>>>>> 60f083413a5d4bfd498d24468d6ca2eaa23a5d9d
# Log the actual command we'll be executing
gateway = f"{self.ip_prefix.get()}.1"
command = f'netsh interface ip set address "{interface}" static {ip} {subnet_mask} {gateway}'
self.log_message(f"Executing network command: {command}")
<<<<<<< HEAD
# Ejecutar script con privilegios - pass subnet mask
if self.execute_admin_script(
@ -1000,14 +927,6 @@ class IPChangerApp:
self.log_message(
f"Successfully set static IP {ip} with mask {subnet_mask} on {interface}"
)
=======
# Ejecutar script con privilegios - pass subnet mask
if self.execute_admin_script(interface, ip, debug=True, subnet_mask=subnet_mask):
time.sleep(2) # Esperar a que se apliquen los cambios
self.refresh_interfaces()
self.log_message(f"Successfully set static IP {ip} with mask {subnet_mask} on {interface}")
>>>>>>> 60f083413a5d4bfd498d24468d6ca2eaa23a5d9d
else:
self.show_error("Failed to set static IP. Check the log for details.")
@ -1100,17 +1019,10 @@ class IPChangerApp:
# Use a static variable to prevent recursion
if hasattr(self, "_updating_mask") and self._updating_mask:
return
<<<<<<< HEAD
try:
self._updating_mask = True
=======
try:
self._updating_mask = True
>>>>>>> 60f083413a5d4bfd498d24468d6ca2eaa23a5d9d
mask = self.subnet_mask.get()
if self.is_valid_subnet_mask(mask):
# Convert mask to bits
@ -1126,17 +1038,10 @@ class IPChangerApp:
# Use a static variable to prevent recursion
if hasattr(self, "_updating_bits") and self._updating_bits:
return
<<<<<<< HEAD
try:
self._updating_bits = True
=======
try:
self._updating_bits = True
>>>>>>> 60f083413a5d4bfd498d24468d6ca2eaa23a5d9d
bits_str = self.cidr_bits.get()
if bits_str.isdigit():
bits = int(bits_str)
@ -1153,22 +1058,14 @@ class IPChangerApp:
"""Validate if the string is a valid subnet mask"""
try:
# Check if it has the format x.x.x.x
<<<<<<< HEAD
parts = mask.split(".")
if len(parts) != 4:
return False
=======
parts = mask.split('.')
if len(parts) != 4:
return False
>>>>>>> 60f083413a5d4bfd498d24468d6ca2eaa23a5d9d
# Each part should be a number between 0-255
for part in parts:
if not part.isdigit() or not 0 <= int(part) <= 255:
return False
<<<<<<< HEAD
# Check if it's a valid subnet mask pattern
# Convert to binary and ensure it's a continuous sequence of 1s followed by 0s
@ -1176,15 +1073,6 @@ class IPChangerApp:
if "01" in binary: # If there's a 0 followed by 1, it's not valid
return False
=======
# Check if it's a valid subnet mask pattern
# Convert to binary and ensure it's a continuous sequence of 1s followed by 0s
binary = ''.join([bin(int(octet))[2:].zfill(8) for octet in parts])
if '01' in binary: # If there's a 0 followed by 1, it's not valid
return False
>>>>>>> 60f083413a5d4bfd498d24468d6ca2eaa23a5d9d
return True
except Exception:
return False
@ -1193,15 +1081,9 @@ class IPChangerApp:
"""Convert subnet mask to CIDR notation bits"""
try:
# Convert each octet to binary and count the number of 1s
<<<<<<< HEAD
parts = mask.split(".")
binary = "".join([bin(int(octet))[2:].zfill(8) for octet in parts])
return binary.count("1")
=======
parts = mask.split('.')
binary = ''.join([bin(int(octet))[2:].zfill(8) for octet in parts])
return binary.count('1')
>>>>>>> 60f083413a5d4bfd498d24468d6ca2eaa23a5d9d
except Exception as e:
self.log_message(f"Error converting subnet mask to CIDR: {str(e)}")
return 24 # Default to /24
@ -1210,7 +1092,6 @@ class IPChangerApp:
"""Convert CIDR bits to subnet mask in dotted decimal notation"""
try:
# Create a binary string with the specified number of 1s followed by 0s
<<<<<<< HEAD
binary = "1" * bits + "0" * (32 - bits)
# Split the binary string into 4 octets and convert each to decimal
@ -1218,15 +1099,6 @@ class IPChangerApp:
decimals = [str(int(octet, 2)) for octet in octets]
return ".".join(decimals)
=======
binary = '1' * bits + '0' * (32 - bits)
# Split the binary string into 4 octets and convert each to decimal
octets = [binary[i:i+8] for i in range(0, 32, 8)]
decimals = [str(int(octet, 2)) for octet in octets]
return '.'.join(decimals)
>>>>>>> 60f083413a5d4bfd498d24468d6ca2eaa23a5d9d
except Exception as e:
self.log_message(f"Error converting CIDR to subnet mask: {str(e)}")
return "255.255.255.0" # Default to 255.255.255.0