導出系統日誌並自動發送郵件到指定郵箱的一般方法(Windows server適用)

筆者在工作中遇到這樣的問題,如何每天將指定的系統日誌發送到指定的郵箱,直接在郵件中查看系統日誌,通過這樣的方法,不需要登錄每臺服務器去查看系統日誌,大致的做法如下:

    1. 採用批處理蒐集系統日誌到一個指定文件

    2. 將這個文件的內容作爲郵件的正文發送到指定郵箱

    3. 安排計劃任務,設置指定的時間發送

以下對各個步驟進行詳細的描述,希望對大家的工作有幫助

1. 收集系統日誌到指定文件,採用的是eventquery.vbs這個工具,這是系統自帶的工具,詳細的使用方法見微軟KB: http://technet.microsoft.com/zh-cn/library/cc772995(WS.10).aspx ,舉例:導出最近3條event id 爲1003的事件的記錄:

echo ==========應用程序報警================ > c:\event.txt

eventquery.vbs /r 3 /L application /FI "id eq 1003" /FO list /v >> c:\event.txt

設置cscript爲指定編譯器:cscript //h:cscript //s

將以上代碼拷貝爲bat文件格式,執行完成之後打開event.txt,可以獲得內容

2. 將獲得的內容作爲郵件的內容併發送,腳本如下

content= "c:\event.txt"

set fso=createobject("scripting.filesystemobject")

if fso.fileexists(content) then

set fil=fso.getfile(content)

filename=fil.name

if lcase(right(filename,4))=".txt" then

set txt=fso.opentextfile(content,1)

code=txt.readall

txt.close

end if

end if

nr=code

Const Email_From = "[email protected]"

Const Password = "**********"

Const Email_To = "[email protected]"

Set CDO = CreateObject("CDO.Message") '創建CDO.Message對象

CDO.Subject = "Server test" '郵件主題

CDO.From = Email_From '發件人地址

CDO.To = Email_To '收件人地址

CDO.TextBody = nr '郵件正文

'cdo.AddAttachment = "C:\hello.txt" '郵件附件文件路徑

Const schema = "http://schemas.microsoft.com/cdo/configuration/"

With CDO.Configuration.Fields '用with關鍵字減少代碼輸入

.Item(schema & "sendusing") = 2 '使用網絡上的SMTP服務器而不是本地的SMTP服務器

.Item(schema & "smtpserver") = "smtp.163.com" 'SMTP服務器地址

.Item(schema & "smtpauthenticate") = 1 '服務器認證方式

.Item(schema & "sendusername") = Email_From '發件人郵箱

.Item(schema & "sendpassword") = Password '發件人郵箱密碼

.Item(schema & "smtpserverport") = 25 'SMTP服務器端口

.Item(schema & "smtpusessl") = True '是否使用SSL

.Item(schema & "smtpconnectiontimeout") = 60 '連接服務器的超時時間

.Update '更新設置

End With

CDO.Send '發送郵件

msgbox "Email sent!"

把上面的代碼保存爲automail.vbs.

3. 將上面兩個步驟合併在一起,使用BAT,內容如下:

:應用程序報警

echo ==========應用程序報警================ > c:\event.txt

eventquery.vbs /r 3 /L application /FI "id eq 1003" /FO list /v >> c:\event.txt

call automail.vbs

把這個代碼保存爲export.bat

4.使用系統的計劃任務,安排計劃,可以設定每天下午三點鐘自動發送日誌到指定郵箱

5.補充:本地的SMTP服務器郵件發送部分代碼如下

     With CDO.Configuration.Fields 

.Item(schema & "sendusing") = 2 

.Item(schema & "smtpserver") = "10.10.10.10" ‘內部smtp地址  

.Item(schema & "smtpauthenticate") = 0 

.Item(schema & "sendusername") = Email_From  

'.Item(schema & "sendpassword") = Password  

.Item(schema & "smtpserverport") = 25  

.Item(schema & "smtpusessl") = False  

.Item(schema & "smtpconnectiontimeout") = 60 

.Update  

End With 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章