自動化運維實驗

目錄

一、實驗拓撲

二、實驗目的

三、實驗步驟

實驗思路:

代碼部分:

四、實驗結果:


一、實驗拓撲

二、實驗目的

利用python腳本,在本地,或者虛擬機里實現,設備CRC數量統計,并輸出成表格

三、實驗步驟

實驗開始之前先搭好環境,測試無誤再開始

實驗思路:

利用ip.txt,存放需要檢查的設備IP

再一臺一臺登錄,匹配并記錄接口名,和CRC數量,最終再輸出保存

代碼部分:

#!/usr/bin/env python3# -*- coding: utf-8 -*-import argparseimport osimport reimport timeimport socketimport getpassimport paramikoimport pandas as pdfrom paramiko import SSHException, AuthenticationExceptionDEFAULT_IP_FILE = 'ip.txt'DEFAULT_OUTPUT = 'crc_results.xlsx'DEFAULT_COMMAND = 'dis interface'DEFAULT_CONNECT_TIMEOUT = 5DEFAULT_CMD_TIMEOUT = 30MORE_PROMPTS = [b'--More--', b'---- More ----', b'--More--', b'More:', b'== More ==', b'--More--', b'\x1b\[K--More--']def read_ip_list(path):ips = []if not os.path.exists(path):print(f"[!] IP file not found: {path}")return ipswith open(path, 'r', encoding='utf-8') as f:for raw in f:line = raw.strip()if not line:continueif line.startswith('#'):continueparts = re.split(r'[\s,]+', line)if parts and parts[0]:ips.append(parts[0])return ipsdef recv_with_paging(shell, timeout=DEFAULT_CMD_TIMEOUT):"""從交互 shell 中讀取輸出,自動處理分頁(遇到 --More-- 等發送空格繼續)。返回解碼后的文本。"""buf = b''start = time.time()last_recv = time.time()shell.settimeout(1.0)while True:try:if shell.recv_ready():chunk = shell.recv(65536)if not chunk:breakbuf += chunklast_recv = time.time()# 檢查是否包含常見分頁提示(原始字節)for mp in MORE_PROMPTS:if mp in chunk:try:shell.send(' ')except Exception:pass# 也處理常見 ASCII 控制字符后跟 More 文本(部分設備會帶 escape)# 繼續循環讀取else:time.sleep(0.1)except socket.timeout:# no data right nowpassexcept Exception:# 其他異常則跳出breakif (time.time() - start) > timeout:break# 當已有數據并且很久沒讀到新數據,認為輸出結束if buf and (time.time() - last_recv) > 1.2:breaktry:return buf.decode(errors='ignore')except:return buf.decode('utf-8', 'ignore')def run_command_interactive(client, command, cmd_timeout=DEFAULT_CMD_TIMEOUT):shell = client.invoke_shell()time.sleep(0.2)# 嘗試關閉分頁# 兼容多廠商:terminal length 0, screen-length disable, page-off 等try:shell.send('terminal length 0\n')time.sleep(0.15)shell.send('screen-length 0 temporary\n')time.sleep(0.15)shell.send('page off\n')time.sleep(0.15)except Exception:pass# 清空 bannertry:if shell.recv_ready():_ = shell.recv(65536)except Exception:pass# 發送命令并讀取,自動處理分頁try:shell.send(command + '\n')except Exception:passoutput = recv_with_paging(shell, timeout=cmd_timeout)try:shell.close()except Exception:passreturn outputdef split_interface_blocks(output):"""更嚴格的 H3C 專用分割:- 識別常見 H3C 前綴:GigabitEthernet, Ethernet, Ten-GigabitEthernet, Eth-Trunk,Vlan-interface / Vlanif, Loopback, FortyGigabitEthernet 等。- 要求接口名包含數字,避免把 'Flow-control' 等字段當接口頭。返回列表 (iface_name, block_text)"""lines = output.splitlines()blocks = []cur_iface = Nonecur_lines = []# 列出常見的接口前綴(可按需擴展)iface_prefixes = [r'GigabitEthernet', r'GigEth', r'Ten-GigabitEthernet', r'FortyGigabitEthernet',r'Ethernet', r'Eth-Trunk', r'Vlan-interface', r'Vlanif', r'Loopback', r'VEth', r'Veth']prefix_pat = r'(' + '|'.join(iface_prefixes) + r')'# 可能的 header 樣式:# "GigabitEthernet1/0/1 current state : UP"# "Interface: GigabitEthernet1/0/1"# "GigabitEthernet1/0/1 is down"p1 = re.compile(r'^\s*(?:Interface[:\s]+)?' + prefix_pat + r'([A-Za-z0-9\/\-\._]*\d+)\b', re.IGNORECASE)# 另一種:全名連續(例如 "GigabitEthernet1/0/1 current state : UP")p2 = re.compile(r'^\s*' + prefix_pat + r'([A-Za-z0-9\/\-\._]*\d+)\b.*(?:current state|is up|is down|UP|DOWN|administratively down)', re.IGNORECASE)for ln in lines:ln_str = ln.rstrip('\r\n')m = Nonefor p in (p1, p2):mm = p.match(ln_str)if mm:# 名字由 mm.group(1)+group(2) 或 mm.group(1)+group(2) 組成,取匹配到的完整接口名# 某些 pattern 捕獲了兩部分(前綴和后綴),拼接起來groups = [g for g in mm.groups() if g]name = ''.join(groups).strip()# 最終再確認包含數字if not re.search(r'\d', name):continuem = namebreakif m:name = m.rstrip(',:')if cur_iface is not None:blocks.append((cur_iface, '\n'.join(cur_lines)))cur_iface = namecur_lines = [ln_str]else:if cur_iface is not None:cur_lines.append(ln_str)else:cur_lines.append(ln_str)if cur_iface is not None:blocks.append((cur_iface, '\n'.join(cur_lines)))else:blocks = [('Unknown', '\n'.join(cur_lines).strip())] if cur_lines else [('Unknown', output.strip())]return blocksdef extract_crc_from_block(block_text):"""多種方式提取 CRC 數字:- '4 input errors, 2 CRC, 0 frame' -> 2- 'CRC: 2' or 'CRC 2' or '2 CRC' -> 2- 'input errors: 2, CRC: 2' etc.返回整數(若能解析)或 None。"""# 常見組合patterns = [re.compile(r'(\d+)\s+input errors.*?(\d+)\s+CRC', re.IGNORECASE | re.DOTALL),re.compile(r'input errors[:\s]*\d+[,;\s]*CRC[:\s]*(\d+)', re.IGNORECASE),re.compile(r'CRC[:\s]+(\d+)', re.IGNORECASE),re.compile(r'\b(\d+)\s+CRC\b', re.IGNORECASE),re.compile(r'CRC errors[:\s]*(\d+)', re.IGNORECASE),re.compile(r'CRC\s+(\d+)', re.IGNORECASE)]for rg in patterns:m = rg.search(block_text)if m:# 找最后一組數字(某些 pattern 有兩個捕獲組)for g in reversed(m.groups()):if g and g.isdigit():try:return int(g)except:pass# 如果找不到數字,但出現單詞 CRC,則標記為 Unknown (存在 CRC 詞但無數字)if re.search(r'\bCRC\b', block_text, re.IGNORECASE):return None? # Unknown count but CRC mentioned# 否則認為沒有 CRC(記錄為 0)return 0def check_one_device(ip, username, password, command, connect_timeout, cmd_timeout):client = paramiko.SSHClient()client.set_missing_host_key_policy(paramiko.AutoAddPolicy())try:client.connect(hostname=ip,username=username,password=password,timeout=connect_timeout,banner_timeout=connect_timeout,auth_timeout=connect_timeout)except AuthenticationException as e:return False, f'Authentication failed: {e}'except socket.timeout:return False, 'Connection timed out'except SSHException as e:return False, f'SSHException: {e}'except Exception as e:return False, f'Connection failed: {e}'try:output = run_command_interactive(client, command, cmd_timeout=cmd_timeout)except Exception as e:try:client.close()except:passreturn False, f'Failed to run command: {e}'try:client.close()except:passif not output:return True, []? # 沒有輸出也返回成功但沒有接口blocks = split_interface_blocks(output)results = []for iface, block in blocks:crc_val = extract_crc_from_block(block)# 規范輸出值:數字 -> string of number; None -> 'Unknown'; 0 -> '0'if crc_val is None:crc_str = 'Unknown'else:crc_str = str(int(crc_val))results.append({'interface': iface, 'crc': crc_str})return True, resultsdef main():parser = argparse.ArgumentParser(description='Check interfaces CRC on devices listed in ip.txt')parser.add_argument('-i', '--ipfile', default=os.environ.get('IP_FILE', DEFAULT_IP_FILE), help='IP list file (default ip.txt)')parser.add_argument('-u', '--username', help='SSH username (or set SSH_USER env)')parser.add_argument('-p', '--password', help='SSH password (or set SSH_PASS env) - warning: visible in process list')parser.add_argument('-c', '--command', default=os.environ.get('CRC_CMD', DEFAULT_COMMAND), help=f'Command to run on device (default: "{DEFAULT_COMMAND}")')parser.add_argument('-o', '--output', default=DEFAULT_OUTPUT, help='Output Excel filename')parser.add_argument('--connect-timeout', type=int, default=int(os.environ.get('SSH_CONNECT_TIMEOUT', DEFAULT_CONNECT_TIMEOUT)), help='SSH connect timeout seconds (default 5)')parser.add_argument('--cmd-timeout', type=int, default=int(os.environ.get('SSH_CMD_TIMEOUT', DEFAULT_CMD_TIMEOUT)), help='Command read timeout seconds (default 30)')args = parser.parse_args()ips = read_ip_list(args.ipfile)if not ips:print(f'[!] No IPs found in {args.ipfile}')returnusername = args.username or os.environ.get('SSH_USER') or input('SSH username: ')password = args.password or os.environ.get('SSH_PASS') or getpass.getpass('SSH password: ')all_rows = []failures = []print(f'[+] Loaded {len(ips)} IPs, connecting with timeout {args.connect_timeout}s, command timeout {args.cmd_timeout}s')for ip in ips:print(f'[{ip}] connecting...')success, data = check_one_device(ip, username, password, args.command, args.connect_timeout, args.cmd_timeout)if not success:print(f'[{ip}] FAILED: {data}')failures.append({'ip': ip, 'reason': data})continueparsed = dataif not parsed:print(f'[{ip}] OK, but no interface blocks parsed.')# still add a row to indicate device had no data? We skip adding rows for this device (user requested only IP/interface/crc)continueprint(f'[{ip}] OK, {len(parsed)} interfaces parsed.')for ent in parsed:all_rows.append({'ip': ip, 'interface': ent['interface'], 'crc': ent['crc']})# 寫 Excel:只包含 ip, interface, crc;另一個 sheet 記錄失敗df = pd.DataFrame(all_rows, columns=['ip', 'interface', 'crc'])df_fail = pd.DataFrame(failures, columns=['ip', 'reason'])with pd.ExcelWriter(args.output, engine='openpyxl') as writer:df.to_excel(writer, sheet_name='crc_results', index=False)df_fail.to_excel(writer, sheet_name='ssh_failures', index=False)print(f'[+] Done. Results saved to {args.output}')print(f'[+] Devices checked: {len(ips)}, interfaces rows: {len(all_rows)}, ssh failures: {len(failures)}')if __name__ == '__main__':main()

