121 lines
3.6 KiB
Python
121 lines
3.6 KiB
Python
import sys
|
|
import subprocess
|
|
import ctypes
|
|
import logging
|
|
import os
|
|
from datetime import datetime
|
|
|
|
|
|
def setup_logging():
|
|
"""Configura el logging para el script"""
|
|
log_dir = os.path.join(os.path.dirname(__file__), "logs")
|
|
if not os.path.exists(log_dir):
|
|
os.makedirs(log_dir)
|
|
|
|
log_file = os.path.join(log_dir, "ip_changer_admin.log")
|
|
|
|
logging.basicConfig(
|
|
level=logging.DEBUG,
|
|
format="%(asctime)s - %(levelname)s - %(message)s",
|
|
handlers=[logging.FileHandler(log_file), logging.StreamHandler(sys.stdout)],
|
|
)
|
|
return logging.getLogger(__name__)
|
|
|
|
|
|
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_command(logger, cmd: str) -> bool:
|
|
"""Ejecuta un comando y retorna True si fue exitoso"""
|
|
logger.info(f"Executing command: {cmd}")
|
|
try:
|
|
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
|
|
|
|
if result.stdout:
|
|
logger.info(f"Command output: {result.stdout}")
|
|
if 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
|
|
|
|
except Exception as e:
|
|
logger.error(f"Error executing command: {str(e)}")
|
|
return False
|
|
|
|
|
|
def main():
|
|
logger = setup_logging()
|
|
|
|
# Log startup information
|
|
logger.info("=" * 50)
|
|
logger.info(f"Script started at {datetime.now()}")
|
|
logger.info(f"Arguments received: {sys.argv}")
|
|
logger.info(f"Running with admin privileges: {is_admin()}")
|
|
|
|
if not is_admin():
|
|
logger.error("This script requires administrator privileges")
|
|
return 1
|
|
|
|
if len(sys.argv) < 3:
|
|
logger.error("Insufficient arguments")
|
|
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")
|
|
logger.info(
|
|
'Example for command: ip_changer_admin.py Ethernet "netsh interface ip set address..."'
|
|
)
|
|
return 1
|
|
|
|
interface = sys.argv[1]
|
|
param = sys.argv[2]
|
|
|
|
logger.info(f"Processing request for interface: {interface}")
|
|
logger.info(f"Parameter: {param}")
|
|
|
|
# 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'
|
|
else:
|
|
# Assume it's an IP address (for backward compatibility)
|
|
ip = param
|
|
|
|
# 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)
|
|
|
|
if success:
|
|
logger.info("Command executed successfully")
|
|
return 0
|
|
else:
|
|
logger.error("Command failed")
|
|
return 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
exit_code = main()
|
|
sys.exit(exit_code)
|
|
except Exception as e:
|
|
logger = setup_logging()
|
|
logger.exception("Unhandled exception occurred")
|
|
sys.exit(1)
|