::NPTEAM:: Network Programer Team

검색 :
RSS 구독 : 글 / 댓글 / 트랙백 / 글+트랙백

[WMI] 프로세스 (시작 / 종료) 이벤트 발생시 프로그램 실행하기

프로세스 시작/종료 이벤트시에 하고 싶은 것들이 많다.
서버 프로그래머라면 서버 프로그램이 이유없이 죽을때 시간 및 Log를 남길 수도 있고,
프로그램이 죽으면, 다시 시작하도록 설정해서 24시간 스스로 유지되길 바라는 경우가 있다.
이럴때 윈도우에서 실행가능한 VBS(WMI)스크립트로 간단하게 관리해 보자.

아래의 스크립트는 다음과 같은 작동을 합니다.
1. 무한 루프를 반복하면서 1초마다 프로세스가 생성되거나 삭제되는 이벤트를 감시한다.
2. notepad.exe 프로세스가 생성되면, calc.exe를 실행합니다.
3. notepad.exe 프로세스가 삭제되면, calc.exe를 종료합니다.


Option Explicit

Dim strComputer
strComputer = "."

'기본 Object 가져오기
Dim Shell : Set Shell = WScript.CreateObject("WScript.Shell")
Dim FSO : Set FSO = CreateObject("Scripting.FileSystemObject")
Dim objWMIService : Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Dim colMonitorCreateProcessesEvent : Set colMonitorCreateProcessesEvent = objWMIService.ExecNotificationQuery("select * from __InstanceCreationEvent within 1 where TargetInstance isa 'Win32_Process'" )
Dim colMonitorDeleteProcessesEvent : Set colMonitorDeleteProcessesEvent = objWMIService.ExecNotificationQuery("select * from __InstanceDeletionEvent within 1 where TargetInstance isa 'Win32_Process'" )

'CMD 윈도우 98에서도 적용 가능하게 COMSPEC으로 가져온다.
Dim COMSPEC : COMSPEC = Shell.ExpandEnvironmentStrings("%comspec%")

'메인 함수 실행
Call MainFunction()


Sub MainFunction
	'중복 실행 방지 코드 - vbs 파일명을 입력합니다.
	If( IsExistSameVBS( "ProcessEvent.vbs" ) ) Then
		Wscript.Quit
	End If
	
	Do While True
		Call ProcessCreatedEvent()
		Call ProcessDeletedEvent()
		Wscript.Sleep( 1000 )
	Loop
	
	Wscript.Quit
End Sub


Sub ProcessCreatedEvent
	'프로세스 시작시
	
	'모니터링할 프로세스 이름
	Dim strMonitorProcessName : strMonitorProcessName = "notepad.exe"
	
	'실행할 파일
	Dim strExecuteFilePath : strExecuteFilePath = "C:\Windows\system32"
	Dim strExecuteFileName : strExecuteFileName = "calc.exe"
	
	'프로세스 시작 이벤트 검사
	Dim objLastestProcess : Set objLastestProcess = colMonitorCreateProcessesEvent.NextEvent
	If( StrComp(Lcase(objLastestProcess.TargetInstance.Name), Lcase(strMonitorProcessName), 1 ) = 0 ) Then
		'프로그램 실행
		Call ExecuteOnce( strExecuteFilePath, strExecuteFileName, "" )
	End If
End Sub


Sub ProcessDeletedEvent
	'프로세스 종료시
	
	'모니터링할 프로세스 이름
	Dim strMonitorProcessName : strMonitorProcessName = "Notepad.exe"
	
	'종료할 프로세스 이름
	Dim strKillProcessName : strKillProcessName = "calc.exe"
	
	'프로세스 종료 이벤트 검사
	Dim objLastestProcess : Set objLastestProcess = colMonitorDeleteProcessesEvent.NextEvent
	If( StrComp(Lcase(objLastestProcess.TargetInstance.Name), Lcase(strMonitorProcessName), 1) = 0 ) Then
		'프로세스 종료
		Call KillProcess( strKillProcessName )
	End If
End Sub


Sub ExecuteFile (strFileFullPath, Arguments)
	If( FSO.FileExists( strFileFullPath ) ) Then
		Shell.Run COMSPEC & " /c " & strFileFullPath & Arguments & " & Exit", 0
	Else
		Shell.Popup strFileFullPath & " 을(를) 찾을 수 없습니다.", 3, "File Dose not exist", 48
		Wscript.Quit
	End If
End Sub


Function IsExistProcess( strProcessName )
	IsExistProcess = False
	
	Dim colProcessList, objProcess
	Set colProcessList = objWMIService.ExecQuery( "select * from Win32_Process" )
	For Each objProcess in colProcessList
		If( StrComp(Lcase(strProcessName), Lcase(objProcess.Name), 1) = 0 ) Then
			IsExistProcess = True
		End If
	Next
End Function


Sub ExecuteOnce( strFilePath, strFileName, Arguments )
	If( IsExistProcess( strFileName ) = False ) Then
		Call ExecuteFile( strFilePath & "\" & strFileName, Arguments )
		Wscript.Sleep 2000
	End If
End Sub


Sub KillProcess( strProcessName )
	Dim colProcessList, objProcess
	Set colProcessList = objWMIService.ExecQuery( "select * from Win32_Process" )
	For Each objProcess in colProcessList
		If( StrComp(Lcase(strProcessName), Lcase(objProcess.Name), 1) = 0 ) Then
			objProcess.Terminate()
		End If
	Next
End Sub


Function IsExistSameVBS( strFileName )
	IsExistSameVBS = False
	Dim nSameVBSCount : nSameVBSCount = 0
	
	Dim colProcessList, objProcess
	Set colProcessList = objWMIService.ExecQuery("SELECT * FROM Win32_Process WHERE Name = 'wscript.exe' OR Name = 'cscript.exe'")
	For Each objProcess in colProcessList
		If InStr( Lcase(objProcess.CommandLine), Lcase(strFileName) ) Then
			nSameVBSCount = nSameVBSCount + 1
		End If
	Next
	
	If( nSameVBSCount > 1 ) Then
		IsExistSameVBS = True
		Wscript.echo strFileName & " 은 이미 실행중인 스크립트 입니다."
	End If
End Function
2009/11/06 21:53 2009/11/06 21:53

맨 위로

[WMI] DEP에 프로그램 추가하기


DEP(Data Execution Prevention : 데이터 실행 방지) 탭에
일일히 프로그램 경로를 추가해야 하는 경우가 있다.

ATL의 Thunk로 메시지 Pump를 구현했거나,
Stack에 Asm으로 코드를 삽입하고 JMP로 EIP를 이동하여 Code Section이 아닌
Data Section에서 Code 실행이 이루어질 경우 DEP에 프로그램을 추가하면 해결된다.

그러나 DEP에 프로그램을 추가하는 MS에서 제공하는 옵션이 없기 때문에,
위와 같은 프로그램을 등록하기 위해선 손이 많이 간다.

아래의 WMI 스크립트를 이용해서 Drag And Drop으로 DEP를 추가해 보자!

Option Explicit
  
' 기본 Object 가져오기
Dim Shell : Set Shell = WScript.CreateObject("WScript.Shell")
Dim FSO : Set FSO = CreateObject("Scripting.FileSystemObject")
Dim WshEnv : Set WshEnv = Shell.Environment("Process")
Dim ProgramDir : ProgramDir = WshEnv("ProgramFiles")
Dim SystemRoot : SystemRoot = WshEnv("Systemroot")
  
'CMD 윈도우 98에서도 적용 가능하게 COMSPEC으로 가져온다.
Dim COMSPEC : COMSPEC = Shell.ExpandEnvironmentStrings("%comspec%")
  
Dim Exe01 : Exe01 = SystemRoot & "\system32\sysdm.cpl"
  
'각 Step별 윈도우 Title 확인
Const WindowTitleName_01 = "시스템 등록 정보"
  
'Main 함수 실행 후 종료
MainFunction
Wscript.quit
  
Sub MainFunction
  ' Argument 검사
  If Wscript.Arguments.Count = 0 Then
    Shell.Popup "DEP에 추가할 Argument를 입력하지 않았습니다.", 3, "No Arguments", 48
    Wscript.quit
  End If
  
  ' Step 1. sysdm.cpl 시스템 등록 정보 열기
  Install Exe01, ""
  SendKeys "{ESC}"
  
  Wscript.sleep 1000
  Install Exe01, ""
  
  ' Step 1. "시스템 등록 정보"
  WaitForActiveWindow WindowTitleName_01, 3
  
' SendKeys "{TAB}{TAB}"
  SendKeys "{RIGHT}{RIGHT}{RIGHT}"
  SendKeys "%s"
  SendKeys "{TAB}{TAB}{TAB}{TAB}"
  SendKeys "{RIGHT}{RIGHT}"
  SendKeys "%(ud)"
    Wscript.Sleep 500
    SendKeys "%(n)"
    
  '설정파일 경로 구하기
  Dim strAddToDepFile : strAddToDepFile = Wscript.Arguments.Item(0)
  Dim strFileFullPath
  GetFileFullPath strAddToDepFile, strFileFullPath
  
  SendKeys strFileFullPath
  Wscript.Sleep 500
  
  SendKeys "%o"
  SendKeys "{ENTER}"
  Wscript.Sleep 500
  SendKeys "{ESC}"
End Sub
  
  
Sub GetFileFullPath(strFileName, strFileFullPath)
  Dim objFile
  Set objFile = FSO.GetFile( strFileName )
  strFileFullPath = FSO.GetAbsolutePathName(objFile)
End Sub
  
  
Sub Install (InstallFile, Arguments)
  If (FSO.FileExists(InstallFile)) Then
    Shell.Run COMSPEC & " /c " & InstallFile & Arguments &" & Exit", 0
  Else
    Shell.Popup InstallFile & " 을(를) 찾을 수 없습니다.", 3, "File dose not exist", 48
    Wscript.Quit
  End if
End Sub
  
  
Sub WaitForActiveWindow(WindowName, Second)
  if Second < 0 Then
    Shell.Popup "음수 시간을 설정할 수 없습니다.", 3, "Error!", 48
    Wscript.Quit
  End if
  
  Dim TimeOutCount : TimeOutCount = Second * 10
  
  Wscript.Sleep 1   'Winxp SP3에서 AppActivate() 버그 임시 해결용 by TTF
  
  While ( Shell.AppActivate( WindowName ) = False )
  
    if TimeOutCount < 0 Then
      Shell.Popup WindowName & " 윈도우를 찾을 수 없습니다. 실행을 종료합니다.", 5, "Can't Find Window", 48
      Wscript.Quit
    End if
  
    Wscript.Sleep 100
    TimeOutCount = TimeOutCount - 1
  WEnd
  
  'Winxp SP3에서 AppActivate() 버그 임시 해결용 by TTF
  Wscript.Sleep 1
End Sub
  
  
'Shell.SendKeys 위를 Sleep(200)로 감싼다. XP SP3 버그 임시 해결 by TTF
Sub SendKeys( Keys )
  Wscript.Sleep 200
  Shell.SendKeys Keys
End Sub
2008/09/09 02:29 2008/09/09 02:29

맨 위로

[WMI] 시스템 변수 레지스트리 추가하기(환경변수설정)


[WMI] 비주얼 스튜디오 2005 단축키 설정 불러오기 by TTF
비주얼 스튜디오 환경설정 Setting 파일을 이용해서
"단축키 설정"과 "프로젝트 디렉터리 설정"을 쉽게 불러오는데 성공하였다.

하지만 비주얼 스튜디오 설치 과정에서 괴로운 작업이 한가지 더 있다.
바로 환경변수에 폴더 경로를 추가하는 작업.

그렇게 힘들진 않지만 윈도우 단축키와 마우스 컨트롤이 단련되어 있지 않은
"특수한" 프로그래머들은 이런 것 하나를 추가하는데에도 고통을 느낀다.(으악~~)

자자 아래와 같이 한방에 등록해 주는 WMI 스크립트!
이제 비주얼 스튜디오 환경변수 설정할 때 약간(?) 도움을 받을 수 있다. ㅎㅎㅎ

"Env_Setting.vbs" 파일만 클릭해 주면,
현재 "Env_Setting.vbs"가 있는 위치의 폴더 경로를 얻어와서,
그동안 등록하기 불편했던 환경 설정 변수들을 모두 등록 해준다.



Option Explicit
  
Dim strComputer : strComputer = "."
  
' 기본 Object 가져오기
Dim Shell : Set Shell = WScript.CreateObject("WScript.Shell")
Dim FSO : Set FSO = CreateObject("Scripting.FileSystemObject")
Dim WshEnv : Set WshEnv = Shell.Environment("Process")
Dim ProgramDir : ProgramDir = WshEnv("ProgramFiles")
Dim Reg : Set Reg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\default:StdRegProv")
Dim WMIService : Set WMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
  
'CMD 윈도우 98에서도 적용 가능하게 COMSPEC으로 가져온다.
Dim COMSPEC : COMSPEC = Shell.ExpandEnvironmentStrings("%comspec%")
  
  
'현재 세팅 파일 경로 구하기
Dim strSetupFile : strSetupFile = "Env_Setting.vbs"
  
'Main 함수 실행 후 종료
MainFunction
Wscript.quit
  
'Main 함수
Sub MainFunction
' 세팅 파일 절대 경로 구하기
  Dim strParentFolderPath
  GetParentFolderPath strSetupFile, strParentFolderPath
  
' 환경 변수 레지스트리 설정
  Const HKEY_CURRENT_USER = &H80000001
  Const HKEY_LOCAL_MACHINE = &H80000002
  
  Dim strKeyPath, strValueName, strValue
  
  '일단 등록하고 아래에서 바로 사용할 수 있도록 Refresh 하자
  strKeyPath = "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
  strValueName = "TTF_Base"
  strValue = strParentFolderPath
  Reg.SetStringValue HKEY_LOCAL_MACHINE, strKeyPath, strValueName, strValue
  
  strKeyPath = "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
  strValueName = "TTF_Base_Header"
  strValue = "%TTF_Base%\include\Header"
  Reg.SetExpandedStringValue HKEY_LOCAL_MACHINE, strKeyPath, strValueName, strValue
  
  strKeyPath = "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
  strValueName = "TTF_Base_Lib"
  strValue = "%TTF_Base%\Include\Library"
  Reg.SetExpandedStringValue HKEY_LOCAL_MACHINE, strKeyPath, strValueName, strValue
  
  strKeyPath = "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
  strValueName = "TTF_Base_UnitTest"
  strValue = "%TTF_Base%\UnitTest++\src"
  Reg.SetExpandedStringValue HKEY_LOCAL_MACHINE, strKeyPath, strValueName, strValue
  
  
'환경 변수 새로고침(바로 사용 가능하도록 Refresh)
  Dim colItems : Set colItems = WMIService.ExecQuery ("Select * from Win32_Environment WHERE SystemVariable = True")
  
  Dim objItem
  For Each objItem in colItems
         objItem.Put_
  Next
End Sub
  
Sub GetParentFolderPath(strFileName, strFileFullPath)
  Dim objFile
  Set objFile = FSO.GetFile( strFileName )
  strFileFullPath = FSO.GetParentFolderName(objFile)
End Sub
2008/07/10 01:40 2008/07/10 01:40

맨 위로

[WMI] 비주얼 스튜디오 2005 단축키 설정 불러오기 by TTF

비주얼 스튜디오 2005 단축키 설정 파일, WMI 스크립트를 이용한 자동 설정 파일입니다.

주의사항 : 비주얼 스튜디오의 솔루션 닫기를 누른 후 사용한다.
(비주얼 스튜디오 Title name을 "Microsoft Visual Studio"로 인식하여 스크립트 진행)
(2008-06-13) Regist_vssettings.vbs 스크립트에 문제가 있어서 수정하였습니다.
(2008-07-15) Window XP SP3 에서는 SendKeys Method의 짧은 시간 반복 입력을 막은 것으로 추측됩니다.
Option Explicit
  
' 기본 Object 가져오기
Dim Shell : Set Shell = WScript.CreateObject("WScript.Shell")
Dim FSO : Set FSO = CreateObject("Scripting.FileSystemObject")
Dim WshEnv : Set WshEnv = Shell.Environment("Process")
Dim ProgramDir : ProgramDir = WshEnv("ProgramFiles")
  
'CMD 윈도우 98에서도 적용 가능하게 COMSPEC으로 가져온다.
Dim COMSPEC : COMSPEC = Shell.ExpandEnvironmentStrings("%comspec%")
  
'각 Step별 윈도우 Title 확인
Const WindowTitleName_01 = "Microsoft Visual Studio"
Const WindowTitleName_02 = "설정 가져오기 및 내보내기 마법사"
Const WindowTitleName_03 = "설정 파일 선택"
  
'비주얼 스튜디오 사용자 정의 설정 파일
Dim strSetupFile : strSetupFile = "TTF.vssettings"
  
'Main 함수 실행 후 종료
MainFunction
Wscript.quit
  
'Main 함수
Sub MainFunction
  ' Microsoft Visual Studio - Window Title 변경
  WaitForActiveWindow WindowTitleName_01, 3
  Wscript.Sleep 200
  SendKeys "%(FT)"    ' ALT + F + T
  
  Shell.Popup "Visual Studio 프로젝트를 닫았습니다. 3초 대기 후 진행합니다.", 3, "3 second wait.", 48
  
  WaitForActiveWindow WindowTitleName_01, 3
  Wscript.Sleep 200
  SendKeys "%(TI)"    ' ALT + T + I
  
  ' 설정 가져오기 및 내보내기 마법사 - Window Title 변경
  WaitForActiveWindow WindowTitleName_02, 3
  Wscript.Sleep 200
  SendKeys "%(I)"   ' ALT + I
  SendKeys "%(N)"   ' ALT + N
  
  WaitForActiveWindow WindowTitleName_02, 3
  Wscript.Sleep 200
  SendKeys "%(O)"   ' ALT + O
  SendKeys "%(N)"   ' ALT + N
  
  
  WaitForActiveWindow WindowTitleName_02, 3
  Wscript.Sleep 200
  SendKeys "%(B)"   ' ALT + B
  
  ' 설정 파일 선택 - Window Title 변경
  WaitForActiveWindow WindowTitleName_03, 3 
  Wscript.Sleep 200
  SendKeys "%(N)"   ' 파일이름 입력
  
  '설정파일 경로 구하기
  Dim strFileFullPath
  GetFileFullPath strSetupFile, strFileFullPath
  
  WaitForActiveWindow WindowTitleName_03, 3
  Wscript.Sleep 200
  SendKeys strFileFullPath  ' 파일 경로 + 이름 입력
  SendKeys "%(O)"   ' ALT + O (파일 열기)
  
  WaitForActiveWindow WindowTitleName_02, 3
  Wscript.Sleep 500
  SendKeys "%(N)"   ' ALT + N
  SendKeys "%(F)"   ' ALT + F
  
  WaitForActiveWindow WindowTitleName_02, 3
  SendKeys "{ENTER}"  ' 닫기 Enter
End Sub
  
Sub GetFileFullPath(strFileName, strFileFullPath)
  Dim objFile
  Set objFile = FSO.GetFile( strFileName )
  strFileFullPath = FSO.GetAbsolutePathName(objFile)
End Sub
  
'Window 이름이 동일한 윈도우 창을 활성화
Sub WaitForActiveWindow(WindowName, Second)
  if Second < 0 Then
    Shell.Popup "음수 시간을 설정할 수 없습니다.", 3, "Error!", 48
    Wscript.Quit
  End if
  
  Dim TimeOutCount : TimeOutCount = Second * 10
  
  While ( Shell.AppActivate( WindowName ) = False )
    Wscript.Sleep 1  
    if TimeOutCount < 0 Then
      Shell.Popup WindowName & " 윈도우를 찾을 수 없습니다. 실행을 종료합니다.", 5, "Can't Find Window", 48
      Wscript.Quit
    End if
  
    Wscript.Sleep 100
    TimeOutCount = TimeOutCount - 1
  WEnd
  Wscript.Sleep 200
End Sub
  
'SendKey를 Sleep(200)로 감싼다. XP SP3 버그 임시 해결 by TTF
Sub SendKeys( Keys )
  Wscript.Sleep 200
  Shell.SendKeys Keys
End Sub



Macro 추가 버전
2008/06/13 03:21 2008/06/13 03:21

맨 위로

[WMI] 프로세스의 CPU_메모리 사용량_네트워크 트래픽을 Log로 저장


서버 프로그래머는 CPU와 메모리 사용량에 많은 관심을 가지게 된다.
서버 프로그램, 즉 Process가 CPU 100%로 사용중이거나 메모리가 2GB(User Memory)에 근접하게 되면 곤란한 경우가 많다.
그래서 종종 OS에서 제공하는 성능 모니터를 이용해서 Log를 남기기도 하는데, Process를 추가하기도 번거롭고 결과물을 EXCEL로 편집하기도 까다롭다.
이번 기회에 WMI 스크립트를 이용해서 Process 이름만 바꿔주고 클릭하면 10초마다 Log를 남기도록 만들었다.(스크립트 기반이므로 누구나 손쉽게 수정하여 사용 가능하다.)
네트워크 트래픽은 네트워크 어댑터 중에서 가장 송/수신이 많은 어댑터의 트래픽을 기록한다.( 단일 프로세스의 트래픽을 기록하는 것이 아니다. )

주의사항 : WbemScripting.SWbemRefresher 객체를 지원하는 OS는 다음과 같다.
Windows XP SP2 이상
Windows Server 2003 이상

Option Explicit
  
Dim FSO, oFile
Dim objWMIService, objProcess, objPerfOS, objNetworkInterface, objRefresher
Dim colProcess, colPerfOS, colPerfNetworkInterface
Dim strComputer, strFileName, strCpuPercent, strProcess
Dim strProcessName, strProcessNameForPerf
Dim strDate, strTime
Dim DateEnd, Timelimit
  
'프로세스 이름(.exe는 제거한다.)
strProcessNameForPerf = "explorer"
strProcessName = strProcessNameForPerf & ".exe"
  
'Log 남길 시간 설정
' "y"  년
' "m"  월
' "d"  일
' "w"  주
' "h"  시
' "n"  분
' "s"  초
  
Timelimit = 1
DateEnd = DateAdd("n", Timelimit, Now)
  
'strFileName = Inputbox("c:\ProcessPerformanceLog.txt","Process Performance","ProcessPerformanceLog.txt")
strFileName = strProcessNameForPerf & "_" & "ProcessPerformanceLog.txt"
  
'시스템 Object 생성
Set FSO = CreateObject("Scripting.FileSystemObject")
Set oFile = FSO.CreateTextFile(strFileName, True)
  
strComputer = "." 
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2") 
  
'새로고침 Object 생성
Set objRefresher = CreateObject("WbemScripting.SWbemRefresher")
  
Set colPerfOS = objRefresher.AddEnum(objWMIService, "Win32_PerfFormattedData_PerfProc_Process").objectSet
Set colPerfNetworkInterface = objRefresher.AddEnum(objWMIService, "Win32_PerfFormattedData_Tcpip_NetworkInterface").objectSet
Set colProcess = objRefresher.AddEnum(objWMIService, "Win32_Process").objectSet
objRefresher.Refresh
Wscript.Sleep 1000
  
'Header 정보 Log 파일에 출력
oFile.Write("Date" & vbTab & "Time" & vbTab & "Process Name" & vbTab & "CPU Usage" & vbTab & "Memory Usage" & vbTab & "Peak Memory Usage" & vbTab & "PageFile Usage" & vbTab & "Peak PageFile Usage" & vbTab & "Network KBytesSendPerSec" & vbTab & "Network KBytesRecvPerSec")
  
While( Now < DateEnd )
   '시스템 정보 Refresh
   objRefresher.Refresh
  
   '네트워크 트래픽 보기 - 모든 네트워크 어댑터에서 중에서 송/수신량이 가장 많은 어댑터의 트래픽을 기록한다.
   Dim nBytesSentPerSec : nBytesSentPerSec = 0
   Dim nBytesReceivedPerSec : nBytesReceivedPerSec = 0
  
   For Each objNetworkInterface in colPerfNetworkInterface
      If ( nBytesSentPerSec < objNetworkInterface.BytesSentPerSec ) Then
         nBytesSentPerSec = objNetworkInterface.BytesSentPerSec
      End If
  
      If ( nBytesReceivedPerSec < objNetworkInterface.BytesReceivedPerSec ) Then
         nBytesReceivedPerSec = objNetworkInterface.BytesReceivedPerSec
      End If
   Next
  
   'CPU 사용량 보기
   For Each objPerfOS in colPerfOS
      If ( strProcessNameForPerf = objPerfOS.Name ) Then
         strCpuPercent = objPerfOS.PercentProcessorTime
      End If
   Next
  
   '프로세스 메모리 보기
   For Each objProcess in colProcess
      If ( strProcessName = objProcess.Name ) Then
         GetDate strDate
         GetTime strTime
         strProcess = vbNewLine & strDate & vbTab & strTime & vbTab & objProcess.Name & vbTab & strCpuPercent & vbTab & objProcess.WorkingSetSize/1024 & "KB" & vbTab & objProcess.PeakWorkingSetSize/1024 & "KB" & vbTab & objProcess.PageFileUsage/1024 & "KB" & vbTab & objProcess.PeakPageFileUsage/1024 & "KB" & vbTab & int(nBytesSentPerSec/1024) & "KB" & vbTab & int(nBytesReceivedPerSec/1024) & "KB"
      End If
   Next
  
   'Log 파일에 저장
   oFile.Write(strProcess)
  
   '10초마다 한번씩 로그를 남긴다.
   Wscript.Sleep 10000
WEnd
  
oFile.Write( vbNewLine & "End of Log" )
oFile.Close
WScript.Quit
  
  
'Sub 함수들
Sub GetTime( strTime )
Dim strHour, strMinute, strSecond
  
'--  Hour 2자리로 변경
strHour = Hour(Now)
If Len(strHour) < 2 Then
  strHour = "0" & strHour
End If
  
'-- Minute 2자리로 변경
strMinute = Minute(Now)
If Len(strMinute) < 2 Then
  strMinute = "0" & strMinute
End If
  
'-- Second
strSecond = Second(Now)
If Len(strSecond) < 2 Then
  strSecond = "0" & strSecond
End If
  
'-- 전체 시간
strTime = strHour & ":" & strMinute & ":" & strSecond
  
End Sub
  
  
Sub GetDate( strDate )
Dim strDay, strMonth, strYear
  
'--  Day 2자리로 변경
strDay = Day(Now)
If Len(strDay) < 2 Then
  strDay = "0" & strDay
End If
  
'-- Month 2자리로 변경
strMonth = Month(Now)
If Len(strMonth) < 2 Then
  strMonth = "0" & strMonth
End If
  
'-- Year
strYear = Year(Now)
  
'-- 전체 날짜 구하기
strDate = strYear & "-" & strMonth & "-" & strDay
  
End Sub
2008/05/28 03:30 2008/05/28 03:30

맨 위로

[WMI] 곰플레이어 자동 설치 버전 by TTF


곰플레이어 자동 설치 vbs 샘플은 위의 출처 링크에서 가져왔습니다.

그러나 포커스가 해당 창이 아닐 경우에 키 입력을 계속 받는 문제점이 있었습니다.

그 부분만 보완해서 WaitFor3secActiveWindow() 함수를 추가하였습니다.

좋은 정보 블로그에 올려주신 영산님께 다시 한번 감사의 말씀 드립니다.

곰플레이어 자동 설치 버전 by TTF

XP SP3에서는 SendKeys()를 짧은 시간에 연속으로 입력하지 못하도록 제한한 것으로 추측됩니다.


Option Explicit
  
' 기본 Object 가져오기
Dim Shell : Set Shell = WScript.CreateObject("WScript.Shell")
Dim FSO : Set FSO = CreateObject("Scripting.FileSystemObject")
Dim WshEnv : Set WshEnv = Shell.Environment("Process")
Dim ProgramDir : ProgramDir = WshEnv("ProgramFiles")
  
'CMD 윈도우 98에서도 적용 가능하게 COMSPEC으로 가져온다.
Dim COMSPEC : COMSPEC = Shell.ExpandEnvironmentStrings("%comspec%")
  
Const GOM_Player_ExeFile = "GOMPLAYERSETUP.EXE"  '고정된 이름은 변수가 아닌 상수로 지정해도 무방..
  
  
If MsgBox ( "곰플레이어를 설치하시겠습니까?  ", 36, "Setup - GomPlayer") = 6 Then
  
    Install GOM_Player_ExeFile, ""
  
    Const Step1 = "곰플레이어 설치"
    Const Step2 = "곰 주소창검색 소개"
  
' Step 1. "곰플레이어 설치"
    WaitForActiveWindow Step1, 10
    SendKeys "{ENTER}"    ' 다음> [엔터]
    SendKeys "{ENTER}"    ' 동의함[엔터]
  
    WaitForActiveWindow Step1, 3
    SendKeys "+{TAB}"  ' 구성 요소 선택 (모든 동영상 확장자 등록 체크)
    SendKeys "{DOWN 6}"  ' 화살표 아래키 6번 입력
    SendKeys " "    ' [SPACE는 공백]
  
    WaitForActiveWindow Step1, 3    
    SendKeys "{ENTER}"    ' 다음> [엔터]
    SendKeys "{ENTER}"    ' 키즈락 선택하지 않고, 다음> [엔터]
    SendKeys "{ENTER}"    ' 설치 위치 선택, 설치> [엔터]
    Wscript.Sleep 14000
  
    WaitForActiveWindow Step1, 3
    SendKeys "{ENTER}"    ' 곰 플레이어 설치 완료, 마침> [엔터]
  
' Step2 . "곰 주소창검색 소개" 설치 취소
    WaitForActiveWindow Step2, 3
    SendKeys "{TAB}"    ' 취소 선택[탭]
    SendKeys "{ENTER}"    ' 곰 주소창 검색 취소 완료, 마침> [엔터]
Else
    Shell.Popup "곰플레이어 설치가 취소되었습니다.   ", 3, "Cancle", 48
    WScript.Quit
End if
  
  
  
Sub Install (InstallFile, Arguments)
  If (FSO.FileExists(InstallFile)) Then
    Shell.Run COMSPEC & " /c " & InstallFile & Arguments &" & Exit", 0
  Else
    Shell.Popup InstallFile & " 을(를) 찾을 수 없습니다.", 3, "File dose not exist", 48
    Wscript.Quit
  End if
End Sub
  
  
Sub WaitForActiveWindow(WindowName, Second)
  if Second < 0 Then
    Shell.Popup "음수 시간을 설정할 수 없습니다.", 3, "Error!", 48
    Wscript.Quit
  End if
  
  Dim TimeOutCount : TimeOutCount = Second * 10
  
  Wscript.Sleep 1   'Winxp SP3에서 AppActivate() 버그 임시 해결용 by TTF
  
  While ( Shell.AppActivate( WindowName ) = False )
  
    if TimeOutCount < 0 Then
      Shell.Popup WindowName & " 윈도우를 찾을 수 없습니다. 실행을 종료합니다.", 5, "Can't Find Window", 48
      Wscript.Quit
    End if
  
    Wscript.Sleep 100
    TimeOutCount = TimeOutCount - 1
  WEnd
  
  'Winxp SP3에서 AppActivate() 버그 임시 해결용 by TTF
  Wscript.Sleep 1
End Sub
  
  
'Shell.SendKeys 위 아래를 Sleep(100)로 감싼다. XP SP3 버그 임시 해결 by TTF
Sub SendKeys( Keys )
  Wscript.Sleep 100
  Shell.SendKeys Keys
  Wscript.Sleep 100
End Sub
2008/02/17 01:01 2008/02/17 01:01

맨 위로

[C++] WMI를 이용해 Local PC의 고정 IP 변경하기

웹 서핑 하다가 정말 좋은 WMI 관련 내용을 찾아서 링크 합니다.

C#이 아닌 Visual C++ 6.0에서 구현한 점이 높이 평가할만 합니다.

관련된 MS 링크 예제 : http://msdn2.microsoft.com/en-us/library/aa390418(VS.85).aspx

#define _WIN32_DCOM

#include 
using namespace std;
#include 
#include 

#pragma comment(lib, "wbemuuid.lib")

int main(int argc, char **argv)
{
	HRESULT hres;

	// Initialize COM.
	hres = CoInitializeEx(0, COINIT_MULTITHREADED);
	if (FAILED(hres))
	{
		cout << "Failed to initialize COM library. "
		<< "Error code = 0x"
		<< hex << hres << endl;
		return 1;              // Program has failed.
	}

	// Initialize
	hres = CoInitializeSecurity(
				NULL,
				-1,        // COM negotiates service
				NULL,      // Authentication services
				NULL,      // Reserved
				RPC_C_AUTHN_LEVEL_DEFAULT,      // authentication
				RPC_C_IMP_LEVEL_IMPERSONATE,    // Impersonation
				NULL,               // Authentication info
				EOAC_NONE,          // Additional capabilities
				NULL              // Reserved
			);


	if (FAILED(hres))
	{
		cout << "Failed to initialize security. "
		<< "Error code = 0x"
		<< hex << hres << endl;
		CoUninitialize();
		return 1;          // Program has failed.
	}

	// Obtain the initial locator to Windows Management
	// on a particular host computer.
	IWbemLocator *pLoc = 0;

	hres = CoCreateInstance(
				CLSID_WbemLocator,
				0,
				CLSCTX_INPROC_SERVER,
				IID_IWbemLocator, (LPVOID *) & pLoc);

	if (FAILED(hres))
	{
		cout << "Failed to create IWbemLocator object. "
		<< "Error code = 0x"
		<< hex << hres << endl;
		CoUninitialize();
		return 1;       // Program has failed.
	}

	IWbemServices *pSvc = 0;

	// Connect to the root\cimv2 namespace with the
	// current user and obtain pointer pSvc
	// to make IWbemServices calls.

	hres = pLoc->ConnectServer(

				_bstr_t(L"ROOT\\CIMV2"),   // WMI namespace
				NULL,                      // User name
				NULL,                      // User password
				0,                         // Locale
				NULL,                      // Security flags
				0,                         // Authority
				0,                         // Context object
				&pSvc                    // IWbemServices proxy
			);

	if (FAILED(hres))
	{
		cout << "Could not connect. Error code = 0x"
		<< hex << hres << endl;
		pLoc->Release();
		CoUninitialize();
		return 1;                // Program has failed.
	}

	cout << "Connected to ROOT\\CIMV2 WMI namespace" << endl;

	// Set the IWbemServices proxy so that impersonation
	// of the user (client) occurs.
	hres = CoSetProxyBlanket(

				pSvc,                           // the proxy to set
				RPC_C_AUTHN_WINNT,              // authentication service
				RPC_C_AUTHZ_NONE,               // authorization service
				NULL,                           // Server principal name
				RPC_C_AUTHN_LEVEL_CALL,         // authentication level
				RPC_C_IMP_LEVEL_IMPERSONATE,    // impersonation level
				NULL,                           // client identity
				EOAC_NONE                     // proxy capabilities
			);

	if (FAILED(hres))
	{
		cout << "Could not set proxy blanket. Error code = 0x"
		<< hex << hres << endl;
		pSvc->Release();
		pLoc->Release();
		CoUninitialize();
		return 1;               // Program has failed.
	}


	// Use the IWbemServices pointer to make requests of WMI.
	// Make requests here:

	// For example, query for all the running processes
	IEnumWbemClassObject* pEnumerator = NULL;
	hres = pSvc->ExecQuery(
				bstr_t("WQL"),
				bstr_t("SELECT * FROM Win32_Process"),
				WBEM_FLAG_FORWARD_ONLY WBEM_FLAG_RETURN_IMMEDIATELY,
				NULL,
				&pEnumerator);

	if (FAILED(hres))
	{
		cout << "Query for processes failed. "
		<< "Error code = 0x"
		<< hex << hres << endl;
		pSvc->Release();
		pLoc->Release();
		CoUninitialize();
		return 1;               // Program has failed.
	}
	else
	{
		IWbemClassObject *pclsObj;
		ULONG uReturn = 0;

		while (pEnumerator)
		{
			hres = pEnumerator->Next(WBEM_INFINITE, 1,
					&pclsObj, &uReturn);

			if (0 == uReturn)
			{
				break;
			}

			VARIANT vtProp;

			// Get the value of the Name property
			hres = pclsObj->Get(L"Name", 0, &vtProp, 0, 0);
			wcout << "Process Name : " << vtProp.bstrVal << endl;
			VariantClear(&vtProp);
		}

	}

	// Cleanup
	// ========

	pSvc->Release();
	pLoc->Release();
	CoUninitialize();

	return 0;   // Program successfully completed.
}
2008/02/11 01:06 2008/02/11 01:06

맨 위로

[WMI] 공유폴더 드라이브에 매핑하기


기본적인 네트워크 드라이브 매핑 스크립트는 아래와 같다.
Set objNetwork = CreateObject("WScript.Network")
objNetwork.MapNetworkDrive "Z:", \\192.168.0.3\새 폴더, false, strUserID, strPassword


HTML 포멧 GUI 기반의 네트워크 드라이브 매핑 스크립트

2008/01/14 23:26 2008/01/14 23:26

맨 위로

[WMI] 원하는 폴더의 원하는 확장자 파일 모두 지우기

strDir = "D:\Backup"
strFileExt = "bak"
  
strComputer = "."
  
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
  
Set FileList = objWMIService.ExecQuery("ASSOCIATORS OF {Win32_Directory.Name='" & strDir & "'} Where " & "ResultClass = CIM_DataFile")
  
For Each objFile In FileList
        If objFile.Extension = strFileExt Then
' Wscript.echo "Extension : " & objFile.Extension
            objFile.Delete
        End If
Next
2007/12/09 00:11 2007/12/09 00:11

맨 위로