四、實驗結果:

建議在終端運行,pycharm運行,getpass會卡住

最終生成excel表:

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

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

相關文章

Wed前端第二次作業

一、作業1&#xff1a;完成自己學校的官網&#xff0c;動忘內容直接貼&#xff0c;至少三個不同的頁面1、界面1&#xff08;1&#xff09;相關代碼<!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><meta name&quo…

第5節 大模型分布式推理通信優化與硬件協同

前言 在分布式推理中,多設備(如GPU、CPU)之間的數據傳輸(通信)是連接計算的“橋梁”。如果通信效率低下,即使單設備計算能力再強,整體性能也會大打折扣。想象一下:如果工廠之間的物流卡車跑得比生產速度還慢,再多的工廠也無法提高整體產量。 本節將從最基礎的單設備內…

XGBoost 的適用場景以及與 CNN、LSTM 的區別

XGBoost 的核心優勢與適用場景XGBoost 是一種梯度提升決策樹算法&#xff0c;屬于集成學習方法。它在處理結構化/表格化數據方面表現極其出色&#xff0c;是 Kaggle 競賽和工業界廣泛應用的“冠軍”模型。其核心優勢和應用場景包括&#xff1a;1. 結構化/表格化數據數據形式&a…

快速設計簡單嵌入式操作系統(3):動手實操,基于STC8編寫單任務執行程序,感悟MCU指令的執行過程

引言 前面我們陸續學習了操作系統常見的基礎概念&#xff0c;接著簡單了解了一下8051單片機的內存結構和執行順序切換的相關概念。接下來&#xff0c;我們就開始進行實操&#xff0c;基于8051單片機STC8來編寫一個簡單的操作系統&#xff0c;這里我們先實現一個單任務的執行程…

Spring AI Alibaba - 聊天機器人快速上手

本節對應 Github&#xff1a;https://github.com/JCodeNest/JCodeNest-AI-Alibaba/tree/master/spring-ai-alibaba-helloworld 本文將以阿里巴巴的通義大模型為例&#xff0c;通過 Spring AI Alibaba 組件&#xff0c;手把手帶你完成從零到一的構建過程&#xff1a;首先&#…

串口通信學習

不需要校驗位就選8位&#xff0c;需要校驗位就選9位&#xff01;USRTUSART框圖STM32的外設引腳這是USART的基本結構。數據幀&#xff0c;八位是這個公式還是很重要的&#xff01;如果在編輯器里面使用printf打印漢字的話&#xff0c;會出現亂碼的話&#xff0c;前提是你的編碼格…

面試經典150題[001]:合并兩個有序數組(LeetCode 88)

合并兩個有序數組&#xff08;LeetCode 88&#xff09; https://leetcode.cn/problems/merge-sorted-array/?envTypestudy-plan-v2&envIdtop-interview-150 1. 題目背景 你有兩個已經排好序的數組&#xff1a; nums1&#xff1a;前面是有效數字&#xff0c;后面是空位&…

