Server – 在水一方 https://blog.vic.mh4u.org 蒹葭蒼蒼,白露為霜。所謂伊人,在水一方。 Thu, 31 Mar 2016 05:54:52 +0000 zh-TW hourly 1 https://wordpress.org/?v=6.7.1 pve4和vlans https://blog.vic.mh4u.org/2016/1532 https://blog.vic.mh4u.org/2016/1532#respond Thu, 31 Mar 2016 03:55:08 +0000 http://blog.vic.mh4u.org/?p=1532 閱讀全文 ]]> Proxmox VE 4.x 的 vlan 功能完整,現就介紹實際應用

我們需要搭配一台網管式 switch ,也就是可切vlan的switch,我們選用 ZyXEL GS1900-8 8port switch 這一台。

應用說明:

ZyXEL GS1900-8 8port switch

ZyXEL GS1900-8 8port switch

參閱上圖,1~7 port,我們分別切成 vlan1~7, 第8port設為trunk port接 pve4 server,這樣的接法用意是在1~7port可接7條小烏龜線路,而pve4 裡的虛擬子機,則可透過 trunk port 分別調用這7條線路,現在的很多虛擬系統都支援vlan,所以這樣的接法應用是很廣的。

重點提醒:1~7port的這七條線路得是100M以下的速率,而trunk port得用cat6的網路線,才能上1G的速率,這樣才不會發生效能瓶頸卡在trunk port上面。

底下先介紹 ZyXEL GS1900-8 8port switch 這台設定的方法:
預設值: http://192.168.1.1 帳:admin 密:1234

[tip]設定重點提醒:
access port:不打tag,需設定untagged 和設定pvid
trunk port:打vlan tage,不動pvid
如:
port2 設定vlan2 pvid 和 vlan2 untagged
port3 設定vlan3 pvid 和 vlan3 untagged

trunk port設定:
除了個別port設定vlan tagged之外,trunk port也都要跟著在每個vlan裡打tag[/tip]

設定VLAN

首先先加7個vlan
zyxel2

設定PVID

仿照下圖,在7個port上面設定好7個 PVID,第8port設為trunk port 不動PVID
zyxel3

設定untagged

vlan1保留預設值不動
zyxel4
vlan2開始設定,將第2port設定為untagged
因為access port 不打 tag ,而excluded中文是不包括的意思(第2port我們要設成vlan2所以怎能不包括?) Forbidden中文是禁止的意思, 所以只剩一個正確的選項 untagged
vlan3~vlan7則比照這個vlan2來設定。
zyxel5
而第8port是trunk port,它要在每個vlan上面都打tag才能正確的調用這7條線路。

以上的設定都完成了,光按apply是不夠的,全部設定完了之後,一定要按右上角的save,才能真正的儲存了你的設定,才不會在你的switch重開機之後,所有的設定都流失。但…
原文:Click this to apply your changes to the Switch’s run-time memory. The Switch loses these changes if it is turned off or loses power, so use the Save link on the top navigation panel to save your changes to the non-volatile memory when you are done configuring.
根據原文大意可能是,按右上角的save,只會存入 run-time memory (不知是否等同於 Running configuration),估計還要點左下角的maintenance才行

zyxel6

進左下角的 maintenance=>configuration=>management
設定
Running configuration => Startup configuration ==> apply

註:2016/03/31 初步測試按右上角的save即可儲存設定,還要再測第2次才能確認。

Proxmox VE 4 vlan 設定

我這台機器上面有2張網卡,eth0 和 eth1 ,拿 eth1 當trunk port 使用,所以這張網卡的網路線要直連 switch 上面的第8port

vim /etc/network/interfaces

auto vmbr1
iface vmbr1 inet static
        address 192.168.1.4
        netmask 255.255.255.0
        bridge_ports eth1
        bridge_stp off
        bridge_fd 0

按以上這樣設定好了之後,應該就能ping到switch 192.168.1.1 的IP,若ping 不通的話,請回頭檢查你的設定和網路設備,因為到這一步若不通的話,後面就算設對了也沒用,因此請務必確認能ping通了之後再往下做

若你的母機想要能直接撥接上網的話,請將小烏龜接在第1port (vlan1)然後撥接第1port的帳密,就能上網。

Container子機設定

pppoe撥接

vim /etc/pve/lxc/10x.conf
加入底下這行
lxc.cgroup.devices.allow = c 108:0 rwm # /dev/ppp
lxc.mount.entry = /dev/ppp dev/ppp none bind,optional,create=file
註:不要編輯/var/lib/lxc/100/config此檔,無用,重啟CT之後內容會被還原
子機要安裝底下這兩個套件才能撥接
aptitude install ppp pppoeconf
註:pve4不象pve3那樣受限於母機一定要先撥接過後,子機才能正常撥接

子機vlan設定請參照下圖
pve1
只要在vlang tag那一欄上面填上你要使用的vlan數字,就可調用1~7條不同的線路,需注意的是這數字只能填2以上的數字,所以若你是想要用vlan1的話,那麼這個欄位留白不填即可。

按以上設定就可以在Proxmox VE 4.X 裡經由一張網卡,一條網路線調用7條不同的Internet線路。

]]>
https://blog.vic.mh4u.org/2016/1532/feed 0
dhcpstatus https://blog.vic.mh4u.org/2011/391 https://blog.vic.mh4u.org/2011/391#respond Wed, 14 Dec 2011 02:39:03 +0000 http://blog.ns01.us/?p=391 閱讀全文 ]]> 監看dhcp server IP 發放狀況

官網下載點英文安裝教學

系統需求:dhcp server, apache, cgi運行環境

1 下載
請將檔案下載至 /root 目錄

2 建目錄&解壓縮

cd /usr/local/
tar zxvf /root/dhcpstatus_0.60.tar.gz
mv dhcpstatus_0.60 dhcpstatus
cd dhcpstatus
tar xvf libraries.tar

3 設定
vim dhcpstatus.ini
改正確路徑
# location of the .conf file.
conf_file=/etc/dhcp3/dhcpd.conf
# location of the .leases file.
leases_file=/var/lib/dhcp3/dhcpd.leases

4 安裝
安裝方法很簡單,只需把 dhcpstatus.cgi copy 到可執行 cgi 的目錄下即可
cp /usr/local/dhcpstatus/scripts/dhcpstatus.cgi /usr/lib/cgi-bin/

5 網址
http://IP/cgi-bin/dhcpstatus.cgi

]]>
https://blog.vic.mh4u.org/2011/391/feed 0
MDaemon安全性設定 https://blog.vic.mh4u.org/2011/327 https://blog.vic.mh4u.org/2011/327#respond Thu, 04 Aug 2011 04:05:17 +0000 http://blog.ns01.us/?p=327 閱讀全文 ]]>

Mdaemon 的安全性設定主要在這個畫面,可用來擋字典攻擊

Activate dynamic screening

啟用動態 IP 封鎖功能

Ban senders who cause this many failed RCPT attempts 5

這行的意思是當寄件者寄出去的信中有5個收件者的 email address是錯誤的或有問題的 則封鎖這個 IP。通常廣告信發送者會寄給不存在的 email address 或過期的 email 帳號,因此用來擋廣告信很有用。需注意的是, SMTP 用本公司的server 來寄信給自己公司的同仁時,若填了失效或不存在的 email address 時,則是連發信都發不出去,馬上就會提示你 email address 有問題,請檢查。 但若是用別人的 SMTP 要寄給本公司的  server 則不會提示,遇到同時寄給5個有問題的 email 時則馬上 ban IP。

