用python 网络自动化统计交换机有多少端口UP

用python统计交换机有多少端口UP

用python统计交换机有多少端口UP,可以间接的反馈有多少个用户在线。我们使用上次的脚本将可达的网络设备ip统计到reachable_ip.txt中,这次我们使用reachable_ip.txt来登陆设备来统计多少端口是UP的

云配置

用python 网络自动化统计交换机有多少端口UP_第1张图片

拓扑

用python 网络自动化统计交换机有多少端口UP_第2张图片

交换机配置SSH

aaa
 local-user admin password cipher Huawei@123   //创建python用户,密码为123
 local-user admin privilege level 15
 local-user admin service-type ssh
#
user-interface vty 0 4
 authentication-mode aaa
 protocol inbound ssh
#
stelnet server enable
ssh user admin authentication-type all
ssh user admin service-type all
ssh client first-time enable

这个时候我们就能与交换机互访,并SSH登陆了

目的

用python统计交换机有多少端口UP,可以间接的反馈有多少个用户在线。

代码

使用以下代码统计出有多少IP是可达的,他会统计后写入到一个文本文件中,也可以自己手动写或者写个循环

import  pythonping  # 导入 pythonping 库,用于执行 ping 操作
import os  # 导入 os 库,用于操作文件和系统功能

# 如果名为 'reachable_ip.txt' 的文件存在,删除它
if os.path.exists('reachable_ip.txt'):
    os.remove('reachable_ip.txt')

ip_list = range(2, 6)  # 创建一个IP列表

# 遍历IP列表
for ip in ip_list:
    ip = '192.168.56.' + str(ip)  # 构建IP地址
    ping_result = pythonping.ping(ip)  # 执行ping操作
    f = open('reachable_ip.txt', 'a')  # 打开 'reachable_ip.txt' 文件,以追加模式写入
    if 'Reply' in str(ping_result):  # 检查ping结果中是否包含 'Reply'
        print(ip + ' is reachable.')  # 如果包含 'Reply',打印IP地址是可达的
        f.write(ip + "\n")  # 将可达的IP地址写入 'reachable_ip.txt' 文件中
    else:
        print(ip + ' is not reachable.')  # 如果不包含 'Reply',打印IP地址是不可达的
    f.close()  # 关闭文件

192.168.56.2 is reachable.
192.168.56.3 is reachable.
192.168.56.4 is reachable.
192.168.56.5 is reachable.

Process finished with exit code 0


#检测到这些IP是可达的,我们接下来用另外一个脚本去登陆上去进行统计

正式统计交换机端口UP的数量的代码

import paramiko  # 导入 paramiko 库,用于 SSH 连接
import time  # 导入 time 库,用于添加延迟等待
import re  # 导入 re 库,用于正则表达式操作
import datetime  # 导入 datetime 库,用于处理日期和时间
import socket  # 导入 socket 库,用于网络通信

# 获取用户名和密码
username = input("Username: ")  # 输入用户名
password = input("Password: ")  # 输入密码

# 获取当前日期和时间
now = datetime.datetime.now()
date = "%s-%s-%s" % (now.month, now.day, now.year)  # 获取当前日期
time_now = "%s-%s-%s" % (now.hour, now.minute, now.second)  # 获取当前时间

switch_with_tacacs_issue = []  # 存储 TACACS 认证失败的交换机列表
switch_not_reachable = []  # 存储不可达的交换机列表
total_number_of_up_port = 0  # 统计所有已连接的端口数量

# 读取可访问的 IP 地址列表文件
with open('reachable_ip.txt') as iplist:
    number_of_switch = len(iplist.readlines())  # 计算交换机数量
    total_number_of_ports = number_of_switch * 24  # 计算总端口数量(每台交换机有24个端口)
    iplist.seek(0)  # 重置文件指针到文件开头

    for line in iplist.readlines():  # 逐行读取 IP 地址列表
        try:
            ip = line.strip()  # 去除行末尾的换行符,得到IP地址字符串

            ssh_client = paramiko.SSHClient()  # 创建 SSHClient 对象
            ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())  # 设置自动添加主机密钥
            ssh_client.connect(hostname=ip, username=username, password=password)  # SSH 连接到交换机
            print("\nYou have successfully connected to ", ip)  # 打印成功连接的消息

            command = ssh_client.invoke_shell()  # 创建交互式 shell
            command.send(b'screen-length 0 temporary\n')  # 发送命令,设置命令行分页为0
            command.send(b'display  interface  brief  | include  up\n')  # 发送命令,显示已启用的端口
            time.sleep(1)  # 等待1秒,确保命令执行完毕

            output = command.recv(65535)  # 接收命令输出
            print(output.decode("ascii"))  # 打印交换机输出

            search_up_port = re.findall(r'GigabitEthernet', output.decode("utf-8"))  # 用正则表达式匹配已启用的端口
            number_of_up_port = len(search_up_port)  # 计算已连接端口数量
            print(ip + " has " + str(number_of_up_port) + " ports up.")  # 打印已连接端口数量信息
            total_number_of_up_port += number_of_up_port  # 更新总的已连接端口数量

        except paramiko.ssh_exception.AuthenticationException:  # 处理认证异常
            print("TACACS is not working for " + ip + ".")  # 打印 TACACS 认证失败消息
            switch_with_tacacs_issue.append(ip)  # 将无法通过 TACACS 认证的交换机加入列表

        except socket.error:  # 处理网络异常
            print(ip + " is not reachable.")  # 打印不可达消息
            switch_not_reachable.append(ip)  # 将不可达的交换机加入列表

    iplist.close()  # 关闭 IP 地址列表文件

    # 输出统计信息
    print("\n")
    print("There are totally " + str(total_number_of_ports) + " ports available in the network.")
    print(str(total_number_of_up_port) + " ports are currently up.")
    print("port up rate is %.2f%%" % (total_number_of_up_port / float(total_number_of_ports) * 100))
    print('\nTACACS is not working for below switches: ')
    for i in switch_with_tacacs_issue:
        print(i)
    print('\nBelow switches are not reachable: ')
    for i in switch_not_reachable:
        print(i)

    # 将结果写入文件
    f = open(date + ".txt", "a+")
    f.write('AS of ' + date + " " + time_now)
    f.write("\n\nThere are totally " + str(total_number_of_ports) + " ports available in the network.")
    f.write("\n" + str(total_number_of_up_port) + " ports are currently up.")
    f.write("\nport up rate is %.2f%%" % (total_number_of_up_port / float(total_number_of_ports) * 100))
    f.write("\n***************************************************************\n\n")
    f.close()  # 关闭文件

结果

Username: admin
Password: Huawei@123

You have successfully connected to  192.168.56.2

Info: The max number of VTY users is 5, and the number
      of current VTY users on line is 1.
      The current login time is 2023-12-09 23:08:19.
<Huawei>screen-length 0 temporary
Info: The configuration takes effect on the current user terminal interface only.
<Huawei>display  interface  brief  | include  up
PHY: Physical
*down: administratively down
(l): loopback
(s): spoofing
(b): BFD down
(e): ETHOAM down
(dl): DLDP down
(d): Dampening Suppressed
InUti/OutUti: input utility/output utility
Interface                   PHY   Protocol InUti OutUti   inErrors  outErrors
GigabitEthernet0/0/1        up    up          0%     0%          0          0
GigabitEthernet0/0/2        up    up          0%     0%          0          0
GigabitEthernet0/0/3        up    up          0%     0%          0          0
NULL0                       up    up(s)       0%     0%          0          0
Vlanif1                     up    up          --     --          0          0
<Huawei>
192.168.56.2 has 3 ports up.

You have successfully connected to  192.168.56.3

Info: The max number of VTY users is 5, and the number
      of current VTY users on line is 1.
      The current login time is 2023-12-09 23:08:21.
<Huawei>screen-length 0 temporary
Info: The configuration takes effect on the current user terminal interface only.
<Huawei>display  interface  brief  | include  up
PHY: Physical
*down: administratively down
(l): loopback
(s): spoofing
(b): BFD down
(e): ETHOAM down
(dl): DLDP down
(d): Dampening Suppressed
InUti/OutUti: input utility/output utility
Interface                   PHY   Protocol InUti OutUti   inErrors  outErrors
GigabitEthernet0/0/1        up    up          0%     0%          0          0
GigabitEthernet0/0/2        up    up          0%     0%          0          0
GigabitEthernet0/0/3        up    up          0%     0%          0          0
GigabitEthernet0/0/4        up    up          0%     0%          0          0
NULL0                       up    up(s)       0%     0%          0          0
Vlanif1                     up    up          --     --          0          0
<Huawei>
192.168.56.3 has 4 ports up.

You have successfully connected to  192.168.56.4

Info: The max number of VTY users is 5, and the number
      of current VTY users on line is 1.
      The current login time is 2023-12-09 23:08:23.
<Huawei>screen-length 0 temporary
Info: The configuration takes effect on the current user terminal interface only.
<Huawei>display  interface  brief  | include  up
PHY: Physical
*down: administratively down
(l): loopback
(s): spoofing
(b): BFD down
(e): ETHOAM down
(dl): DLDP down
(d): Dampening Suppressed
InUti/OutUti: input utility/output utility
Interface                   PHY   Protocol InUti OutUti   inErrors  outErrors
GigabitEthernet0/0/1        up    up          0%     0%          0          0
GigabitEthernet0/0/2        up    up          0%     0%          0          0
NULL0                       up    up(s)       0%     0%          0          0
Vlanif1                     up    up          --     --          0          0
<Huawei>
192.168.56.4 has 2 ports up.

You have successfully connected to  192.168.56.5

Info: The max number of VTY users is 5, and the number
      of current VTY users on line is 1.
      The current login time is 2023-12-09 23:08:25.
<Huawei>screen-length 0 temporary
Info: The configuration takes effect on the current user terminal interface only.
<Huawei>display  interface  brief  | include  up
PHY: Physical
*down: administratively down
(l): loopback
(s): spoofing
(b): BFD down
(e): ETHOAM down
(dl): DLDP down
(d): Dampening Suppressed
InUti/OutUti: input utility/output utility
Interface                   PHY   Protocol InUti OutUti   inErrors  outErrors
GigabitEthernet0/0/1        up    up          0%     0%          0          0
GigabitEthernet0/0/2        up    up          0%     0%          0          0
GigabitEthernet0/0/3        up    up          0%     0%          0          0
GigabitEthernet0/0/4        up    up          0%     0%          0          0
GigabitEthernet0/0/5        up    up          0%     0%          0          0
NULL0                       up    up(s)       0%     0%          0          0
Vlanif1                     up    up          --     --          0          0
<Huawei>
192.168.56.5 has 5 ports up.


There are totally 96 ports available in the network.
14 ports are currently up.
port up rate is 14.58%

TACACS is not working for below switches: 

Below switches are not reachable: 

Process finished with exit code 0

执行完后,会生成一个以日期为命名的文本文档

用python 网络自动化统计交换机有多少端口UP_第3张图片

你可能感兴趣的:(网工的python之路,网络,自动化,python)