Excel VBA: 自動生成巡檢報表並通過郵件定時發送


目錄

環境說明
邏輯結構
效果說明及截圖
①. 安裝SecureCRT
②. 自動巡檢腳本
③. 數據檢索並FTP傳送
④. 安裝Excel 2013
⑤. 安裝Serv-U
⑥. 自動生成圖表並郵件發送

環境說明

系統: Windows Server 2003, Windows Server 2008

Windows Server 2003上目錄結構: 

Windows Server 2008 上的目錄結構:

系統說明: 可在一台機器上進行[Windows Server 2008支持Excel 2013], 本文在Windows server2003上做數據采集, Windows server2008 上做報表

軟件: SecureCRT, Excel 2013, Serv-U

邏輯結構

 

效果說明及截圖

①. 安裝SecureCRT

  安裝方法請參考官方文檔, 安裝后能夠實現通過命令行調出SecureCRT窗口

  

②. 自動巡檢腳本

1. 建立巡檢列表device_list.txt

建立一個名為device_list.txt的文本, 其中數據組織格式為 IP地址 用戶名 密碼 enable密碼 例如 192.168.100.1 root pass enpass

2. 建立SecureCRT可調用的腳本checking_router.vbs

腳本內容如下

 1 Sub Main
 2      '打開保存設備管理地址以及密碼的文件
 3      Const ForReading = 1, ForWriting = 2, ForAppending = 8
 4      Dim fso,dvices,line,command,params
 5      Set fso = CreateObject("Scripting.FileSystemObject")
 6      Set dvices = fso.OpenTextFile("device_list",Forreading, False)        
 7      crt.Screen.Synchronous = True
 8      DO While dvices.AtEndOfStream <> True
 9         '讀出每行
10         line = dvices.ReadLine
11         '分離每行的參數 IP地址 用戶名 密碼 En密碼
12         params = Split (line)
13         '在日志文件里添加時間戳
14         dim directory
15         directory = "datadir/" & "R_"&params(0)&"_"&Year(Date)&Right("0"&Month(Date),2)&Right("0"&Day(Date),2)& ".txt"
16         set fso1=createobject("scripting.filesystemobject") 
17         set file=fso1.opentextfile(directory,8,true)
18         dim timestamp
19         timestamp = "flow: "&Year(now)&"-"&Month(now)&"-"&Day(now)&" "&Hour(now)&":"&Minute(now) 
20         file.writeline timestamp
21         file.close 
22         '下面執行命令, 並將命令執行結果記入日志
23         crt.session.LogFileName = "datadir/" & "R_"&params(0)&"_"&Year(Date)&Right("0"&Month(Date),2)&Right("0"&Day(Date),2)& ".txt"
24         '表示讓日志追加寫入
25         crt.session.Log true, true
26         'SSH2到這個設備上
27         crt.session.Connect "/SSH2 /PASSWORD "&params(2)&" "&params(1)&"@" & params(0)
28         '輸入telnet密碼
29         'crt.Screen.WaitForString "Password:"
30         'crt.Screen.Send params(1) & chr(13)
31         '進特權模式
32         crt.Screen.Send "enable" & chr(13)
33         crt.Screen.WaitForString "Password:"
34         crt.Screen.Send params(3) & chr(13)
35         crt.Screen.waitForString "#"
36         '執行數據收集命令
37         command = "show ip fpm statistics"
38         crt.Screen.Send command & vbcr
39         crt.Screen.waitForString "#" 
40         '執行完命令, 斷開連接
41         crt.Session.Disconnect         
42         loop
43     '在后台運行
44     crt.Screen.Synchronous = False
45     '執行完關閉程序
46     Close_Process("securecrt.exe")      
47 End Sub
48     sub Close_Process(ProcessName)  
49     On Error Resume Next  
50          for each ps in getobject("winmgmts:\\.\root\cimv2:win32_process").instances_ '循環進程  
51                if Ucase(ps.name)=Ucase(ProcessName) then  
52                      ps.terminate  
53                end if  
54          next  
55     end sub  
checking_router.bat

3. 建立Inspection_router.bat

  • 腳本內容如下
    @echo off
    securecrt /SCRIPT checking_router.vbs

4. 設定自動任務計划

    設定Inspection_router.bat任務計划, 該計划任務設定的巡檢周期為30分鍾, 從0:10開始, 執行24個小時, 每天每台網絡設備會產生48條數據

    

    設定search_transfer.bat計划任務

    

5. 執行結果

    

