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

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

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

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

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

如下對各個步驟進行詳細的描述,但願對你們的工做有幫助ide

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.txtcode

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

將以上代碼拷貝爲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 = "abc@163.com"

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

Const Email_To = "def@139.com"

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 

相關文章
相關標籤/搜索