Agregado de ping y del campo de mascara
This commit is contained in:
parent
4ee8015953
commit
be03b1a730
|
@ -1,29 +1,27 @@
|
||||||
import sys
|
import sys
|
||||||
import subprocess
|
import subprocess
|
||||||
import ctypes
|
import ctypes
|
||||||
import time
|
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
|
|
||||||
def setup_logging():
|
def setup_logging():
|
||||||
"""Configura el logging para el script"""
|
"""Configura el logging para el script"""
|
||||||
log_dir = os.path.join(os.path.dirname(__file__), 'logs')
|
log_dir = os.path.join(os.path.dirname(__file__), "logs")
|
||||||
if not os.path.exists(log_dir):
|
if not os.path.exists(log_dir):
|
||||||
os.makedirs(log_dir)
|
os.makedirs(log_dir)
|
||||||
|
|
||||||
log_file = os.path.join(log_dir, 'ip_changer_admin.log')
|
log_file = os.path.join(log_dir, "ip_changer_admin.log")
|
||||||
|
|
||||||
logging.basicConfig(
|
logging.basicConfig(
|
||||||
level=logging.DEBUG,
|
level=logging.DEBUG,
|
||||||
format='%(asctime)s - %(levelname)s - %(message)s',
|
format="%(asctime)s - %(levelname)s - %(message)s",
|
||||||
handlers=[
|
handlers=[logging.FileHandler(log_file), logging.StreamHandler(sys.stdout)],
|
||||||
logging.FileHandler(log_file),
|
|
||||||
logging.StreamHandler(sys.stdout)
|
|
||||||
]
|
|
||||||
)
|
)
|
||||||
return logging.getLogger(__name__)
|
return logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
def is_admin():
|
def is_admin():
|
||||||
"""Verifica si el script se está ejecutando con privilegios de administrador"""
|
"""Verifica si el script se está ejecutando con privilegios de administrador"""
|
||||||
try:
|
try:
|
||||||
|
@ -31,64 +29,79 @@ def is_admin():
|
||||||
except:
|
except:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def run_command(logger, cmd: str) -> bool:
|
def run_command(logger, cmd: str) -> bool:
|
||||||
"""Ejecuta un comando y retorna True si fue exitoso"""
|
"""Ejecuta un comando y retorna True si fue exitoso"""
|
||||||
logger.info(f"Executing command: {cmd}")
|
logger.info(f"Executing command: {cmd}")
|
||||||
try:
|
try:
|
||||||
result = subprocess.run(
|
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
|
||||||
cmd,
|
|
||||||
shell=True,
|
|
||||||
capture_output=True,
|
|
||||||
text=True
|
|
||||||
)
|
|
||||||
|
|
||||||
if result.stdout:
|
if result.stdout:
|
||||||
logger.info(f"Command output: {result.stdout}")
|
logger.info(f"Command output: {result.stdout}")
|
||||||
if result.stderr:
|
if result.stderr:
|
||||||
logger.error(f"Command error: {result.stderr}")
|
logger.error(f"Command error: {result.stderr}")
|
||||||
|
|
||||||
|
if result.returncode != 0:
|
||||||
|
logger.error(f"Command failed with return code: {result.returncode}")
|
||||||
|
|
||||||
return result.returncode == 0
|
return result.returncode == 0
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error executing command: {str(e)}")
|
logger.error(f"Error executing command: {str(e)}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
# Log startup information
|
# Log startup information
|
||||||
logger.info("=" * 50)
|
logger.info("=" * 50)
|
||||||
logger.info(f"Script started at {datetime.now()}")
|
logger.info(f"Script started at {datetime.now()}")
|
||||||
logger.info(f"Arguments received: {sys.argv}")
|
logger.info(f"Arguments received: {sys.argv}")
|
||||||
logger.info(f"Running with admin privileges: {is_admin()}")
|
logger.info(f"Running with admin privileges: {is_admin()}")
|
||||||
|
|
||||||
if not is_admin():
|
if not is_admin():
|
||||||
logger.error("This script requires administrator privileges")
|
logger.error("This script requires administrator privileges")
|
||||||
return 1
|
return 1
|
||||||
|
|
||||||
if len(sys.argv) < 3:
|
if len(sys.argv) < 3:
|
||||||
logger.error("Insufficient arguments")
|
logger.error("Insufficient arguments")
|
||||||
logger.info("Usage: ip_changer_admin.py <interface> <ip|dhcp>")
|
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 static IP: ip_changer_admin.py Ethernet 192.168.1.100")
|
||||||
logger.info("Example for DHCP: ip_changer_admin.py Ethernet dhcp")
|
logger.info("Example for DHCP: ip_changer_admin.py Ethernet dhcp")
|
||||||
|
logger.info(
|
||||||
|
'Example for command: ip_changer_admin.py Ethernet "netsh interface ip set address..."'
|
||||||
|
)
|
||||||
return 1
|
return 1
|
||||||
|
|
||||||
interface = sys.argv[1]
|
interface = sys.argv[1]
|
||||||
ip_mode = sys.argv[2]
|
param = sys.argv[2]
|
||||||
|
|
||||||
logger.info(f"Processing request for interface: {interface}")
|
logger.info(f"Processing request for interface: {interface}")
|
||||||
logger.info(f"IP mode: {ip_mode}")
|
logger.info(f"Parameter: {param}")
|
||||||
|
|
||||||
if ip_mode.lower() == "dhcp":
|
# Check if the second parameter is a full command (starts with netsh)
|
||||||
|
if param.lower().startswith("netsh"):
|
||||||
|
cmd = param
|
||||||
|
elif param.lower() == "dhcp":
|
||||||
cmd = f'netsh interface ip set address "{interface}" dhcp'
|
cmd = f'netsh interface ip set address "{interface}" dhcp'
|
||||||
else:
|
else:
|
||||||
# Asumimos que es una IP estática
|
# Assume it's an IP address (for backward compatibility)
|
||||||
ip = ip_mode
|
ip = param
|
||||||
gateway = '.'.join(ip.split('.')[:3] + ['1'])
|
|
||||||
cmd = f'netsh interface ip set address "{interface}" static {ip} 255.255.255.0 {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}'
|
||||||
|
|
||||||
|
logger.info(f"Command to execute: {cmd}")
|
||||||
success = run_command(logger, cmd)
|
success = run_command(logger, cmd)
|
||||||
|
|
||||||
if success:
|
if success:
|
||||||
logger.info("Command executed successfully")
|
logger.info("Command executed successfully")
|
||||||
return 0
|
return 0
|
||||||
|
@ -96,6 +109,7 @@ def main():
|
||||||
logger.error("Command failed")
|
logger.error("Command failed")
|
||||||
return 1
|
return 1
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
try:
|
try:
|
||||||
exit_code = main()
|
exit_code = main()
|
||||||
|
|
|
@ -1 +1 @@
|
||||||
{"last_interface": "Ethernet", "last_ip_prefix": "10.1.33"}
|
{"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}}
|
|
@ -1,192 +0,0 @@
|
||||||
import ctypes
|
|
||||||
import subprocess
|
|
||||||
import sys
|
|
||||||
import re
|
|
||||||
import os
|
|
||||||
import json
|
|
||||||
import time
|
|
||||||
from win10toast import ToastNotifier
|
|
||||||
|
|
||||||
# Definir una constante para la ruta del directorio
|
|
||||||
DIR = "D:\\Proyectos\\Scripts\\IPChanger"
|
|
||||||
IP_HISTORY_FILE = os.path.join(DIR, "ip_history.json")
|
|
||||||
|
|
||||||
|
|
||||||
def is_admin():
|
|
||||||
"""Verifica si el script se está ejecutando con privilegios de administrador."""
|
|
||||||
try:
|
|
||||||
return ctypes.windll.shell32.IsUserAnAdmin()
|
|
||||||
except:
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def run_as_admin(argv=None, debug=False):
|
|
||||||
"""Ejecuta el script como administrador."""
|
|
||||||
shell32 = ctypes.windll.shell32
|
|
||||||
if argv is None and shell32.IsUserAnAdmin():
|
|
||||||
# Ya estamos ejecutando como administrador, no es necesario hacer nada
|
|
||||||
return True
|
|
||||||
if argv is None:
|
|
||||||
argv = sys.argv
|
|
||||||
if hasattr(sys, "_MEIPASS"):
|
|
||||||
# Soporte para PyInstaller
|
|
||||||
arguments = map(str, argv[1:])
|
|
||||||
else:
|
|
||||||
arguments = map(str, argv)
|
|
||||||
argument_line = " ".join(arguments)
|
|
||||||
executable = str(sys.executable)
|
|
||||||
if debug:
|
|
||||||
print(f"Command line: {executable} {argument_line}")
|
|
||||||
ret = shell32.ShellExecuteW(None, "runas", executable, argument_line, None, 1)
|
|
||||||
if int(ret) <= 32:
|
|
||||||
return False
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def set_static_ip(ip_address, gateway):
|
|
||||||
"""Establece una dirección IP estática para el adaptador Ethernet."""
|
|
||||||
try:
|
|
||||||
subprocess.run(
|
|
||||||
f'netsh interface ip set address "Ethernet" static {ip_address} 255.255.255.0 {gateway}',
|
|
||||||
shell=True,
|
|
||||||
)
|
|
||||||
return f"Dirección IP establecida en {ip_address}"
|
|
||||||
except Exception as e:
|
|
||||||
return f"Error al establecer la dirección IP: {e}"
|
|
||||||
|
|
||||||
|
|
||||||
def set_dhcp():
|
|
||||||
"""Configura el adaptador Ethernet para obtener la dirección IP automáticamente a través de DHCP."""
|
|
||||||
try:
|
|
||||||
subprocess.run('netsh interface ip set address "Ethernet" dhcp', shell=True)
|
|
||||||
return "Adaptador Ethernet configurado para DHCP"
|
|
||||||
except Exception as e:
|
|
||||||
return f"Error al configurar DHCP: {e}"
|
|
||||||
|
|
||||||
|
|
||||||
def save_current_ip():
|
|
||||||
"""Guarda la dirección IP actual del adaptador Ethernet en un archivo."""
|
|
||||||
try:
|
|
||||||
ip_config_output = subprocess.check_output("ipconfig", shell=True).decode(
|
|
||||||
"cp850"
|
|
||||||
)
|
|
||||||
current_ip = re.search(
|
|
||||||
"Adaptador de Ethernet Ethernet:[\s\S]*?Dirección IPv4. . . . . . . . . . . . . . : (\d+\.\d+\.\d+\.\d+)",
|
|
||||||
ip_config_output,
|
|
||||||
)
|
|
||||||
if current_ip:
|
|
||||||
update_ip_history(current_ip.group(1))
|
|
||||||
return f"Dirección IP actual guardada: {current_ip.group(1)}"
|
|
||||||
else:
|
|
||||||
return "No se encontró la dirección IP actual."
|
|
||||||
except Exception as e:
|
|
||||||
return f"Error al guardar la dirección IP actual: {e}"
|
|
||||||
|
|
||||||
|
|
||||||
def update_ip_history(current_ip):
|
|
||||||
"""Actualiza el historial de las últimas 10 IPs usadas, excluyendo 'auto'."""
|
|
||||||
if current_ip.lower() == "auto":
|
|
||||||
return
|
|
||||||
|
|
||||||
if os.path.exists(IP_HISTORY_FILE):
|
|
||||||
with open(IP_HISTORY_FILE, "r") as file:
|
|
||||||
ip_history = json.load(file)
|
|
||||||
else:
|
|
||||||
ip_history = []
|
|
||||||
|
|
||||||
ip_history.insert(0, current_ip)
|
|
||||||
ip_history = ip_history[:10]
|
|
||||||
|
|
||||||
with open("ip_history.json", "w") as file:
|
|
||||||
json.dump(ip_history, file)
|
|
||||||
|
|
||||||
|
|
||||||
def restore_last_ip():
|
|
||||||
"""Restaura la última dirección IP guardada para el adaptador Ethernet."""
|
|
||||||
if os.path.exists(IP_HISTORY_FILE):
|
|
||||||
with open(IP_HISTORY_FILE, "r") as file:
|
|
||||||
ip_history = json.load(file)
|
|
||||||
if ip_history:
|
|
||||||
last_ip = ip_history[0] # Obtener la última IP del historial
|
|
||||||
gateway = last_ip.rsplit(".", 1)[0] + ".1"
|
|
||||||
return set_static_ip(last_ip, gateway)
|
|
||||||
else:
|
|
||||||
return "No hay direcciones IP guardadas en el historial."
|
|
||||||
else:
|
|
||||||
return "No se encontró el archivo de historial de IPs."
|
|
||||||
|
|
||||||
|
|
||||||
def get_input_parameter():
|
|
||||||
"""Solicita al usuario un parámetro por línea de comandos."""
|
|
||||||
return input(
|
|
||||||
"Ingrese la dirección IP, 'auto' para DHCP, o 'last' para la última IP: "
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def display_ip_history(ip_history):
|
|
||||||
"""Muestra el historial de las últimas 10 IPs y permite al usuario seleccionar una."""
|
|
||||||
if ip_history:
|
|
||||||
for i, ip in enumerate(ip_history):
|
|
||||||
print(f"{i}: {ip}")
|
|
||||||
choice = input(
|
|
||||||
"Seleccione una IP del historial (0-9), o presione Enter para continuar: "
|
|
||||||
)
|
|
||||||
if choice.isdigit() and 0 <= int(choice) < len(ip_history):
|
|
||||||
return ip_history[int(choice)]
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
if not is_admin():
|
|
||||||
# Si no se está ejecutando como administrador, solicitar elevación
|
|
||||||
result = run_as_admin()
|
|
||||||
if result is True:
|
|
||||||
print("Ejecutando como administrador.")
|
|
||||||
elif result is False:
|
|
||||||
print("No se pudo obtener privilegios de administrador.")
|
|
||||||
return
|
|
||||||
else:
|
|
||||||
# El script se reinició con privilegios de administrador
|
|
||||||
return
|
|
||||||
|
|
||||||
if os.path.exists(IP_HISTORY_FILE):
|
|
||||||
with open(IP_HISTORY_FILE, "r") as file:
|
|
||||||
ip_history = json.load(file)
|
|
||||||
|
|
||||||
argument = sys.argv[1] if len(sys.argv) > 1 else None
|
|
||||||
|
|
||||||
if not argument:
|
|
||||||
chosen_ip = display_ip_history()
|
|
||||||
if chosen_ip:
|
|
||||||
argument = chosen_ip
|
|
||||||
else:
|
|
||||||
argument = get_input_parameter()
|
|
||||||
|
|
||||||
# Guardar la dirección IP actual solo si no es 'auto'
|
|
||||||
if argument.lower() != "auto":
|
|
||||||
message = save_current_ip()
|
|
||||||
|
|
||||||
if argument == "auto":
|
|
||||||
message = set_dhcp()
|
|
||||||
elif argument == "last":
|
|
||||||
message = restore_last_ip()
|
|
||||||
else:
|
|
||||||
ip_parts = argument.split(".")
|
|
||||||
if len(ip_parts) == 3:
|
|
||||||
argument += ".249"
|
|
||||||
gateway = ".".join(ip_parts[:3]) + ".1"
|
|
||||||
message = set_static_ip(argument, gateway)
|
|
||||||
update_ip_history(argument) # Actualizar el historial solo con IPs estáticas
|
|
||||||
|
|
||||||
# Aquí asumimos que 'message' contiene el mensaje que quieres mostrar
|
|
||||||
try:
|
|
||||||
toaster = ToastNotifier()
|
|
||||||
toaster.show_toast("Cambio de IP", message, duration=10)
|
|
||||||
except Exception as e:
|
|
||||||
print(
|
|
||||||
f"Se produjo un error al mostrar la notificación, pero la operación se completó con éxito: {e}"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1 @@
|
||||||
|
{"10.1.22": "10.1.20.11"}
|
Loading…
Reference in New Issue