③. 數據檢索並FTP傳送

  • 1. 創建數據檢索腳本search_transfer.bat

 1 @echo off
 2 
 3 ::獲取和vb一致的時間格式
 4 set /a tm1=%time:~0,2%*1
 5 if %tm1% LSS 10 set tm1=0%tm1%
 6 echo %date:~0,4%%date:~5,2%%date:~8,2%
 7 set i=%date:~0,4%%date:~5,2%%date:~8,2%
 8 
 9 
10 ::篩選原始巡檢數據
11 mkdir temp
12 for %%I in (datadir/R_*_%i%.txt) do (echo %%I
13 findstr "flows" datadir\%%I>temp\%%I)
14 
15 ::向日志里添加分割線
16 echo ======================================================== >> log.txt
17 ::向日志里添加日期時間
18 echo %date% %time%>> log.txt
19 
20 
21 ::執行cmd.txt里的傳輸信息, 日志輸出到log.txt
22 ftp -s:ftpinfo.txt >> log.txt
23 
24 ::清除temp臨時文件夾
25 rd /S /Q temp
26 
27 ::刪除臨時文件lldp的篩選結果
28 for /r %%a in (*_Report_%i%*) do (del %%a)
search_transter.bat
  • 2. 創建ftp信息文本ftpinfo.txt

    open 192.168.100.103
    user
    password
    
    lcd temp
    mkdir temp
    cd /temp/
    
    binary
    prompt off
    mput *.txt
    
    quit

④. 安裝Excel 2013

安裝方法參考官方文檔

⑤. 安裝Serv-U

安裝方法參考官方文檔

⑥. 自動生成圖表並郵件發送

1. 建立巡檢設備列表文件NBR_G.txt

文件內容格式為 IP地址 設備名稱 設備型號; 每個型號統計結束, 使用 IP END 型號 結束標志

例如

192.168.10.1 Waiwang 1500G
IP END 1500G
192.168.20.1 MSTP 2000G
192.168.30.1 IPsec 2000G
IP END 2000G

2. 建立報表繪圖文件NBR_G.xlsm(支持宏的Excel)

建立時間表

  編寫宏代碼 

  1 'Attribute VB_Name = "模塊1"
  2 Sub 制圖表_NBR_G()
  3 'Attribute 制圖表_NBR_G.VB_ProcData.VB_Invoke_Func = " \n14"
  4 '獲取當前文件目錄
  5     Dim CurPath
  6     CurPath = ActiveWorkbook.Path
  7 ' 制圖表_NBR_G 宏
  8     Application.DisplayAlerts = False
  9 ' 獲取今天的時間
 10     Dim DateOfToday As String
 11     DateOfToday = Format$(Date, "yyyymmdd")
 12     'DateOfToday = 20161105
 13 '打開文本取數據
 14     Const ForReading = 1, ForWriting = 2, ForAppending = 8
 15 '格式:路由器IP 店鋪編號 型號
 16     Dim fso, file1, line, params, ip, number, mode
 17     Set fso = CreateObject("Scripting.FileSystemObject")
 18     Set file1 = fso.OpenTextFile(CurPath & "\NBR_G.txt", ForReading, False)
 19 '循環寫每一列數據
 20 Do While file1.AtEndOfStream <> True
 21 '讀取一行數據
 22     line = file1.ReadLine
 23 '格式:路由器IP 店鋪編號 型號
 24     params = Split(line)
 25 '獲取IP地址
 26     ip = params(0)
 27 '店鋪編號
 28     number = params(1)
 29 '獲取設備型號
 30     mode = params(2)
 31     
 32 '判斷同一型號設備添加數據結束,制圖標
 33     If number = "END" Then
 34     '刪除掉多余字符串
 35     Cells.Replace What:="Number of active flows:", Replacement:="", LookAt:= _
 36         xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
 37         ReplaceFormat:=False
 38     Cells.Replace What:="Active flows num:", Replacement:="", LookAt:= _
 39         xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
 40         ReplaceFormat:=False
 41         
 42     If mode = "1300G" Then
 43 '調整數據格式
 44     Range("B2:AI49").Select
 45     Selection.NumberFormatLocal = "0"
 46 '選擇區域生成圖表
 47     Range("A1:AI49").Select
 48     ActiveSheet.Shapes.AddChart2(240, xlXYScatterSmoothNoMarkers).Select
 49     ActiveChart.SetSourceData Source:=Range("data!$A$1:$AI$49")
 50     End If
 51     
 52     If mode = "1000G" Then
 53 '調整數據格式
 54     Range("B2:I49").Select
 55     Selection.NumberFormatLocal = "0"
 56 '選擇區域生成圖表
 57     Range("A1:I49").Select
 58     ActiveSheet.Shapes.AddChart2(240, xlXYScatterSmoothNoMarkers).Select
 59     ActiveChart.SetSourceData Source:=Range("data!$A$1:$I$49")
 60     End If
 61     
 62     If mode = "1500G" Then
 63     '調整數據格式
 64     Range("B2:B49").Select
 65     Selection.NumberFormatLocal = "0"
 66 '選擇區域生成圖表
 67     Range("A1:B49").Select
 68     ActiveSheet.Shapes.AddChart2(240, xlXYScatterSmoothNoMarkers).Select
 69     ActiveChart.SetSourceData Source:=Range("data!$A$1:$B$49")
 70     End If
 71     
 72     If mode = "2000G" Then
 73     '調整數據格式
 74     Range("B2:D49").Select
 75     Selection.NumberFormatLocal = "0"
 76 '選擇區域生成圖表
 77     Range("A1:D49").Select
 78     ActiveSheet.Shapes.AddChart2(240, xlXYScatterSmoothNoMarkers).Select
 79     ActiveChart.SetSourceData Source:=Range("data!$A$1:$D$49")
 80     End If
 81         
 82     ActiveChart.Axes(xlCategory).Select
 83 '調整圖表橫坐標度量值
 84     ActiveChart.Axes(xlCategory).MaximumScale = 1
 85     ActiveChart.Axes(xlCategory).MajorUnit = 0.05
 86 '調整圖表縱坐標起始值
 87     ActiveChart.Axes(xlValue).MinimumScale = 0
 88     ActiveChart.ClearToMatchStyle
 89     ActiveChart.ChartStyle = 245
 90 '修改圖表title
 91     ActiveChart.ChartTitle.Select
 92     Selection.Format.TextFrame2.TextRange.Characters.Text = mode & "-" & DateOfToday & "-Report"
 93     ActiveChart.ChartArea.Select
 94 '移動到新的chart里
 95     ActiveChart.Location Where:=xlLocationAsNewSheet
 96     End If
 97     
 98     
 99     If ip <> "IP" Then