快速安裝達夢8測試庫

計劃&#xff1a;數據庫名實例名PORT_NUMMAL_INST_DW_PORTMAL_HOSTMAL_PORTMAL_DW_PORTDMDWDBINST_1533615101192.168.207.612510135101*****[2025-08-11 15:14:34]***** Last login: Fri Jul 25 17:36:04 2025 from 192.168.88.48 [rootdm01 ~]# ip a 1: lo: <LOOPBACK,UP,…

Hive中優化問題

一、小文件合并優化Hive中的小文件分為Map端的小文件和Reduce端的小文件。(1)、Map端的小文件優化是通過CombineHiveInputFormat操作。相關的參數是&#xff1a;set hive.input.formatorg.apache.hadoop.hive.ql.io.CombineHiveInputFormat;(2)、Reduce端的小文件合并Map端的小…

tlias智能學習輔助系統--Maven高級-繼承

目錄 一、打包方式與應用場景 二、父子工程繼承關系 1. 父工程配置 2. 子工程配置 三、自定義屬性與引用屬性 1. 定義屬性 2. 在 dependencyManagement 中引用 3. 子工程中引用 四、dependencyManagement 與 dependencies 的區別 五、項目結構示例 六、小結 在實際開…

把 AI 押進“小黑屋”——基于 LLM 的隱私對話沙盒設計與落地

標簽&#xff1a;隱私計算、可信執行環境、LLM、沙盒、內存加密、TEE、SGX、Gramine ---- 1. 背景&#xff1a;甲方爸爸一句話&#xff0c;“數據不能出機房” 我們給某三甲醫院做智能問診助手&#xff0c;模型 70 B、知識庫 300 GB。 甲方只給了兩條鐵律&#xff1a; 1. 患者…

