Enterprise IT Solutions/Microsoft

Active Directory 계정 생성/삭제 이벤트 기록 스크립트

iseop 2023. 6. 17. 23:59   인쇄용 버전

1. 계정 생성 (4720)

# Capture user account creation (4720)

$str = wevtutil.exe qe Security /q:"*[System[(EventID=4720)]]" /rd:true /c:1 /f:XML | Out-String

$stis = $str.IndexOf("SystemTime")+12
$stie = $str.IndexOf("'/>", $stis)
$st = $str.Substring($stis, $stie-$stis)

$unis = $str.IndexOf("TargetUserName")+16
$unie = $str.IndexOf("</Data>", $unis)
$un = $str.Substring($unis, $unie-$unis)

$snis = $str.IndexOf("SubjectUserName")+17
$snie = $str.IndexOf("</Data>", $snis)
$sn = $str.Substring($snis, $snie-$snis)

$out = $st+" "+$sn+" CREATE "+$un
$out | out-file -append c:\log.txt

 

2. 계정 삭제 (4726)

# Capture user account creation (4726)

$str = wevtutil.exe qe Security /q:"*[System[(EventID=4726)]]" /rd:true /c:1 /f:XML | Out-String

$stis = $str.IndexOf("SystemTime")+12
$stie = $str.IndexOf("'/>", $stis)
$st = $str.Substring($stis, $stie-$stis)

$unis = $str.IndexOf("TargetUserName")+16
$unie = $str.IndexOf("</Data>", $unis)
$un = $str.Substring($unis, $unie-$unis)

$snis = $str.IndexOf("SubjectUserName")+17
$snie = $str.IndexOf("</Data>", $snis)
$sn = $str.Substring($snis, $snie-$snis)

$out = $st+" "+$sn+" DELETE "+$un
$out | out-file -append c:\log.txt

 

두 스크립트를 event-triggered task로 만들어서 해당 이벤트가 생성될 때마다 실행되도록 하면 결과가 텍스트 파일에 기록된다.  단, 속도가 느리기 때문에 1초 이내에 여러 이벤트가 발생할 경우 제대로 기록되지 않는다.

 

WEVTUTIL.EXE 파라미터 설명

1. /rd:true

Reverse direction의 약자로, 최근 이벤트를 먼저 출력하도록 만든다.

 

2. /c:1

상위 1개만 출력하도록 한다.

 

3. /f:XML

XML로 출력하도록 한다.

 

4. /q:*[System[(EventID=4726)]]

Structured query가 아닌 단순 쿼리를 입력받는다.

이를 작성하기 힘들면 이벤트 뷰어에서 필터를 설정한 뒤 XML탭에서 복사하면 된다.

 

파워셸 String 객체 메소드와 관련 cmdlet 설명

1. out-string

앞선 명령어의 출력을 System.Object.String 타입으로 변환한다.

변환하지 않으면 출력이 System.Object 타입이 된다.

변환하면 String의 메소드를 사용할 수 있다.

 

2. indexof("string", [int index])

string이 시작하는 부분의 인덱스를 반환한다.

index를 지정하면 해당 인덱스 이후에 나타나는 string의 인덱스를 반환한다.

 

3. substring(int start, int end)

start부터 end까지의 string을 반환한다.