用python 網絡自動化統計交換機有多少端口UP

用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

執行完后,會生成一個以日期為命名的文本文檔

請添加圖片描述

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/211792.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/211792.shtml
英文地址,請注明出處:http://en.pswp.cn/news/211792.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

使用fcl庫做碰撞檢測

fcl庫是真難用&#xff0c;導入自己的項目的時候遇到各種坑。 第一個坑就是git clone并build fcl庫后生成的fcl-config.cmake里面有問題&#xff0c;需要在這里進行相應修改 set_and_check(FCL_INCLUDE_DIRS "/home/xxxx/fcl/build/include") set(FCL_LIBRARIES fc…

【Cisco Packet Tracer】VLAN通信 多臂/單臂路由/三層交換機

在進行本文的實驗之前&#xff0c;請確保掌握以下內容&#xff1a; 【Cisco Packet Tracer】交換機 學習/更新/泛洪/VLAN實驗 【Cisco Packet Tracer】路由器實驗 靜態路由/RIP/OSPF/BGP 【Cisco Packet Tracer】路由器 NAT實驗 本文介紹VLAN間的通信方法&#xff0c; 包括…

FreeRTOS的任務優先級、Tick以及狀態講解(尊敬的嵌入式工程師,不妨進來喝杯茶)

任務優先級和Tick 在FreeRTOS中&#xff0c;任務的優先級和Tick是兩個關鍵的概念&#xff0c;它們直接影響任務的調度和執行。 任務優先級 每個任務都被分配一個優先級&#xff0c;用于決定任務在系統中的調度順序。 優先級是一個無符號整數&#xff0c;通常從0開始&#xff0…

Mysql- 流程函數-(If, CASE WHEN)的使用及練習

目錄 4.1 If函數語法格式 4.2 CASE WHEN 條件表達式格式 4.3 update與 case when 4.4 練習題1 4.5 練習題2 4.6 練習題3-行轉列 4.7 牛客練習題 4.8 LeetCode練習題 4.1 If函數語法格式 IF(expr1,expr2,expr3) 解釋&#xff1a; 如果表達式expr1true(expr1 <>…

力扣第 119 場雙周賽(Java)

文章目錄 T1 找到兩個數組中的公共元素代碼解釋 T2 消除相鄰近似相等字符代碼解釋 T3 最多 K 個重復元素的最長子數組代碼解釋 T4 關閉分部的可行集合數目代碼解釋 鏈接&#xff1a;第 119 場雙周賽 - 力扣&#xff08;LeetCode&#xff09; T1 找到兩個數組中的公共元素 給你…

Xcode doesn’t support iOS 16.6

xocde版本低&#xff0c;手動放入16.6的依賴文件 https://gitee.com/qiu1993/iOSDeviceSupport/blob/master/iOS16/16.6.zip 路徑 /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport

JAVA全棧開發 day21_JDBC與反射結合、設計模式

一、總結 一階段 day01 java 發展&#xff0c;java 環境( path, java_home, class_path)&#xff0c;java 原理&#xff0c; java 執行 &#xff0c; jvm , jre , jdk day02 變量 標識符命名規則 數據類型 數據類型的轉換 運算符 day03 選擇結構 if , switch day04 循環結…

分割回文串

分割回文串 描述 : 給你一個字符串 s&#xff0c;請你將 s 分割成一些子串&#xff0c;使每個子串都是 回文串 。返回 s 所有可能的分割方案。 回文串 是正著讀和反著讀都一樣的字符串。 題目 : LeetCode 131.分割回文串 : 131. 分割回文串 分析 : 字符串如何判斷回文本…

20 Redis進階 - 運維監控

1、理解Redis監控 Redis運維和監控的意義不言而喻&#xff0c;可以以下三個方面入手 1.首先是Redis自身提供了哪些狀態信息&#xff0c;以及有哪些常見的命令可以獲取Redis的監控信息; 2.一些常見的UI工具可以可視化的監控Redis; 3.理解Redis的監控體系;2、Redis自身狀態及命…

Vue3-02-ref() 響應式詳解

ref() 是什么 ref() 是一個函數&#xff1b; ref() 函數用來聲明響應式的狀態&#xff08;就是來聲明變量的&#xff09; ref() 函數聲明的變量&#xff0c;是響應式的&#xff0c;變量的值改變之后&#xff0c;頁面中會自動重新渲染。ref() 有什么特點 1.ref() 可以聲明基礎…