Java 大視界 -- Java 大數據在智能教育學習效果評估指標體系構建與精準評估中的應用(394)

Java 大視界 -- Java 大數據在智能教育學習效果評估指標體系構建與精準評估中的應用&#xff08;394&#xff09;引言&#xff1a;正文&#xff1a;一、傳統學習評估的 “數字陷阱”&#xff1a;看不全、說不清、跟不上1.1 評估維度的 “單行道”1.1.1 分數掩蓋的 “學習真相”…

Dubbo 3.x源碼(33)—Dubbo Consumer接收服務調用響應

基于Dubbo 3.1&#xff0c;詳細介紹了Dubbo Consumer接收服務調用響應 此前我們學習了Dubbo Provider處理服務調用請求的流程&#xff0c;現在我們來學習Dubbo Consumer接收服務調用響應流程。 實際上接收請求和接收響應同屬于接收消息&#xff0c;它們的流程的很多步驟是一樣…

棧和隊列:數據結構中的基礎與應用?

棧和隊列&#xff1a;數據結構中的基礎與應用在計算機科學的領域中&#xff0c;數據結構猶如大廈的基石&#xff0c;支撐著各類復雜軟件系統的構建。而棧和隊列作為兩種基礎且重要的數據結構&#xff0c;以其獨特的特性和廣泛的應用&#xff0c;在程序設計的舞臺上扮演著不可或…

服務端配置 CORS解決跨域問題的原理

服務端配置 CORS&#xff08;跨域資源共享&#xff09;的原理本質是 瀏覽器與服務器之間的安全協商機制。其核心在于服務器通過特定的 HTTP 響應頭聲明允許哪些外部源&#xff08;Origin&#xff09;訪問資源&#xff0c;瀏覽器根據這些響應頭決定是否放行跨域請求。以下是詳細…

Unity筆記(五)知識補充——場景切換、退出游戲、鼠標隱藏鎖定、隨機數、委托

寫在前面&#xff1a;寫本系列(自用)的目的是回顧已經學過的知識、記錄新學習的知識或是記錄心得理解&#xff0c;方便自己以后快速復習&#xff0c;減少遺忘。主要是C#代碼部分。十七、場景切換和退出游戲1、場景切換場景切換使用方法&#xff1a; SceneManager.LoadScene()&a…

用 Spring 思維快速上手 DDD——以 Kratos 為例的分層解讀

用 Spring 思維理解 DDD —— 以 Kratos 為參照 ? 在此前的學習工作中&#xff0c;使用的開發框架一直都是 SpringBoot&#xff0c;對 MVC 架構幾乎是肌肉記憶&#xff1a;Controller 接請求&#xff0c;Service 寫業務邏輯&#xff0c;Mapper 操作數據庫&#xff0c;這套套路…

docspace|Linux|使用docker完全離線化部署onlyoffice之docspace文檔協作系統(全網首發)

一、 前言 書接上回&#xff0c;Linux|實用工具|onlyoffice workspace使用docker快速部署&#xff08;離線和定制化部署&#xff09;-CSDN博客&#xff0c;如果是小公司或者比如某個項目組內部使用&#xff0c;那么&#xff0c;使用docspace這個文檔協同系統是非常合適的&…

【教程】如何高效提取胡蘿卜塊根形態和顏色特征?

胡蘿卜是全球不可或缺的健康食材和重要的經濟作物&#xff0c; 從田間到餐桌&#xff0c;從鮮食到深加工&#xff0c;胡蘿卜在現代人的飲食和健康中扮演著極其重要的角色&#xff0c;通過量化塊根形態和色澤均勻性&#xff0c;可實現對高產優質胡蘿卜品種的快速篩選。工具/材料…

Python初學者筆記第二十四期 -- (面向對象編程)

第33節課 面向對象編程 1. 面向對象編程基礎 1.1 什么是面向對象編程面向過程&#xff1a;執行者 耗時 費力 結果也不一定完美 面向對象&#xff1a;指揮者 省時 省力 結果比較完美面向對象編程(Object-Oriented Programming, OOP)是一種編程范式&#xff0c;它使用"對象&…