100 '激活data sheet
101     Worksheets("data").Activate
102 '從文本讀取數據寫到B2
103     
104     With ActiveSheet.QueryTables.Add(Connection:= _
105         "TEXT;" & CurPath & "\temp\R_" & ip & "_" & DateOfToday & ".txt", Destination:= _
106         Range("$B$2"))
107         .Name = "R_" & ip & "_" & DateOfToday & ""
108         .FieldNames = True
109         .RowNumbers = False
110         .FillAdjacentFormulas = False
111         .PreserveFormatting = True
112         .RefreshOnFileOpen = False
113         .RefreshStyle = xlInsertDeleteCells
114         .SavePassword = False
115         .SaveData = True
116         .AdjustColumnWidth = False
117         .RefreshPeriod = 0
118         .TextFilePromptOnRefresh = False
119         .TextFilePlatform = 936
120         .TextFileStartRow = 1
121         .TextFileParseType = xlDelimited
122         .TextFileTextQualifier = xlTextQualifierDoubleQuote
123         .TextFileConsecutiveDelimiter = False
124         .TextFileTabDelimiter = True
125         .TextFileSemicolonDelimiter = False
126         .TextFileCommaDelimiter = False
127         .TextFileSpaceDelimiter = False
128         .TextFileColumnDataTypes = Array(1, 1, 1, 1)
129         .TextFileTrailingMinusNumbers = True
130         .Refresh BackgroundQuery:=False
131     End With
132 '將店鋪編號寫到B1
133     Range("B1").Select
134     ActiveCell.FormulaR1C1 = number
135     End If
136 
137 Loop
138 '將生成圖標另存為本目錄下的excel
139     ChDir CurPath
140     ActiveWorkbook.SaveAs Filename:=CurPath & "\NBR_G_Report_" & DateOfToday & ".xlsx", _
141         FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
142 
143 End Sub
制報表_NBR_G

3. 建立可調用NBR_G.xlsm執行的腳本NBR_G.vbs

 1 '獲取當前目錄
 2 Dim CurrentDirectory
 3 CurrentDirectory =Left(WScript.ScriptFullName, (Len(WScript.ScriptFullName))-(Len(WScript.ScriptName)))
 4 Set objExcel = CreateObject("Excel.Application")
 5 '打開指定的含有宏的excel
 6 Set objWorkbook = objExcel.Workbooks.Open(CurrentDirectory & "NBR_G.xlsm")
 7 '設置excel運行是否可視
 8 objExcel.Application.Visible = false
 9 'objExcel.Workbooks.Add
10 'objExcel.Cells(1, 1).Value = "Test value"
11 '運行Execl中的宏
12 objExcel.Application.Run "制報表_NBR_G"
13 '關閉活動的表格
14 objExcel.ActiveWorkbook.Close
15 '關閉Execl程序
16 objExcel.Application.Quit
17 'WScript.Echo "Finished."
18 '退出vbs
19 WScript.Quit
NBR_G.vbs