VUE語法--toRefs與toRef用法

1、功能概述 ref和reactive能夠定義響應式的數據&#xff0c;當我們通過reactive定義了一個對象或者數組數據的時候&#xff0c;如果我們只希望這個對象或者數組中指定的數據響應&#xff0c;其他的不響應。這個時候我們就可以使用toRefs和toRef實現局部數據的響應。 toRefs是…

算一算并輸出2到正整數n中每個數的質因子(for循環)

計算并輸出2到正整數n之間每個數的質因子&#xff0c;并以乘法形式輸出。 輸入格式: 輸入只有1個正整數即n。 輸出格式: 把2到正整數n間的每一個數分解成它的質因子&#xff0c;并以乘法的形式輸出。例如&#xff0c;輸入的正整數n值為10&#xff0c;則應輸出如下&#xff…

MIT線性代數筆記-第28講-正定矩陣,最小值

目錄 28.正定矩陣&#xff0c;最小值打賞 28.正定矩陣&#xff0c;最小值 首先正定矩陣是一個實對稱矩陣 由第 26 26 26講的末尾可知正定矩陣有以下四種判定條件&#xff1a; 所有特征值都為正左上角所有 k k k階子矩陣行列式都為正&#xff08; 1 ≤ k ≤ n 1 \le k \le n …

DDD系列 - 第6講 倉庫Repository及Mybatis、JPA的取舍(一)

目錄 一、領域層定義倉庫接口1.1 設計聚合1.2 定義倉庫Repository接口二 、基礎設施層實現倉庫接口2.1 設計數據庫2.2 集成Mybatis2.3 引入Convetor2.4 實現倉庫三、回顧一、領域層定義倉庫接口 書接上回,之前通過一個關于拆解、微服務、面向對象的故事,向大家介紹了如何從微…

簡單的WEB服務器

優質博文&#xff1a;IT-BLOG-CN 目的&#xff1a; 了解Java Web服務器是如何運行的。Web服務器使用HTTP與其客戶端&#xff0c;也就是Web瀏覽器進行通信。基于Java的Web服務器會使用兩個重要類&#xff1a;java.net.Socket類和java.net.ServerSocket類&#xff0c;并通過發送…

詳解Keras3.0 Models API: Model class

1、語法 keras.Model() 將不同層組為具有訓練/推理特征的對象的模型 2、示例一 inputs keras.Input(shape(37,)) x keras.layers.Dense(32, activation"relu")(inputs) outputs keras.layers.Dense(5, activation"softmax")(x) model keras.Model…

58.Nacos源碼分析2

三、服務心跳。 3.服務心跳 Nacos的實例分為臨時實例和永久實例兩種&#xff0c;可以通過在yaml 文件配置&#xff1a; spring:application:name: order-servicecloud:nacos:discovery:ephemeral: false # 設置實例為永久實例。true&#xff1a;臨時; false&#xff1a;永久ser…

MySQL-備份+日志:介質故障與數據庫恢復

目錄 第1關&#xff1a;備份與恢復 第2關&#xff1a;備份日志&#xff1a;介質故障的發生與數據庫的恢復 第1關&#xff1a;備份與恢復 任務描述 本關任務: 備份數據庫&#xff0c;然后再恢復它。 test1_1.sh # 你寫的命令將在linux的命令行運行 # 對數據庫residents作海…

【C/C++筆試練習】多態的概念、虛函數的概念、虛表地址、派生類的虛函數、虛函數的訪問、指針引用、動態多態、完全數計算、撲克牌大小

文章目錄 C/C筆試練習選擇部分&#xff08;1&#xff09;多態的概念&#xff08;2&#xff09;虛函數的概念&#xff08;3&#xff09;虛表地址&#xff08;4&#xff09;派生類的虛函數&#xff08;5&#xff09;虛函數的訪問&#xff08;6&#xff09;分析程序&#xff08;7&…

C# WPF上位機開發(會員管理軟件)

【 聲明&#xff1a;版權所有&#xff0c;歡迎轉載&#xff0c;請勿用于商業用途。 聯系信箱&#xff1a;feixiaoxing 163.com】 好多同學都認為上位機只是純軟件開發&#xff0c;不涉及到硬件設備&#xff0c;比如聽聽音樂、看看電影、寫寫小的應用等等。如果是消費電子&#…