底下的 log 訊息,則是我測試的結果,用 hinet 的 smtp 寄信給本公司的 mail server,隨意的填了 5個假的 email address ,就可看到 log 訊息裡擋了  hinet 的 smtp 168.95.4.109 阻擋時間為 120分鐘。

Thu 2011-08-04 10:52:19: Dynamic screening added 168.95.4.109 for 120 minutes; tried sending to 5 unknown recipients

 

Ban senders that connect more than 5 times in 2 minutes

寄件者在2分鐘內連接本server次數超過5次則封鎖。發生情況通常於 pop3 連接時無正確密碼時的連續測試,因此可用於抵擋字典攻擊。 和過於頻繁的發信動作也會被擋,換句話說,正常的發信動作,兩分鐘內分別寄了5封單獨的信件出去也會被擋。(此話仍推測未經測試證實)

Ban senders that fail this many authentication attempts 3

適用情況: SMTP 寄信時,認證沒有通過,失敗3次則封鎖該IP。此選項無法用於抵擋 pop3 認證錯誤,只適用於SMTP,若要抵擋 pop3攻擊,只能用前一個選項。

Ban senders for this many minutes 30

封鎖時間

Close SMTP session after banning site

禁止該站點後關閉 SMTP 會話,啟用該選項則  MDaemon 在禁止發件人的 IP後會 close smtp session.

Don’t ban senders who use an authenticated session

不禁止使用已驗證會話的發件人。從動態封鎖中排除發送前對郵件會話進行驗證的發件人。

Advanced

進階設定。這裡面記錄了當前已封鎖了的IP,可以手動添加,一行一個IP,格式如下

IP(空格)分鐘   範例: 1.1.1.1 60

 

White list

白名單,可在此填入不想被封鎖的IP

]]>
https://blog.vic.mh4u.org/2011/327/feed 0
匯出事件檢視器-轉換日期格式 https://blog.vic.mh4u.org/2011/318 https://blog.vic.mh4u.org/2011/318#respond Mon, 01 Aug 2011 16:05:44 +0000 http://blog.ns01.us/?p=318 閱讀全文 ]]>

上一篇的基礎下,我們繼續修改匯出的訊息成為我們要的格式。

' 作者:夢見草  製作日期:2011/08/01
' 網址: http://blog.ns01.us/2011/318
' -----------------------------------------------------------'
Option Explicit

Dim objFSO, objFolder, objFile, objWMI, objItem, objShell
Dim strComputer, strFileName, strFileOpen, strFolder, strPath
Dim intEvent, intNumberID, intRecordNum, colLoggedEvents
Dim intEventType, strLogType

' --------------------------------------------------------
' 設定匯出 資料夾位置 和 檔名
strComputer = "."
strFileName = "\pop.txt"
strFolder = "C:\MDlogs"
strPath = strFolder & strFileName

' 設定要抓取 事件檢視器裡的 Event ID
intNumberID = 521 ' Event ID Number
intEventType = 2
strLogType = "'Application'"
intRecordNum = 0

' -----------------------------------------------------
' Section to create folder and hold file.
' Create the File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")

' Check that the strFolder folder exists
If objFSO.FolderExists(strFolder) Then
Set objFolder = objFSO.GetFolder(strFolder)
Else
Set objFolder = objFSO.CreateFolder(strFolder)
WScript.Echo "Just created " & strFolder
End If

If objFSO.FileExists(strFolder & strFileName) Then
Set objFolder = objFSO.GetFolder(strFolder)
Else
Set objFile = objFSO.CreateTextFile(strFolder & strFileName)
Wscript.Echo "Just created " & strFolder & strFileName
End If
' --------------------------------------------------
' Two tiny but vital commands (Try script without)
set objFile = nothing
set objFolder = nothing

' ----------------------------------------------------
' Write the information to the file
Set strFileOpen = objFso.CreateTextFile(strPath, True)

' ----------------------------------------------------------
' WMI Core Section
Set objWMI = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate,(Security)}!\\" _
& strComputer & "\root\cimv2")
Set colLoggedEvents = objWMI.ExecQuery _
("Select * from Win32_NTLogEvent Where Logfile =" & strLogType)
'-------------------------------------------------------------------------------------------------
'ConvertWMIDateTime 功能:可轉換 WMI 的日期格式
'Name       : ConvertWMIDateTime -> Converts a WMI Date Time String into a String that can be formatted as a valid Date Time.
'Parameters : wmiDateTimeString  -> String containing a WMI Date Time String.
'Return     : ConvertWMIDateTime -> Returns a valid Date Time String otherwise returns a Blank String.
'-------------------------------------------------------------------------------------------------
Function ConvertWMIDateTime(wmiDateTimeString)
   Dim integerValues, i
   '-------------------------------------------------------------------------------------------------
   'Ensure the wmiDateTimeString contains a "+" or "-" character. If it doesn't it is not a valid WMI date time so exit.
   '-------------------------------------------------------------------------------------------------
   If InStr(1, wmiDateTimeString, "+", vbTextCompare) = 0 And _
      InStr(1, wmiDateTimeString, "-", vbTextCompare) = 0 Then
      ConvertWMIDateTime = ""
      Exit Function
   End If
   '-------------------------------------------------------------------------------------------------
   'Replace any "." or "+" or "-" characters in the wmiDateTimeString and check each character is a valid integer.
   '-------------------------------------------------------------------------------------------------
   integerValues = Replace(Replace(Replace(wmiDateTimeString, ".", ""), "+", ""), "-", "")
   For i = 1 To Len(integerValues)
      If Not IsNumeric(Mid(integerValues, i, 1)) Then
         ConvertWMIDateTime = ""
         Exit Function
      End If
   Next
   '-----------------------------------------------------------------------------------
   'Convert the WMI Date Time string to a String that can be formatted as a valid Date Time value.
   '-----------------------------------------------------------------------------------
   ConvertWMIDateTime = CDate(Mid(wmiDateTimeString, 5, 2)  & "/" & _
                              Mid(wmiDateTimeString, 7, 2)  & "/" & Left(wmiDateTimeString, 4) & " " & _
                              Mid(wmiDateTimeString, 9, 2)  & ":" & _
                              Mid(wmiDateTimeString, 11, 2) & ":" & _
                              Mid(wmiDateTimeString, 13, 2))
End Function

'-------------------------------------------------------------------------------------------------
'IsoDateTimeString 可轉換成 ISO 標準格式,用法 IsoDateTimeString(ConvertWMIDateTime)
'Name       : IsoDateTimeString -> Generate an ISO date and time string from a date/time value.
'Parameters : dateValue         -> Input date/time value.
'Return     : IsoDateTimeString -> Date and time parts of the input value in "yyyy-mm-dd hh:mm:ss" format.
'-------------------------------------------------------------------------------------------------
Function IsoDateTimeString(dateValue)
   IsoDateTimeString = IsoDateString (dateValue) & " " & IsoTimeString (dateValue)
End Function
'----------------------------------------------------------------------------------------------------------------------------
'Name       : IsoDateString -> Generate an ISO date string from a date/time value.
'Parameters : dateValue     -> Input date/time value.
'Return     : IsoDateString -> Date part of the input value in "yyyy-mm-dd" format.
'----------------------------------------------------------------------------------------------------------------------------
Function IsoDateString(dateValue)
   If IsDate(dateValue) Then
      IsoDateString = Right ("000" &  Year (dateValue), 4) & "-" & _
                      Right (  "0" & Month (dateValue), 2) & "-" & _
                      Right (  "0" &   Day (dateValue), 2)
   Else
      IsoDateString = "0000-00-00"
   End If
End Function
'----------------------------------------------------------------------------------------------------------------------------
'Name       : IsoTimeString -> Generate an ISO time string from a date/time value.
'Parameters : dateValue     -> Input date/time value.
'Return     : IsoTimeString -> Time part of the input value in "hh:mm:ss" format.
'----------------------------------------------------------------------------------------------------------------------------
Function IsoTimeString(dateValue)
   If IsDate(dateValue) Then
      IsoTimeString = Right ("0" &   Hour (dateValue), 2) & ":" & _
                      Right ("0" & Minute (dateValue), 2) & ":" & _
                      Right ("0" & Second (dateValue), 2)
   Else
      IsoTimeString = "00:00:00"
   End If
End Function

'-----------------------------------------------------------------------------------
' Next section loops through ID properties

For Each objItem in colLoggedEvents
If objItem.EventCode = intNumberID Then
If objItem.EventType = intEventType Then
strFileOpen.WriteLine IsoDateTimeString(ConvertWMIDateTime(objItem.TimeWritten)) & " " & "Msg:" & objItem.Message
intRecordNum = intRecordNum +1
End If
End If
Next

此 vb script 設計目地是用來匯出 MDaemon 單一事件的 log,將其匯出的訊息修改成像 linux log 一樣的精簡,方便 linux 系統裡面的 fail2ban 來分析。

簡單的講一下此程式的內容,底下的數值都是可以修改的

‘ 設定匯出 資料夾位置 和 檔名
strComputer = “.”
strFileName = “\pop.txt”
strFolder = “C:\MDlogs”
strPath = strFolder & strFileName

‘ 設定要抓取 事件檢視器裡的 Event ID
intNumberID = 521 ‘ Event ID Number
intEventType = 2
strLogType = “‘Application'”
intRecordNum = 0

另外這次花比較多的時間就是在研究怎樣將 WMI 的日期格式轉換成標準的日期格式,好方便其它程式分析,所幸網路上早有人有寫好的範例了,我不用再重新寫過。

程式碼說明

'-------------------------------------------------------------------------------------------------
'ConvertWMIDateTime 功能:可轉換 WMI 的日期格式
'Name       : ConvertWMIDateTime -> Converts a WMI Date Time String into a String that can be formatted as a valid Date Time.
'Parameters : wmiDateTimeString  -> String containing a WMI Date Time String.
'Return     : ConvertWMIDateTime -> Returns a valid Date Time String otherwise returns a Blank String.
'-------------------------------------------------------------------------------------------------
Function ConvertWMIDateTime(wmiDateTimeString)
   Dim integerValues, i
   '-------------------------------------------------------------------------------------------------
   'Ensure the wmiDateTimeString contains a "+" or "-" character. If it doesn't it is not a valid WMI date time so exit.
   '-------------------------------------------------------------------------------------------------
   If InStr(1, wmiDateTimeString, "+", vbTextCompare) = 0 And _
      InStr(1, wmiDateTimeString, "-", vbTextCompare) = 0 Then
      ConvertWMIDateTime = ""
      Exit Function
   End If
   '-------------------------------------------------------------------------------------------------
   'Replace any "." or "+" or "-" characters in the wmiDateTimeString and check each character is a valid integer.
   '-------------------------------------------------------------------------------------------------
   integerValues = Replace(Replace(Replace(wmiDateTimeString, ".", ""), "+", ""), "-", "")
   For i = 1 To Len(integerValues)
      If Not IsNumeric(Mid(integerValues, i, 1)) Then
         ConvertWMIDateTime = ""
         Exit Function
      End If
   Next
   '-----------------------------------------------------------------------------------
   'Convert the WMI Date Time string to a String that can be formatted as a valid Date Time value.
   '-----------------------------------------------------------------------------------
   ConvertWMIDateTime = CDate(Mid(wmiDateTimeString, 5, 2)  & "/" & _
                              Mid(wmiDateTimeString, 7, 2)  & "/" & Left(wmiDateTimeString, 4) & " " & _
                              Mid(wmiDateTimeString, 9, 2)  & ":" & _
                              Mid(wmiDateTimeString, 11, 2) & ":" & _
                              Mid(wmiDateTimeString, 13, 2))
End Function

以上的這段內容,最主要的功能就是將原本的 WMI 日期格式 20110730231040.000000+480
轉換成這樣的格式 2010/4/12 下午 09:39:19 雖然它已經很容易閲讀了,但是 fail2ban 就是不吃這樣的日期格式(因為它的4月份沒有寫成 04 ),所以我們還得有底下的程式碼幫忙

'-------------------------------------------------------------------------------------------------
'IsoDateTimeString 可轉換成 ISO 標準格式,用法 IsoDateTimeString(ConvertWMIDateTime)
'Name       : IsoDateTimeString -> Generate an ISO date and time string from a date/time value.
'Parameters : dateValue         -> Input date/time value.
'Return     : IsoDateTimeString -> Date and time parts of the input value in "yyyy-mm-dd hh:mm:ss" format.
'-------------------------------------------------------------------------------------------------
Function IsoDateTimeString(dateValue)
   IsoDateTimeString = IsoDateString (dateValue) & " " & IsoTimeString (dateValue)
End Function
'----------------------------------------------------------------------------------------------------------------------------
'Name       : IsoDateString -> Generate an ISO date string from a date/time value.
'Parameters : dateValue     -> Input date/time value.
'Return     : IsoDateString -> Date part of the input value in "yyyy-mm-dd" format.
'----------------------------------------------------------------------------------------------------------------------------
Function IsoDateString(dateValue)
   If IsDate(dateValue) Then
      IsoDateString = Right ("000" &  Year (dateValue), 4) & "-" & _
                      Right (  "0" & Month (dateValue), 2) & "-" & _
                      Right (  "0" &   Day (dateValue), 2)
   Else
      IsoDateString = "0000-00-00"
   End If
End Function
'----------------------------------------------------------------------------------------------------------------------------
'Name       : IsoTimeString -> Generate an ISO time string from a date/time value.
'Parameters : dateValue     -> Input date/time value.
'Return     : IsoTimeString -> Time part of the input value in "hh:mm:ss" format.
'----------------------------------------------------------------------------------------------------------------------------
Function IsoTimeString(dateValue)
   If IsDate(dateValue) Then
      IsoTimeString = Right ("0" &   Hour (dateValue), 2) & ":" & _
                      Right ("0" & Minute (dateValue), 2) & ":" & _
                      Right ("0" & Second (dateValue), 2)
   Else
      IsoTimeString = "00:00:00"
   End If
End Function

以上的程式碼的功能就是把日期格式轉換成標準的 ISO 日期格式也就是說 ConvertWMIDateTime 運算出來的日期格式,我們還要餵給 IsoDateTimeString 這個功能去運算。

所以最後、最重要的輸出就是這一行

Wscript.Echo IsoDateTimeString(ConvertWMIDateTime(objItem.TimeWritten)) & ” ” & “Msg:” & objItem.Message

objItem.TimeWritten 的日期格式是這樣 20020710113047.000000420
經過 ConvertWMIDateTime 的運算後會是這樣 2002/7/10 上午 11:30:47
再經過 IsoDateTimeString 的運算後會是這樣 2002-07-10 11:30:47

Wscript.Echo 是只在螢幕上顯示,不寫入檔案
strFileOpen.WriteLine 則會寫入指定的檔案

最後,這個程式所吐出來的訊息如下
2011-03-07 23:17:27 Msg:**** ALERT **** 1.15.229.228 gave false logon/password to POP server; user: abc@hot.com.com [EvSecurity]

然後我們要餵給 fail2ban 的 filter 最關鍵的一行就是底下這行了

failregex = Msg:\*\*\*\* ALERT \*\*\*\* gave false logon/password to POP server

[note]
參考資料: Script to Export Pervious Day Events Logs to CSV(輸出成標準日期格式)Tech NotesConverting WMI Dates to a Standard Date-Time FormatConvertWMIDateTimeExtract Data from windows Event Log抓取最後15分的 log
[/note]

參考程式碼:

Option Explicit
Const ForReading   = 1
Const ForWriting   = 2
Const ForAppending = 8
Dim objDictionary, objFSO, wshShell, wshNetwork
Dim scriptBaseName, scriptPath, scriptLogPath
Dim ipAddress, macAddress, item, messageType, message
On Error Resume Next
   Set objDictionary = NewDictionary
   Set objFSO        = CreateObject("Scripting.FileSystemObject")
   Set wshShell      = CreateObject("Wscript.Shell")
   Set wshNetwork    = CreateObject("Wscript.Network")
   scriptBaseName    = objFSO.GetBaseName(Wscript.ScriptFullName)
   scriptPath        = objFSO.GetFile(Wscript.ScriptFullName).ParentFolder.Path
   scriptLogPath     = scriptPath & "\" & IsoDateString(Now)
   If Err.Number <> 0 Then
      Wscript.Quit
   End If
On Error Goto 0
'----------------------------------------------------------------------------------------------------------------------------
'Main Processing Section
'----------------------------------------------------------------------------------------------------------------------------
On Error Resume Next
   PromptScriptStart
   ProcessScript
   If Err.Number <> 0 Then
      MsgBox BuildError("Processing Script"), vbCritical, scriptBaseName
      Wscript.Quit
   End If
   PromptScriptEnd
On Error Goto 0
'----------------------------------------------------------------------------------------------------------------------------
'Functions Processing Section
'----------------------------------------------------------------------------------------------------------------------------
'Name       : ProcessScript -> Primary Function that controls all other script processing.
'Parameters : None          ->
'Return     : None          ->
'----------------------------------------------------------------------------------------------------------------------------
Function ProcessScript
   Dim hostName, logName, startDateTime, endDateTime
   Dim events, eventNumbers, i
   hostName      = wshNetwork.ComputerName
   logName       = "Security"
   eventNumbers  = Array("672")
   startDateTime = DateAdd("n", -120, Now)
   '-------------------------------------------------------------------------------------------------------------------------
   'Query the event log for the eventID's within the specified event log name and date range.
   '-------------------------------------------------------------------------------------------------------------------------
   If Not QueryEventLog(events, hostName, logName, eventNumbers, startDateTime) Then
      Exit Function
   End If
   '-------------------------------------------------------------------------------------------------------------------------
   'Log the scripts results to the scripts
   '-------------------------------------------------------------------------------------------------------------------------
   For i = 0 To UBound(events)
      LogMessage events(i)
   Next
End Function
'----------------------------------------------------------------------------------------------------------------------------
'Name       : QueryEventLog -> Primary Function that controls all other script processing.
'Parameters : results       -> Input/Output : Variable assigned to an array of results from querying the event log.
'           : hostName      -> String containing the hostName of the system to query the event log on.
'           : logName       -> String containing the name of the Event Log to query on the system.
'           : eventNumbers  -> Array containing the EventID's (eventCode) to search for within the event log.
'           : startDateTime -> Date\Time containing the date to finish searching at.
'           : minutes       -> Integer containing the number of minutes to subtract from the startDate to begin the search.
'Return     : QueryEventLog -> Returns True if the event log was successfully queried otherwise returns False.
'----------------------------------------------------------------------------------------------------------------------------
Function QueryEventLog(results, hostName, logName, eventNumbers, startDateTime)
   Dim wmiDateTime, wmi, query, eventItems, eventItem
   Dim timeWritten, eventDate, eventTime, description
   Dim eventsDict, eventInfo, errorCount, i
   QueryEventLog = False
   errorCount    = 0
   If Not IsArray(eventNumbers) Then
      eventNumbers = Array(eventNumbers)
   End If
   '-------------------------------------------------------------------------------------------------------------------------
   'Construct part of the WMI Query to account for searching multiple eventID's
   '-------------------------------------------------------------------------------------------------------------------------
   query = "Select * from Win32_NTLogEvent Where Logfile = " & SQ(logName) & " And (EventCode = "
   For i = 0 To UBound(eventNumbers)
      query = query & SQ(eventNumbers(i)) & " Or EventCode = "
   Next
   On Error Resume Next
      Set eventsDict = NewDictionary
      If Err.Number <> 0 Then
         LogError "Creating Dictionary Object"
         Exit Function
      End If
      Set wmi = GetObject("winmgmts:{impersonationLevel=impersonate,(Security)}!\\" & hostName & "\root\cimv2")
      If Err.Number <> 0 Then
         LogError "Creating WMI Object to connect to " & DQ(hostName)
         Exit Function
      End If
      '----------------------------------------------------------------------------------------------------------------------
      'Create the "SWbemDateTime" Object for converting WMI Date formats. Supported in Windows Server 2003 & Windows XP.
      '----------------------------------------------------------------------------------------------------------------------
      Set wmiDateTime = CreateObject("WbemScripting.SWbemDateTime")
      If Err.Number <> 0 Then
         LogError "Creating " & DQ("WbemScripting.SWbemDateTime") & " object"
         Exit Function
      End If
      '----------------------------------------------------------------------------------------------------------------------
      'Build the WQL query and execute it.
      '----------------------------------------------------------------------------------------------------------------------
      wmiDateTime.SetVarDate startDateTime, True
      query          = Left(query, InStrRev(query, "'")) & ") And (TimeWritten >= " & SQ(wmiDateTime.Value) & ")"
      Set eventItems = wmi.ExecQuery(query)
      If Err.Number <> 0 Then
         LogError "Executing WMI Query " & DQ(query)
         Exit Function
      End If
      '----------------------------------------------------------------------------------------------------------------------
      'Convert the property values of Each event found to a comma seperated string and add it to the dictionary.
      '----------------------------------------------------------------------------------------------------------------------
      For Each eventItem In eventItems
         Do
            timeWritten = ""
            eventDate   = ""
            eventTime   = ""
            eventInfo   = ""
            timeWritten = ConvertWMIDateTime(eventItem.TimeWritten)
            eventDate   = FormatDateTime(timeWritten, vbShortDate)
            eventTime   = FormatDateTime(timeWritten, vbLongTime)
            eventInfo   = eventDate                          & ","
            eventInfo   = eventInfo & eventTime              & ","
            eventInfo   = eventInfo & eventItem.SourceName   & ","
            eventInfo   = eventInfo & eventItem.Type         & ","
            eventInfo   = eventInfo & eventItem.Category     & ","
            eventInfo   = eventInfo & eventItem.EventCode    & ","
            eventInfo   = eventInfo & eventItem.User         & ","
            eventInfo   = eventInfo & eventItem.ComputerName & ","
            description = eventItem.Message
            '------------------------------------------------------------------------------------------------------------------------
            'Ensure the event description is not blank.
            '------------------------------------------------------------------------------------------------------------------------
            If IsNull(description) Then
               description = "The event description cannot be found."
            End If
            description = Replace(description, vbCrLf, " ")
            eventInfo   = eventInfo & description
            '------------------------------------------------------------------------------------------------------------------------
            'Check if any errors occurred enumerating the event Information
            '------------------------------------------------------------------------------------------------------------------------
            If Err.Number <> 0 Then
               LogError "Enumerating Event Properties from the " & DQ(logName) & " event log on " & DQ(hostName)
               errorCount = errorCount + 1
               Err.Clear
               Exit Do
            End If
            '------------------------------------------------------------------------------------------------------------------------
            'Remove all Tabs and spaces.
            '------------------------------------------------------------------------------------------------------------------------
            eventInfo = Trim(Replace(eventInfo, vbTab, " "))
            Do While InStr(1, eventInfo, "  ", vbTextCompare) <> 0
               eventInfo = Replace(eventInfo, "  ", " ")
            Loop
            '------------------------------------------------------------------------------------------------------------------------
            'Add the Event Information to the Dictionary object if it doesn't exist.
            '------------------------------------------------------------------------------------------------------------------------
            If Not eventsDict.Exists(eventInfo) Then
               eventsDict(eventsDict.Count) = eventInfo
            End If
         Loop Until True
      Next
   On Error Goto 0
   If errorCount <> 0 Then
      Exit Function
   End If
   results       = eventsDict.Items
   QueryEventLog = True
End Function
'----------------------------------------------------------------------------------------------------------------------------
'Name       : ConvertWMIDateTime -> Converts a WMI Date Time String into a String that can be formatted as a valid Date Time.
'Parameters : wmiDateTimeString  -> String containing a WMI Date Time String.
'Return     : ConvertWMIDateTime -> Returns a valid Date Time String otherwise returns a Blank String.
'----------------------------------------------------------------------------------------------------------------------------
Function ConvertWMIDateTime(wmiDateTimeString)
   Dim integerValues, i
   '-------------------------------------------------------------------------------------------------------------------------
   'Ensure the wmiDateTimeString contains a "+" or "-" character. If it doesn't it is not a valid WMI date time so exit.
   '-------------------------------------------------------------------------------------------------------------------------
   If InStr(1, wmiDateTimeString, "+", vbTextCompare) = 0 And _
      InStr(1, wmiDateTimeString, "-", vbTextCompare) = 0 Then
      ConvertWMIDateTime = ""
      Exit Function
   End If
   '-------------------------------------------------------------------------------------------------------------------------
   'Replace any "." or "+" or "-" characters in the wmiDateTimeString and check each character is a valid integer.
   '-------------------------------------------------------------------------------------------------------------------------   
   integerValues = Replace(Replace(Replace(wmiDateTimeString, ".", ""), "+", ""), "-", "")
   For i = 1 To Len(integerValues)
      If Not IsNumeric(Mid(integerValues, i, 1)) Then
         ConvertWMIDateTime = ""
         Exit Function
      End If
   Next
   '-------------------------------------------------------------------------------------------------------------------------
   'Convert the WMI Date Time string to a String that can be formatted as a valid Date Time value.
   '-------------------------------------------------------------------------------------------------------------------------
   ConvertWMIDateTime = CDate(Mid(wmiDateTimeString, 5, 2)  & "/" & _
                              Mid(wmiDateTimeString, 7, 2)  & "/" & Left(wmiDateTimeString, 4) & " " & _
                              Mid(wmiDateTimeString, 9, 2)  & ":" & _
                              Mid(wmiDateTimeString, 11, 2) & ":" & _
                              Mid(wmiDateTimeString, 13, 2))
End Function
'----------------------------------------------------------------------------------------------------------------------------
'Name       : NewDictionary -> Creates a new dictionary object.
'Parameters : None          ->
'Return     : NewDictionary -> Returns a dictionary object.
'----------------------------------------------------------------------------------------------------------------------------
Function NewDictionary
   Dim dict
   Set dict          = CreateObject("scripting.Dictionary")
   dict.CompareMode  = vbTextCompare
   Set NewDictionary = dict
End Function
'----------------------------------------------------------------------------------------------------------------------------
'Name       : SQ          -> Places single quotes around a string
'Parameters : stringValue -> String containing the value to place single quotes around
'Return     : SQ          -> Returns a single quoted string
'----------------------------------------------------------------------------------------------------------------------------
Function SQ(ByVal stringValue)
   If VarType(stringValue) = vbString Then
      SQ = "'" & stringValue & "'"
   End If
End Function
'----------------------------------------------------------------------------------------------------------------------------
'Name       : DQ          -> Place double quotes around a string and replace double quotes
'           :             -> within the string with pairs of double quotes.
'Parameters : stringValue -> String value to be double quoted
'Return     : DQ          -> Double quoted string.
'----------------------------------------------------------------------------------------------------------------------------
Function DQ (ByVal stringValue)
   If stringValue <> "" Then
      DQ = """" & Replace (stringValue, """", """""") & """"
   Else
      DQ = """"""
   End If
End Function
'----------------------------------------------------------------------------------------------------------------------------
'Name       : IsoDateTimeString -> Generate an ISO date and time string from a date/time value.
'Parameters : dateValue         -> Input date/time value.
'Return     : IsoDateTimeString -> Date and time parts of the input value in "yyyy-mm-dd hh:mm:ss" format.
'----------------------------------------------------------------------------------------------------------------------------
Function IsoDateTimeString(dateValue)
   IsoDateTimeString = IsoDateString (dateValue) & " " & IsoTimeString (dateValue)
End Function
'----------------------------------------------------------------------------------------------------------------------------
'Name       : IsoDateString -> Generate an ISO date string from a date/time value.
'Parameters : dateValue     -> Input date/time value.
'Return     : IsoDateString -> Date part of the input value in "yyyy-mm-dd" format.
'----------------------------------------------------------------------------------------------------------------------------
Function IsoDateString(dateValue)
   If IsDate(dateValue) Then
      IsoDateString = Right ("000" &  Year (dateValue), 4) & "-" & _
                      Right (  "0" & Month (dateValue), 2) & "-" & _
                      Right (  "0" &   Day (dateValue), 2)
   Else
      IsoDateString = "0000-00-00"
   End If
End Function
'----------------------------------------------------------------------------------------------------------------------------
'Name       : IsoTimeString -> Generate an ISO time string from a date/time value.
'Parameters : dateValue     -> Input date/time value.
'Return     : IsoTimeString -> Time part of the input value in "hh:mm:ss" format.
'----------------------------------------------------------------------------------------------------------------------------
Function IsoTimeString(dateValue)
   If IsDate(dateValue) Then
      IsoTimeString = Right ("0" &   Hour (dateValue), 2) & ":" & _
                      Right ("0" & Minute (dateValue), 2) & ":" & _
                      Right ("0" & Second (dateValue), 2)
   Else
      IsoTimeString = "00:00:00"
   End If
End Function
'----------------------------------------------------------------------------------------------------------------------------
'Name       : LogMessage -> Writes a message to a log file.
'Parameters : logPath    -> String containing the full folder path and file name of the Log file without with file extension.
'           : message    -> String containing the message to include in the log message.
'Return     : None       -> 
'----------------------------------------------------------------------------------------------------------------------------
Function LogMessage(message)
   If Not LogToCentralFile(scriptLogPath & ".log", IsoDateTimeString(Now) & "," & message) Then
      Exit Function
   End If
End Function
'----------------------------------------------------------------------------------------------------------------------------
'Name       : LogError -> Writes an error message to a log file.
'Parameters : logPath  -> String containing the full folder path and file name of the Log file without with file extension.
'           : message  -> String containing a description of the event that caused the error to occur.
'Return     : None       -> 
'----------------------------------------------------------------------------------------------------------------------------
Function LogError(message)
   If Not LogToCentralFile(scriptLogPath & ".err", IsoDateTimeString(Now) & "," & BuildError(message)) Then
      Exit Function
   End If
End Function
'----------------------------------------------------------------------------------------------------------------------------
'Name      : BuildError -> Builds a string of information relating to the error object.
'Parameters: message    -> String containnig the message that relates to the process that caused the error.
'Return    : BuildError -> Returns a string relating to error object.   
'----------------------------------------------------------------------------------------------------------------------------
Function BuildError(message)
   BuildError = "Error " & Err.Number & " (Hex " & Hex(Err.Number) & ") " & message & ". " & Err.Description
End Function
'----------------------------------------------------------------------------------------------------------------------------
'Name       : LogToCentralFile -> Attempts to Appends information to a central file.
'Parameters : logSpec          -> Folder path, file name and extension of the central log file to append to.
'           : message          -> String to include in the central log file
'Return     : LogToCentralFile -> Returns True if Successfull otherwise False.
'----------------------------------------------------------------------------------------------------------------------------
Function LogToCentralFile(logSpec, message)
   Dim attempts, objLogFile
   LogToCentralFile = False
   '-------------------------------------------------------------------------------------------------------------------------
   'Attempt to append to the central log file up to 10 times, as it may be locked by some other system.
   '-------------------------------------------------------------------------------------------------------------------------
   attempts = 0
   Do
      On Error Resume Next
         Set objLogFile = objFSO.OpenTextFile(logSpec, ForAppending, True)
         If Err.Number = 0 Then
            objLogFile.WriteLine message
            objLogFile.Close
            LogToCentralFile = True
            Exit Function
         End If
      On Error Goto 0
      Randomize
      Wscript.sleep 1000 + Rnd * 100
      attempts = attempts + 1
   Loop Until attempts >= 10
End Function
'----------------------------------------------------------------------------------------------------------------------------
'Name       : PromptScriptStart -> Prompt when script starts.
'Parameters : None
'Return     : None
'----------------------------------------------------------------------------------------------------------------------------
Function PromptScriptStart
   MsgBox "Now processing the " & DQ(Wscript.ScriptName) & " script.", vbInformation, scriptBaseName
End Function
'----------------------------------------------------------------------------------------------------------------------------
'Name       : PromptScriptEnd -> Prompt when script has completed.
'Parameters : None
'Return     : None
'----------------------------------------------------------------------------------------------------------------------------
Function PromptScriptEnd
   MsgBox "The " & DQ(Wscript.ScriptName) & " script has completed successfully.", vbInformation, scriptBaseName
End Function
'----------------------------------------------------------------------------------------------------------------------------

strComputer = "." 
Set wbemServices = Getobject("winmgmts:\\" & strComputer)
Set wbemObjectSet = wbemServices.InstancesOf("Win32_NTLogEvent") 


' ----------------------------------------------------------
'Name       : ConvertWMIDateTime -> Converts a WMI Date Time String into a String that can be formatted as a valid Date Time.
'Parameters : wmiDateTimeString  -> String containing a WMI Date Time String.
'Return     : ConvertWMIDateTime -> Returns a valid Date Time String otherwise returns a Blank String.
'-------------------------------------------------------------------------------------------------
Function ConvertWMIDateTime(wmiDateTimeString)
   Dim integerValues, i
   '-------------------------------------------------------------------------------------------------
   'Ensure the wmiDateTimeString contains a "+" or "-" character. If it doesn't it is not a valid WMI date time so exit.
   '-------------------------------------------------------------------------------------------------
   If InStr(1, wmiDateTimeString, "+", vbTextCompare) = 0 And _
      InStr(1, wmiDateTimeString, "-", vbTextCompare) = 0 Then
      ConvertWMIDateTime = ""
      Exit Function
   End If
   '-------------------------------------------------------------------------------------------------
   'Replace any "." or "+" or "-" characters in the wmiDateTimeString and check each character is a valid integer.
   '-------------------------------------------------------------------------------------------------
   integerValues = Replace(Replace(Replace(wmiDateTimeString, ".", ""), "+", ""), "-", "")
   For i = 1 To Len(integerValues)
      If Not IsNumeric(Mid(integerValues, i, 1)) Then
         ConvertWMIDateTime = ""
         Exit Function
      End If
   Next
   '-----------------------------------------------------------------------------------
   'Convert the WMI Date Time string to a String that can be formatted as a valid Date Time value.
   '-----------------------------------------------------------------------------------
   ConvertWMIDateTime = CDate(Mid(wmiDateTimeString, 5, 2)  & "/" & _
                              Mid(wmiDateTimeString, 7, 2)  & "/" & Left(wmiDateTimeString, 4) & " " & _
                              Mid(wmiDateTimeString, 9, 2)  & ":" & _
                              Mid(wmiDateTimeString, 11, 2) & ":" & _
                              Mid(wmiDateTimeString, 13, 2))
End Function


'Name       : IsoDateTimeString -> Generate an ISO date and time string from a date/time value.
'Parameters : dateValue         -> Input date/time value.
'Return     : IsoDateTimeString -> Date and time parts of the input value in "yyyy-mm-dd hh:mm:ss" format.
'----------------------------------------------------------------------------------------------------------------------------
Function IsoDateTimeString(dateValue)
   IsoDateTimeString = IsoDateString (dateValue) & " " & IsoTimeString (dateValue)
End Function
'----------------------------------------------------------------------------------------------------------------------------
'Name       : IsoDateString -> Generate an ISO date string from a date/time value.
'Parameters : dateValue     -> Input date/time value.
'Return     : IsoDateString -> Date part of the input value in "yyyy-mm-dd" format.
'----------------------------------------------------------------------------------------------------------------------------
Function IsoDateString(dateValue)
   If IsDate(dateValue) Then
      IsoDateString = Right ("000" &  Year (dateValue), 4) & "-" & _
                      Right (  "0" & Month (dateValue), 2) & "-" & _
                      Right (  "0" &   Day (dateValue), 2)
   Else
      IsoDateString = "0000-00-00"
   End If
End Function
'----------------------------------------------------------------------------------------------------------------------------
'Name       : IsoTimeString -> Generate an ISO time string from a date/time value.
'Parameters : dateValue     -> Input date/time value.
'Return     : IsoTimeString -> Time part of the input value in "hh:mm:ss" format.
'----------------------------------------------------------------------------------------------------------------------------
Function IsoTimeString(dateValue)
   If IsDate(dateValue) Then
      IsoTimeString = Right ("0" &   Hour (dateValue), 2) & ":" & _
                      Right ("0" & Minute (dateValue), 2) & ":" & _
                      Right ("0" & Second (dateValue), 2)
   Else
      IsoTimeString = "00:00:00"
   End If
End Function


'-----------------------------------------------------------------------------------


For Each wbemObject In wbemObjectSet
    WScript.Echo "Log File:        " & wbemObject.LogFile        & vbCrLf & _
                 "Record Number:   " & wbemObject.RecordNumber   & vbCrLf & _
                 "Type:            " & wbemObject.Type           & vbCrLf & _
                 "Time Generated:  " & IsoDateTimeString(ConvertWMIDateTime(wbemObject.TimeGenerated))  & vbCrLf & _
                 "Source:          " & wbemObject.SourceName     & vbCrLf & _
                 "Category:        " & wbemObject.Category       & vbCrLf & _
                 "Category String: " & wbemObject.CategoryString & vbCrLf & _
                 "Event:           " & wbemObject.EventCode      & vbCrLf & _
                 "User:            " & wbemObject.User           & vbCrLf & _
                 "Computer:        " & wbemObject.ComputerName   & vbCrLf & _
                 "Message:         " & wbemObject.Message        & vbCrLf
Next

↑匯出事件檢視器裡所有的內容,並轉換日期格式為 ISO 標準格式

]]>
https://blog.vic.mh4u.org/2011/318/feed 0
匯出事件檢視器 https://blog.vic.mh4u.org/2011/306 https://blog.vic.mh4u.org/2011/306#respond Sun, 31 Jul 2011 10:51:45 +0000 http://blog.ns01.us/?p=306 閱讀全文 ]]>

Windows 底下有個事件檢視器,記錄著系統上所有的 log ,若想要將單獨的某一事件分離出來另存為一個檔案的話,是否能做到?

可以的,這時就需要 WMI (Windows Management Instrumentation) 但 WMI 並不能直接使用,你必須選擇一種支援WMI的腳本語言(VBScript, Microsoft JScript, Perl, ASP, .Net written in C#, Visual Basic .NET, or J#)寫個小程式去呼叫 WMI 裡的功能才行。

此網頁有完整的教學,教你怎樣獨立出某一個 log

' EventLogFSO.vbs
' Sample VBScript to write event log data to text file
' Author Guy Thomas http://computerperformance.co.uk/
' Version 1.7 - May 2006
' -----------------------------------------------------------'
Option Explicit

Dim objFSO, objFolder, objFile, objWMI, objItem, objShell
Dim strComputer, strFileName, strFileOpen, strFolder, strPath
Dim intEvent, intNumberID, intRecordNum, colLoggedEvents
Dim intEventType, strLogType

' --------------------------------------------------------
' Set the folder and file name
strComputer = "."
strFileName = "\Event680.txt"
strFolder = "e:\logs"
strPath = strFolder & strFileName

' Set numbers
intNumberID = 680 ' Event ID Number
intEventType = 4
strLogType = "'Security'"
intRecordNum = 0

' -----------------------------------------------------
' Section to create folder and hold file.
' Create the File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")

' Check that the strFolder folder exists
If objFSO.FolderExists(strFolder) Then
Set objFolder = objFSO.GetFolder(strFolder)
Else
Set objFolder = objFSO.CreateFolder(strFolder)
WScript.Echo "Just created " & strFolder
End If

If objFSO.FileExists(strFolder & strFileName) Then
Set objFolder = objFSO.GetFolder(strFolder)
Else
Set objFile = objFSO.CreateTextFile(strFolder & strFileName)
Wscript.Echo "Just created " & strFolder & strFileName
End If
' --------------------------------------------------
' Two tiny but vital commands (Try script without)
set objFile = nothing
set objFolder = nothing

' ----------------------------------------------------
' Write the information to the file
Wscript.Echo " Press OK and Wait 30 seconds (ish)"
Set strFileOpen = objFso.CreateTextFile(strPath, True)

' ----------------------------------------------------------
' WMI Core Section
Set objWMI = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate,(Security)}!\\" _
& strComputer & "\root\cimv2")
Set colLoggedEvents = objWMI.ExecQuery _
("Select * from Win32_NTLogEvent Where Logfile =" & strLogType)

' ----------------------------------------------------------
' Next section loops through ID properties

For Each objItem in colLoggedEvents
If objItem.EventCode = intNumberID Then
If objItem.EventType = intEventType Then
strFileOpen.WriteLine("Category: " & objItem.Category _
& " string " & objItem.CategoryString)
strFileOpen.WriteLine("ComputerName: " & objItem.ComputerName)
strFileOpen.WriteLine("Logfile: " & objItem.Logfile _
& " source " & objItem.SourceName)
strFileOpen.WriteLine("EventCode: " & objItem.EventCode)
strFileOpen.WriteLine("EventType: " & objItem.EventType)
strFileOpen.WriteLine("Type: " & objItem.Type)
strFileOpen.WriteLine("User: " & objItem.User)
strFileOpen.WriteLine("Message: " & objItem.Message)
strFileOpen.WriteLine (" ")
intRecordNum = intRecordNum +1
End If
End If
Next

' Confirms the script has completed and opens the file
Set objShell = CreateObject("WScript.Shell")
objShell.run ("Explorer" &" " & strPath & "\" )

WScript.Quit

' End of Guy's FSO sample VBScript

簡單說明一下其內容

strFileName = “\Event680.txt”
strFolder = “e:\logs”
intNumberID = 680 ‘ Event ID Number
intEventType = 4
strLogType = “‘Security'”

以上是幾個你要修改的參數,分別是檔名、資料夾位置、Event ID和 Event Type
Event Type
1 = Other 其它
2 = Warning 警告
3 = Information 資訊
4 = Security Success 稽核成功
5 = Security Failure 稽核失敗

LogType 選項基本有三種, Security (安全性)、 Application(應用程式)、System(系統)

另外,該篇文章提到叫我們下載安裝 WMI Monitor 其實不必下載安裝上面的這個 .vbs 檔也能運作,因為 WMI Services 在系統有內建 (Windows 2000、Windows XP 和 Windows Server 2003 以上都有)

然後我依照上面的範例修改成我要的內容

' EventLogFSO.vbs
' Sample VBScript to write event log data to text file
' Author Guy Thomas http://computerperformance.co.uk/
' Version 1.7 - May 2006
' -----------------------------------------------------------'
Option Explicit

Dim objFSO, objFolder, objFile, objWMI, objItem, objShell
Dim strComputer, strFileName, strFileOpen, strFolder, strPath
Dim intEvent, intNumberID, intRecordNum, colLoggedEvents
Dim intEventType, strLogType

' --------------------------------------------------------
' Set the folder and file name
strComputer = "."
strFileName = "\Event521.txt"
strFolder = "c:\logs"
strPath = strFolder & strFileName

' Set numbers
intNumberID = 521 ' Event ID Number
intEventType = 2
strLogType = "'Application'"
intRecordNum = 0

' -----------------------------------------------------
' Section to create folder and hold file.
' Create the File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")

' Check that the strFolder folder exists
If objFSO.FolderExists(strFolder) Then
Set objFolder = objFSO.GetFolder(strFolder)
Else
Set objFolder = objFSO.CreateFolder(strFolder)
WScript.Echo "Just created " & strFolder
End If

If objFSO.FileExists(strFolder & strFileName) Then
Set objFolder = objFSO.GetFolder(strFolder)
Else
Set objFile = objFSO.CreateTextFile(strFolder & strFileName)
Wscript.Echo "Just created " & strFolder & strFileName
End If
' --------------------------------------------------
' Two tiny but vital commands (Try script without)
set objFile = nothing
set objFolder = nothing

' ----------------------------------------------------
' Write the information to the file
'Wscript.Echo " Press OK and Wait 30 seconds (ish)"
Set strFileOpen = objFso.CreateTextFile(strPath, True)

' ----------------------------------------------------------
' WMI Core Section
Set objWMI = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate,(Security)}!\\" _
& strComputer & "\root\cimv2")
Set colLoggedEvents = objWMI.ExecQuery _
("Select * from Win32_NTLogEvent Where Logfile =" & strLogType)
' ----------------------------------------------------------
' Next section loops through ID properties

For Each objItem in colLoggedEvents
If objItem.EventCode = intNumberID Then
If objItem.EventType = intEventType Then
strFileOpen.WriteLine("TimeWritten:" & objItem.TimeWritten)
strFileOpen.WriteLine("Message: " & objItem.Message)
strFileOpen.WriteLine (" ")
intRecordNum = intRecordNum +1
End If
End If
Next

' Confirms the script has completed and opens the file
Set objShell = CreateObject("WScript.Shell")

WScript.Quit

' End of Guy's FSO sample VBScript

修改的內容主要是拿掉了一些我不需要的訊息顯示,並另外的加上了一個時間的訊息。

時間訊息
strFileOpen.WriteLine(“TimeWritten:” & objItem.TimeWritten)

執行方法很簡單,用滑鼠點擊該 .vbs 檔或下指令 cscript xx.vbs 即可
執行一次它就會匯出現有的log檔, 執行第二次時,則會蓋掉原有的內容

[note]
參考資料:WMI詳解1WMI詳解2WMI指令碼高手不完全手冊以程式透過WMI讀取Windows系統事件日誌[ASP.NET] 讀取事件檢視器 EventLog事件檢視器的記錄檔備份WMI 診斷公用程式如何提取2003关机日志几个 WMI 的例子
[/note]

]]>
https://blog.vic.mh4u.org/2011/306/feed 0
proftpd https://blog.vic.mh4u.org/2011/75 https://blog.vic.mh4u.org/2011/75#respond Fri, 13 May 2011 14:12:24 +0000 http://blog.ns01.us/?p=75 閱讀全文 ]]> proftpd 教學


寫作環境: debian 5 lenny 64bit

安裝指令:

[cmd]aptitude install proftpd[/cmd]

安裝過程中它會問你啟動模式,請選擇standalone 設定上會比較容易,若你選擇了另一種啟動模式inetd的話,那麼請確認你對這種模式相當熟悉再選擇它。

proftpd 是個功能強大的 ftp server,可細部調節的地方很多,它所有的設定全在此檔內 /etc/proftpd/proftpd.conf 可以點我下載參考設定檔

底下針對常用的安全性設定說明一下,其它的細節請參閱上面的參考設定檔

Port				25
#設定啟動時要監聽哪個 port

PassivePorts                  49152 65534
#設定被動式連線的 port 位的範圍

DefaultRoot			~
#將使用者困在他們的家目錄,有底下設定參考
#指定特定使用者登入後的根目錄。
#DefaultRoot /var/www webmaster
#設定每個使用者登入後的根目錄 ! 後為排除的使用者
#DefaultRoot /var/ftp !admin
#限制每個使用者都登入在自己的家目錄(”!” 後為排除的使用者)
#DefaultRoot ~ !admin
#DefaultRoot ~,!www-data,/var/www www-data
#↑上面這行的意思是,將所有使用者困在家目錄裡,除了www-data 群組,這群組被限制在 /var/www 這個目錄裡

#MaxClients 5 "Sorry, max %m users -- try again later"
#設定最多允許多少個使用者(不同IP)登入,後面為超過數量時顯示的訊息。

#MaxClientsPerHost 2
#設定最多允許多少個使用者(不同IP)登入,後面為超過數量時顯示的訊息。

#MaxLoginAttempts 3
# 設定使用者嘗試登入失敗後幾次斷線。

AllowStoreRestart on
#AllowStoreRestart: 允許上傳續傳。

AllowOverwrite			on
#設定是否可以覆寫檔案,預設是 off,可以用於整體設定與目錄區段設定

		#檔案刪除限制
DenyAll			#全部都不行
#Allowuser eric david	#僅允許 2 人

改 port位 ,這與防火牆有關,若你不知你 port 開啟的範圍,你就不知防火牆該打什麼洞

SSL 加密連線

使用加密連線,需要產生 SSL 憑證

debian 未自帶 ssl-cert 所以我們得先安裝這個套件

[cmd]aptitude install ssl-cert[/cmd]

再下此指令產生一個憑證
[cmd]openssl req -x509 -newkey rsa:1024 -keyout /etc/ssl/private/proftpd.key -out /etc/ssl/certs/proftpd.crt -nodes -days 3650[/cmd]

↑下此指令後,需回答一些問題,然後會產生一個10年有效的憑證,檔案分別位於這裡 /etc/ssl/private/proftpd.key 和這裡 /etc/ssl/certs/proftpd.crt

開啟 ssl 連線功能,編輯 proftpd.conf
[cmd]vim /etc/proftpd/proftpd.conf[/cmd]

找到底下這行,將前面的 # 號拿掉

#Include /etc/proftpd/tls.conf

編輯 tls.conf 檔

[cmd]vim /etc/proftpd/tls.conf[/cmd]

將底下的內容貼至 <IfModule mod_tls.c> 和 </IfModule> 之間

TLSEngine on
TLSLog /var/log/proftpd-tls.log
TLSProtocol SSLv23
TLSRequired ctrl
TLSRSACertificateFile /etc/ssl/certs/proftpd.crt
TLSRSACertificateKeyFile /etc/ssl/private/proftpd.key
TLSVerifyClient off

然後重啟 proftpd
[cmd]/etc/init.d/proftpd restart[/cmd]

然後請用 Filezilla 在連線的地方伺服器種類,請選擇  FTPES – 透過外顯式 TLS/SSL 的 FTP 這樣就可以了。

[note]參考資料:proftpd官網Damon水果報報、[/note]

]]>
https://blog.vic.mh4u.org/2011/75/feed 0