import re
import telnetlib
import time
from datetime import datetime
import pandas as pd
import os
import matplotlib
matplotlib.use('Agg') # Non-GUI backend
from matplotlib import pyplot as plt
import re
import pandas as pd
import os
from datetime import datetime
from matplotlib import pyplot as plt
import time
def execute_interface_brief(tn, hostname):
command = bytes("show interface brief", encoding='utf-8')
tn.write(command + b'\r\n')
result_list = []
# Continuously read the command result, handle "--More--" pagination
while True:
command_result = tn.read_very_eager().decode('ascii')
result_list.append(command_result)
if re.findall(r"--More--", command_result.strip()):
tn.write(b" ")
elif re.findall(r"#", command_result.strip()):
break
else:
time.sleep(1)
continue
result_str = "\n".join(result_list)
list_str = result_str.split('\n') # Split the result into lines
list_interface_data = []
columns = []
# Debugging: Print out the entire Telnet output to check if we are getting the right data
print("Raw Telnet Output:\n", result_str)
# Iterate over the result lines and extract the relevant information
for line in list_str:
# Identify the column headers
if "Interface" in line:
columns = re.split(r'\s+', line.strip()) # Split headers by spaces
print("Extracted Columns:", columns) # Debugging
columns = columns[:20] # Keep only the first 8 columns
# Match interface data lines using regex
regex = re.compile(r'\w+gei.+\s+.+\s+.+\s+.+\s+.+\s+.+\s+', re.S)
match = regex.findall(line)
if match:
interface_data = re.split(r'\s+', match[0]) # Split interface data by spaces
list_interface_data.append(interface_data)
# Check if any data was extracted, handle case where nothing is found
if not list_interface_data:
print(f"No valid interface data found for {hostname}.")
return None
# Create a DataFrame with the extracted data
pd_result = pd.DataFrame(list_interface_data, columns=columns)
# Save the DataFrame to a CSV file
output_filename = f'interface_brief-{hostname}-{datetime.now().strftime("%Y%m%d-%H%M%S")}.csv'
pd_result.to_csv(output_filename, encoding='utf-8', index=False)
print(f"Interface brief result saved to {output_filename}")
# Visualization
visualize_interface_brief(pd_result)
return pd_result
def visualize_interface_brief(df):
"""
Function to visualize interface statuses, bandwidth, and other relevant metrics.
"""
# Map 'up' to 1 and 'down' to 0 for Admin and Phy statuses
df['Admin_status'] = df['Admin'].apply(lambda x: 1 if x.lower() == 'up' else 0)
df['Phy_status'] = df['Phy'].apply(lambda x: 1 if x.lower() == 'up' else 0)
# Set up the figure for plotting
fig, axes = plt.subplots(2, 1, figsize=(10, 8))
# Plot Admin status (up = 1, down = 0)
axes[0].bar(df['Interface'], df['Admin_status'], color='skyblue', edgecolor='black')
axes[0].set_title('Admin Status (up = 1, down = 0)')
axes[0].set_xlabel('Interface')
axes[0].set_ylabel('Status')
axes[0].set_xticklabels(df['Interface'], rotation=90)
axes[0].grid(True, linestyle='--', alpha=0.7)
# Plot Phy status (up = 1, down = 0)
axes[1].bar(df['Interface'], df['Phy_status'], color='lightgreen', edgecolor='black')
axes[1].set_title('Physical Status (up = 1, down = 0)')
axes[1].set_xlabel('Interface')
axes[1].set_ylabel('Status')
axes[1].set_xticklabels(df['Interface'], rotation=90)
axes[1].grid(True, linestyle='--', alpha=0.7)
# Adjust layout
plt.tight_layout()
# Show the plots
plt.savefig('plot5555.png')
def connect_telnet(hostname, username, password):
try:
tn = telnetlib.Telnet()
tn.open(hostname, port=23, timeout=5) # 尝试连接 Telnet
print("connected......", hostname)
# 输入用户名
tn.read_until(b'Username:', timeout=5)
tn.write(username.encode('ascii') + b'\n')
# 输入密码
tn.read_until(b'Password:', timeout=5)
tn.write(password.encode('ascii') + b'\n')
# 检查是否成功登录
login_result = tn.read_until(b'#', timeout=5)
if b'#' not in login_result:
print('登录失败!', hostname)
tn.close() # 登录失败,关闭连接
return None
else:
print('登录成功!', hostname)
return tn # 登录成功,返回 Telnet 对象
except Exception as e:
print(f"连接失败: {e}")
return None # 连接失败,返回 None
if __name__ == '__main__':
hostname = '129.201.0.1' # Example hostname
username = 'zte'
password = 'zte'
# Connect to the device
tn = connect_telnet(hostname, username, password)
if tn:
# Execute the interface brief command, save the result, and visualize
df_result = execute_interface_brief(tn, hostname)
tn.close() # Close the Telnet connection