Skip to content

Instantly share code, notes, and snippets.

@jamesy0ung
Last active September 22, 2024 06:20
Show Gist options
  • Save jamesy0ung/8c1d105100d79507b9a6876014c2d332 to your computer and use it in GitHub Desktop.
Save jamesy0ung/8c1d105100d79507b9a6876014c2d332 to your computer and use it in GitHub Desktop.
import serial
import time
import logging
import sys
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(sys.stdout),
logging.FileHandler('switch_config.log')
])
class HPSwitch:
def __init__(self, port, baudrate=38400, timeout=1):
self.ser = serial.Serial(port, baudrate, timeout=timeout)
self.clear_buffer()
def clear_buffer(self):
self.ser.reset_input_buffer()
self.ser.reset_output_buffer()
def read_until(self, expected, timeout=30):
start_time = time.time()
buffer = ""
while time.time() - start_time < timeout:
data = self.ser.read(1).decode('utf-8', errors='ignore')
if data:
buffer += data
logging.debug(f"Buffer: {buffer}")
if expected in buffer:
return buffer
else:
time.sleep(0.1)
raise TimeoutError(f"Timeout waiting for '{expected}'. Last received: {buffer}")
def send_command(self, command, wait_for=None, timeout=5):
self.clear_buffer()
self.ser.write(f"{command}\n".encode())
logging.debug(f"Sent: {command}")
if wait_for:
return self.read_until(wait_for, timeout)
time.sleep(0.5)
def initialize_connection(self):
logging.info("Initializing connection...")
self.clear_buffer()
self.ser.write(b"\n")
time.sleep(1)
initial_output = self.ser.read(self.ser.in_waiting).decode('utf-8', errors='ignore')
logging.debug(f"Initial output: {initial_output}")
if "Press ENTER to get started" in initial_output:
self.send_command("", wait_for="Username:")
elif "Username:" in initial_output:
pass # Already at username prompt
else:
# Try to reach a known state
for _ in range(3):
self.send_command("\n", wait_for="Username:", timeout=5)
if "Username:" in self.ser.read(self.ser.in_waiting).decode('utf-8', errors='ignore'):
break
else:
raise Exception("Unable to reach login prompt")
def login(self):
self.initialize_connection()
self.send_command("admin", wait_for="Password:")
response = self.send_command("", wait_for="<HP V1910 Switch>", timeout=10)
if "<HP V1910 Switch>" not in response:
raise Exception("Login failed")
logging.info("Login successful")
def configure_switch(self):
logging.info("Entering command line mode...")
self.send_command("_cmdline-mode on")
self.send_command("y")
self.send_command("512900")
self.send_command("system-view")
logging.info("Configuring ports...")
for port in range(1, 28):
self.send_command(f"interface GigabitEthernet1/0/{port}")
self.send_command("port link-type trunk")
self.send_command("port trunk permit vlan 100 110 120 180")
self.send_command("quit")
logging.info("All ports configured. Saving configuration...")
self.send_command("save")
self.send_command("y")
self.send_command("") # Send Enter for confirmation
self.send_command("y")
logging.info("Configuration saved.")
def close(self):
self.ser.close()
def configure_switch(com_port):
switch = HPSwitch(com_port)
try:
switch.login()
switch.configure_switch()
logging.info("Switch configuration completed successfully")
except Exception as e:
logging.error(f"An error occurred: {str(e)}")
finally:
switch.close()
if __name__ == "__main__":
com_port = 'COM14' # Replace with your actual COM port
configure_switch(com_port)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment