1. 程式人生 > 實用技巧 >使用python批量獲取IP對應的交換機介面並生成excel表

使用python批量獲取IP對應的交換機介面並生成excel表

以下程式碼是本人現網親測指令碼。

程式碼如下“

# -*- coding: gbk -*-
# 製作人:Tim

import os
import openpyxl
from openpyxl import Workbook

path = "D:\\裝置日誌\\7503-info.txt"
dir = "D:\\裝置日誌\\"


def action(pathx,hostname,content):
    f1 = open(pathx,'r')    # 開啟檔案
    for line1 in f1.readlines():    # 遍歷檔案內容
        if content[1] in
line1: if "port-security" in line1: pass else: lst1 = line1.split(" ") # 格式如下:['f84d-fc56-6c45', '', '', '22', '', 'Learned', '', 'GE1/0/25'] if 'Security' in lst1: output = open("D:\\裝置日誌\\cctv\\output.txt"
,'a') # 新建一個檔案,把輸出的內容儲存到這裡 if ('GE1/0/25' in lst1 or 'GE1/0/26' in lst1 or 'GE1/0/27' in lst1 or 'BAGG1' in lst1 or 'GE1/0/49' in lst1 or 'GE1/0/52' in lst1 or 'BAGG2' in lst1 or 'BAGG3' in lst1 or 'GE2/0/28' in lst1 or 'GE1/0/51' in lst1):
pass else: print("hostname:"+ hostname[1]+" IP:"+ content[0]+" MAC:" + content[1] + " 介面:" + lst1[21],file = output) book = openpyxl.load_workbook(r'D:\python\program\test.xlsx') sheet = book.active l1 = [] l1.append(hostname[1]) l1.append(content[0]) l1.append(content[1]) l1.append(lst1[21]) sheet.append(l1) book.save(r'D:\python\program\test.xlsx') output.close() if "Learned" in lst1: output = open("D:\\裝置日誌\\output.txt",'a') if ('GE1/0/25' in lst1 or 'GE1/0/26' in lst1 or 'GE1/0/27' in lst1 or 'BAGG1' in lst1 or 'GE1/0/49' in lst1 or 'GE1/0/52' in lst1 or 'BAGG2' in lst1 or 'BAGG3' in lst1 or 'GE2/0/28' in lst1 or 'GE1/0/51' in lst1): pass else: print("hostname:"+ hostname[1]+" IP:"+ content[0]+" MAC:" + content[1] + " 介面:" + lst1[22],file = output) book = openpyxl.load_workbook(r'D:\python\program\test.xlsx') sheet = book.active l1 = [] l1.append(hostname[1]) l1.append(content[0]) l1.append(content[1]) l1.append(lst1[22]) sheet.append(l1) book.save(r'D:\python\program\test.xlsx') output.close() f1.close() def main(): book = Workbook() sheet = book.active book.save('D:\\python\\program\\test.xlsx') content = [] f = open(path,'r') for line in f.readlines(): # 遍歷"D:\\裝置日誌\\7503-info.txt"檔案 lst = line.split(" ") for i in lst: if i !='': # 去除列表中的' '空元素 content.append(i) # 如:['10.235.22.9', 'f84d-fc56-6c52', '22', 'GE1/0/0/3', '1188', 'D', '\n'] for x in os.listdir(dir): # 遍歷dir目錄下的內容,如D:\\裝置日誌\\cctv\\ pathx = dir +x # 賦值pathx = “D:\\裝置日誌\\7月\\10.235.11.4” hostname = pathx.split(" ") for a in range(20,35): # 匹配vlan 20 - 34 if content[2] == str(a): # content[2]匹配的是vlan action(pathx,hostname,content) content=[] f.close () if __name__=='__main__': main()

效果如下:

PS:本人非專業的程式設計師,如寫得不好請多擔待,歡迎留言評論,謝謝!!