4. 建立自動發送郵件腳本SendEmail.vbs

 1 '以下是利用上面的函數發送帶附件的郵件例子 
 2 If Send_Mail("senduser@163.com","sendpass","reciver mail1;receiver mail2","","巡檢報告詳情請查看附件!")=True Then 
 3 'Wscript.Echo "發送成功" 
 4 Else 
 5 'Wscript.Echo "發送失敗" 
 6 End If 
 7 
 8 function Send_mail(You_Account,You_Password,Send_Email,Send_Email2,Send_Body)  
 9 'code by NetPatch 
10 'VBS發送郵件參數說明 
11 'You_Account:你的郵件帳號 
12 'You_Password:你的郵件密碼 
13 'Send_Email: 主要郵件地址 
14 'Send_Email2: 備用郵件地址 
15 'Send_Topic: 郵件主題 
16 'Send_Body:   郵件內容 
17 'Send_Attachment:郵件附件 
18 
19 You_ID=Split(You_Account, "@", -1, vbTextCompare)  
20 '帳號和服務器分離 
21 MS_Space = "http://schemas.microsoft.com/cdo/configuration/" 
22 '這個是必須要的,不過可以放心的事,不會通過微軟發送郵件 
23 Set Email = CreateObject("CDO.Message") 
24 Email.From = You_Account 
25 '這個一定要和發送郵件的帳號一樣 
26 Email.To = Send_Email         '主要郵件地址 
27 
28 If Send_Email2 <> "" Then 
29 Email.CC = Send_Email2        '備用郵件地址 
30 End If 
31 
32 Email.Subject = "巡檢報告_"&Year(now)&"-"&Month(now)&"-"&Day(now)&" "&Hour(now)&":"&Minute(now)         '郵件主題 
33 Email.Textbody = Send_Body        '郵件內容 
34 
35 'If IsArray(Send_Attachment) Then
36 'Dim attachment
37 'For Each attachment In Send_Attachment
38 'Email.AddAttachment attachment     '郵件附件 
39 'Next
40 'End If
41 
42 '從dir_temp.txt讀取含有指定日期的巡檢文件,添加成附件
43 Const ForReading = 1, ForWriting = 2, ForAppending = 8
44 Dim fso,file1,attachment
45 Set fso = CreateObject("Scripting.FileSystemObject")
46 Set file1 = fso.OpenTextFile("dir_temp.txt",Forreading, False)        
47 DO While file1.AtEndOfStream <> True
48 '讀出每行
49 attachment = file1.ReadLine
50 Email.AddAttachment attachment    
51 loop
52 
53 'If Send_Attachment <> "" Then 
54 'Email.AddAttachment Send_Attachment     '郵件附件 
55 'End If 
56 
57 With Email.Configuration.Fields 
58 .Item(MS_Space&"sendusing") = 2       '發信端口 
59 .Item(MS_Space&"smtpserver") = "smtp."&You_ID(1) 'SMTP服務器地址 
60 .Item(MS_Space&"smtpserverport") = 25     'SMTP服務器端口 
61 .Item(MS_Space&"smtpauthenticate") = 1     'cdobasec 
62 .Item(MS_Space&"sendusername") = You_ID(0)    '你的郵件帳號 
63 .Item(MS_Space&"sendpassword") = You_Password   '你的郵件密碼 
64 .Update 
65 End With 
66 Email.Send 
67 '發送郵件 
68 Set Email=Nothing 
69 '關閉組件 
70 
71 Send_Mail=True  
72 '如果沒有任何錯誤信息,則表示發送成功,否則發送失敗  
73 If Err Then  
74 Err.Clear  
75 Send_Mail=False  
76 End If  
77 End Function 
SendEmail.vbs

5. 建立可調用NBR_G.xlsm和SendEmail.vbs的腳本NBR_G.bat

 1 @echo off
 2 
 3 ::調用生成圖表
 4 wscript NBR_G.vbs
 5 
 6 ::刪除臨時文件及文件夾,靜默, 不需要確認
 7 rd /S /Q temp
 8 
 9 ::查找相關文件目錄存放到dir_temp.txt
10 for /r %%a in (*_Report_%i%*) do (echo %%a>>dir_temp.txt)
11 
12 ::郵件發送
13 wscript SendEmail.vbs
14 
15 ::刪除郵件已發送的附件存根
16 for /r %%a in (*_Report_%i%*) do (del %%a)
17 del dir_temp.txt
NBR_G.bat

6. 設定自動任務計划

設定自動任務計划的對象是NBR_G.bat

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM