用python統計交換機有多少端口UP
用python統計交換機有多少端口UP,可以間接的反饋有多少個用戶在線。我們使用上次的腳本將可達的網絡設備ip統計到reachable_ip.txt中,這次我們使用reachable_ip.txt來登陸設備來統計多少端口是UP的
云配置
拓撲
交換機配置SSH
aaalocal-user admin password cipher Huawei@123 //創建python用戶,密碼為123local-user admin privilege level 15local-user admin service-type ssh
#
user-interface vty 0 4authentication-mode aaaprotocol 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() # 創建交互式 shellcommand.send(b'screen-length 0 temporary\n') # 發送命令,設置命令行分頁為0command.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@123You have successfully connected to 192.168.56.2Info: The max number of VTY users is 5, and the numberof 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.3Info: The max number of VTY users is 5, and the numberof 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.4Info: The max number of VTY users is 5, and the numberof 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.5Info: The max number of VTY users is 5, and the numberof 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
執行完后,會生成一個以日期為命名的文本文檔