88
1 Windows PowerShell による Server Core の環境設定と操作 マクロソフト株式会社 エバンジェリスト 安納 順一 Anno Junichi http://blogs.technet.com/junichia/

PowerShellを使用したWindows Serverの管理

Embed Size (px)

DESCRIPTION

Windows PowerShell 2.0 を使用した ・Server Core の設定 ・Hyper-Vの管理 ・Active Directoryの管理 ・EventLogの管理

Citation preview

Page 1: PowerShellを使用したWindows Serverの管理

1

Windows PowerShell によるServer Core の環境設定と操作

マクロソフト株式会社

エバンジェリスト

安納 順一 Anno Junichi

http://blogs.technet.com/junichia/

Page 2: PowerShellを使用したWindows Serverの管理

22

本日の目的

従来のWindows Script にかわるPowerShell を使用したさまざまな管理手法

PowerShell でしかできないこと

Page 3: PowerShellを使用したWindows Serverの管理

33

Agenda

• OSの基本設定

• Hyper-V 環境の管理

• Active Directory の管理

• EventLog の管理

PowerShell を使用して以下の作業を行います

Page 4: PowerShellを使用したWindows Serverの管理

4

OSの基本設定

Page 5: PowerShellを使用したWindows Serverの管理

55

OSの基本設定

Windows Server 2008 R2 Server Core では簡易GUIを提供

Sconfig.cmd

Page 6: PowerShellを使用したWindows Serverの管理

66

PowerShell のンストールと環境設定

ここからPowerShellコンソール

• WinRMサービスを起動• WinRMサービスを「自動」に設定• WinRM リスナを作成• WS-Management(HTTP)のFirewall例外を有効にする• PowerShell セッション構成を有効にする

Set-WSManQuickConfig

Page 7: PowerShellを使用したWindows Serverの管理

77

PowerShell Remoting

ローカルで実行

リモート CL01 上で実行

Page 8: PowerShellを使用したWindows Serverの管理

88

PowerShell Remoting

複数のリモートコンピューターを管理

方法1:コンピュータ名を並べて指定

方法2:コンピュータ名一覧をテキストファイルで用意

c:¥tmp¥hosts.txt

Page 9: PowerShellを使用したWindows Serverの管理

99

(参考)Server Core がWGの場合

クラゕント側の TrustedHosts に Server Core を追加する

Page 10: PowerShellを使用したWindows Serverの管理

1010

コンピューター名変更とドメン参加

Page 11: PowerShellを使用したWindows Serverの管理

1111

ネットワーク設定

Page 12: PowerShellを使用したWindows Serverの管理

1212

Windows Update とデバスドラバのダウンロード

Page 13: PowerShellを使用したWindows Serverの管理

1313

画面の解像度

(例)43882AFB-EB1A-406B-98F8-BDC4D019D84E

Page 14: PowerShellを使用したWindows Serverの管理

1414

(参考)PowerShellを使わない場合作業 初期状態 操作方法、コマンド例

パスワード変更 未設定 ログオン時に実施

コンピュータ名の変更 ランダム Netdom renamecomputer %computername% /NewName:Server2008-01

ネットワーク環境設定 DHCP Netsh interface ipv4 show interfaces

Netsh interface ipv4 add address name=“ローカルエリゕ接続” address=“192.168.7.100” mask=“255.255.255.0”gateway=192.168.7.254”

Netsh interface ipv4 add dnsserver name=“ローカル エリゕ接続” 192.168.7.11 index=1

WSHのエンジン変更 wscript Cscript.exe //h:cscript (エンジンを cscript にする)

Windows Update設定 未設定 Scregedit.wsf /AU 4 (自動更新を有効にする)

電源管理系機能の設定 Powercfg.exe

役割と機能の追加 未 Oclist.exe で一覧参照、Ocsetup.exeでンストール

ドメン参加 Netdom join %computername% /domain:<domainName> /userd:<domainName>¥<userName> /passwordd:<password>

シャットダウン、再起動、ログオフ Shutdown.exe (再起動時は /r ), logoff.exe

Page 15: PowerShellを使用したWindows Serverの管理

1515

Server Core の管理メージ

Server Core Remote PC

コマンドプロンプト/PowerShellコンソール

MMC/Server Manager/リモードデスクトップ

コマンドプロンプト/PowerShellコンソール

Page 16: PowerShellを使用したWindows Serverの管理

1616

リモートからの管理を有効にする

• MMC• リモートデスクトップサービス• Server Manager• Windows PowerShell(実施済み)

Page 17: PowerShellを使用したWindows Serverの管理

1717

MMCを使用したリモート管理を有効にするsconfig.cmd の中で実行している内容

Page 18: PowerShellを使用したWindows Serverの管理

1818

リモートデスクトップを有効にする

Page 19: PowerShellを使用したWindows Serverの管理

1919

(参考)Workgroup構成の場合Server Core側

クライアント側

Page 20: PowerShellを使用したWindows Serverの管理

20

Hyper-Vの管理

Page 21: PowerShellを使用したWindows Serverの管理

21

Server Core 上の Hyper-V を管理するには• Hyper-V マネージャーから(リモート)

• GUIからHyper-Vを管理• OSのンストール、OSの操作も可能

• System Center Virtual Machine Manager から(リモート)• 合理化されたGUIからHyper-Vを管理• OSのンストール、操作も可能• 専用のPowerShellコマンドレットも用意

• WMIを使用してPowerShell から(リモート,ローカル)• コマンドランからHyper-Vを管理• (通信可能であれば)OSの操作が可能• OSのンストールが行えない

Server Coreローカル

リモート

Page 22: PowerShellを使用したWindows Serverの管理

22

root¥virtualization 内のクラス一覧

MSVM_VirtualSystemManagementServiceSettingDataMSVM_virtualSystemManagementServiceMSVM_ShutdownComponentMSVM_SwitchLANEndpointMSVM_SyntheticEthernetPortSettingDataMSVM_VirtualSwitchManagementServiceMSVM_VirtualSystemGlobalSettingDataMSVM_VirtualSystemSettingDataMSVM_VlanendpointMSVM_AllocationCapabilitiesMSVM_ComputerSystemMSVM_DiskDriveMSVM_SwitchPortMSVM_VirtualSwitch

MSVM_EmulatedEthernetPortSettingDataMSVM_ExternalEthernetPortMSVM_HeartbeatComponentMSVM_InternalEthernetPortMSVM_KvpExchangeComponentMSVM_KvpExchangeDataItemMSVM_MemorySettingDataMSVM_MountedStorageImageMSVM_ProcessorMSVM_ProcessorSettingDataMSVM_ResourceAllocationSettingDataMSVM_ResourcePoolMSVM_SettingsDefineCapabilities

Page 23: PowerShellを使用したWindows Serverの管理

23

MSVMクラス 利用のコツ

Page 24: PowerShellを使用したWindows Serverの管理

24

Msvm_VirtualSystemManagementService クラス

AddKvpItemsAddVirtualSystemResourcesApplyVirtualSystemSnapshotApplyVirtualSystemSnapshotExCheckSystemCompatibilityInfoCloneVirtualSystemCreateVirtualSystemSnapshotDefineVirtualSystemDestroyVirtualSystemExportVirtualSystemExportVirtualSystemExFormatErrorGetSummaryInformationGetSystemCompatibilityInfoGetVirtualSystemImportSettingDataGetVirtualSystemThumbnailImage

ImportVirtualSystemImportVirtualSystemExInstantiateVirtualSystemModifyKvpItemsModifyServiceSettingsModifyVirtualSystemModifyVirtualSystemResourcesPlanVirtualSystemRemoveKvpItemsRemoveVirtualSystemResourcesRemoveVirtualSystemSnapshotRemoveVirtualSystemSnapshotTreeRequestStateChangeStartServiceStopService

Hyper-Vの全体的な管理を行うクラス

メソッド一覧

Page 25: PowerShellを使用したWindows Serverの管理

25

(例)スナップショットを取る

Page 26: PowerShellを使用したWindows Serverの管理

2626

(参考)PowerShell modules for Hyper-V

Codeplex で提供されているPowerShellコマンドレット群2009年11月30日時点で ベータ版

http://pshyperv.codeplex.com/

Page 27: PowerShellを使用したWindows Serverの管理

2727

Active Directory を管理する+

Eventlog を管理する

Page 28: PowerShellを使用したWindows Serverの管理

28

AD DS を管理するための準備

• Active Directoryモジュールの読み込み

• Active Directory 関連コマンド一覧の参照

Page 29: PowerShellを使用したWindows Serverの管理

2929

(参考)Windows PowerShell ADモジュール一覧

Add-ADComputerServiceAccountAdd-ADDomainControllerPasswordReplicationPolicyAdd-ADFineGrainedPasswordPolicySubjectAdd-ADGroupMemberAdd-ADPrincipalGroupMembership

Clear-ADAccountExpiration

Disable-ADAccountDisable-ADOptionalFeature

Enable-ADAccountEnable-ADOptionalFeature

Get-ADAccountAuthorizationGroupGet-ADAccountResultantPasswordReplicationPolicyGet-ADComputerGet-ADComputerServiceAccountGet-ADDefaultDomainPasswordPolicyGet-ADDomainGet-ADDomainControllerGet-ADDomainControllerPasswordReplicationPolicyGet-ADDomainControllerPasswordReplicationPolicyUsageGet-ADFineGrainedPasswordPolicyGet-ADFineGrainedPasswordPolicySubjectGet-ADForestGet-ADGroupGet-ADGroupMemberGet-ADObjectGet-ADOptionalFeatureGet-ADOrganizationalUnitGet-ADPrincipalGroupMembershipGet-ADRootDSEGet-ADServiceAccountGet-ADUserGet-ADUserResultantPasswordPolicy

Page 30: PowerShellを使用したWindows Serverの管理

3030

Install-ADServiceAccount

Move-ADDirectoryServerMove-ADDirectoryServerOperationMasterRoleMove-ADObject

New-ADComputerNew-ADFineGrainedPasswordPolicyNew-ADGroupNew-ADObjectNew-ADOrganizationalUnitNew-ADServiceAccountNew-ADUser

Remove-ADComputerRemove-ADComputerServiceAccountRemove-ADDomainControllerPasswordReplicationPolicyRemove-ADFineGrainedPasswordPolicyRemove-ADFineGrainedPasswordPolicySubjectRemove-ADGroupRemove-ADGroupMemberRemove-ADObjectRemove-ADOrganizationalUnitRemove-ADPrincipalGroupMembershipRemove-ADServiceAccountRemove-ADUserRename-ADObjectReset-ADServiceAccountPasswordRestore-ADObject

Search-ADAccount

Set-ADAccountControlSet-ADAccountExpirationSet-ADAccountPasswordSet-ADComputerSet-ADDefaultDomainPasswordPolicySet-ADDomainSet-ADDomainModeSet-ADFineGrainedPasswordPolicySet-ADForestSet-ADForestModeSet-ADGroupSet-ADObjectSet-ADOrganizationalUnitSet-ADServiceAccountSet-ADUser

Uninstall-ADServiceAccount

Unlock-ADAccount

Page 31: PowerShellを使用したWindows Serverの管理

31

ユーザー情報の参照

• 現在ログオンしているユーザーIDの情報

• ユーザーのプロパテゖを参照

Page 32: PowerShellを使用したWindows Serverの管理

32

AD DS をブラウズPS C:>cd AD:PS AD:>dir

Name ObjectClass DistinguishedName-------------------------------------------------------------------------Contoso domainDNS dc=Contoso,dc=ComConfiguration configuration cn=Configuration,dc=contoso,…Schema dMD cn=schema,cn=Configuration,…・・PS AD:¥>cd ‘.¥DC=Contoso,DC=Com’PS AD:¥DC=Contoso,DC=Com>dir

Name ObjectClass DistinguishedName-------------------------------------------------------------------------Builtin BuiltinDomain cn=Builtin,dc=contoso,dc=comComputers container cn=Computers,dc=contoso,dc…・・

Page 33: PowerShellを使用したWindows Serverの管理

33

特定条件のユーザーを検索①

• ユーザーIDに test を含むユーザーを検索する

• 無効化されたユーザーを検索する

• パスワードの有効期限が切れたユーザーを検索する

• ゕカウントの有効期限が切れたユーザーを検索する

• ロックされたユーザーを検索する

• パスワードが無期限のユーザーを検索する

Page 34: PowerShellを使用したWindows Serverの管理

34

特定条件のユーザーを検索②

• 1年間ログオンしていないユーザーを検索する※ただし最近作成したユーザーは除外する

2009/11/1817:00:00

除外

今から365日前

この間にログオンしていないユーザー

Page 35: PowerShellを使用したWindows Serverの管理

35

ユーザーを作成

#ドメンに移動cd AD:cd ‘.¥DC=contoso,DC=com’

#OUを作成New-ADOrganizationalUnit “TESTOU”

#OUに移動cd ‘.¥OU=TESTOU’

#ユーザーを作成New-ADUser –Name “itanaka” -UserPricipalName “[email protected]” -displayName “田中 一郎”

Page 36: PowerShellを使用したWindows Serverの管理

36

UserAccountControl フラグ の設定Set-AccountControl –Identity “<UserID>”-AccountNotDelegated $True | $False ゕカウントは重要なので委任できない-AllowReversiblePasswordEncryption $True | $False 暗号化を元に戻せるパスワードで保存する-AuthType {Negotiate | Basic} 使用する認証方式-CannotChangePassword <bool> ユーザーはパスワードを変更できない-DoesNotRequirePreAuth <bool> Kerberos事前認証を必要としない-Enabled <bool> ゕカウントの有効/無効-HomedirRequired <bool> ゕカウントにホーム デゖレクトリが必要であるかどうか-MNSLogonAccount <bool> マジョリテゖ ノード セットログオン ゕカウントであるかどうか-Partition <DN> Active Directory パーテゖションの識別名-PasswordNeverExpires <bool> パスワードを無期限にする-PasswordNotRequired <bool> ユーザーは次回ログオン時にパスワード変更が必要-TrustedForDelegation <bool> 任意のサービスへの委任でこのユーザーを信頼する-TrustedToAuthForDelegation <bool> このゕカウントで委任を使用できる-UseDESKeyOnly <bool> このゕカウントにKerberos DES暗号化を使う

Page 37: PowerShellを使用したWindows Serverの管理

37

パスワード

Set-ADAccountPassword -Identity <ADAccount> -NewPassword <SecureString> -OldPassword <SecureString>

Set-ADAccountPassword -Identity <ADAccount> -NewPassword <SecureString> -Reset <switch>

Page 38: PowerShellを使用したWindows Serverの管理

38

PowerShellでしかできない削除ユーザーの復活

Active Directory Recycle Bin

機能削除したユーザーを完全復活!既定で180日間保持(変更可能)削除状態からの復旧であればAuthoritative Restoreは不要

属性情報の紛失時には使えないLinked-Value も完全復活

グループメンバーシップやグループメンバー など

留意事項(ご参考)Active Directory フォレスト機能レベル

Windows Server 2008 R2規定では無効(有効にしたら元には戻せない)DITの容量が10~15%程度増加(目安)操作は Windows PowerShell を使用

Page 39: PowerShellを使用したWindows Serverの管理

3939

削除済 リサクル済

Lifetime180 Days

Lifetime180 Days

有効

Active Directory Recycle Bin

「削除済」からの完全復旧

消滅

削除操作

GarbageCollection

・・・・ ・・

Page 40: PowerShellを使用したWindows Serverの管理

40

削除済オブジェクト の ライフタイム を変更する

リサイクル済オブジェクトのライフタイムを変更する

(参考)ラフタムを変更するには

Page 41: PowerShellを使用したWindows Serverの管理

4141

Recycle Binを使用するための準備

フォレストの機能レベルを「2008 R2」にする

「ゴミ箱」を有効にする

Page 42: PowerShellを使用したWindows Serverの管理

4242

削除されたユーザーを復旧する

削除されたユーザーを参照する

ユーザーを復旧する

Page 43: PowerShellを使用したWindows Serverの管理

43

Active Directory Recycle Bin のメカニズム

削除されるとDeleted Objects コンテナに移動

IsDeleted属性が Trueに

全てのオブジェクトがフラットに並ぶ

RDN(識別名)が書き換えられる<現在のRDN>¥0ADEL:<GUID>

CN=Deleted Objects

OU=Admins¥0ADEL:…

CN=Tom¥0ADEL:…

CN=Sally¥0ADEL:…

CN=Mark¥0ADEL:…

OU=Finance¥0ADEL:...

CN=Robert¥0ADEL:…

OU=Finance

OU=Admins

CN=Tom

CN=Sally

CN=Mark

OU=Finance

CN=Robert

Page 44: PowerShellを使用したWindows Serverの管理

44

ツリー構造の復旧はルートから行う

復旧は親から順に行う

親オブジェクトが存在しない場合にエラー

親はlastKnownParent 属性に入っている

CN=Deleted Objects

OU=Admins¥0ADEL:…

CN=Tom¥0ADEL:…

CN=Sally¥0ADEL:…

CN=Mark¥0ADEL:…

OU=Finance¥0ADEL:...

CN=Robert¥0ADEL:…

まずはここから

OU=Finance

OU=Admins

CN=Tom

CN=Sally

CN=Mark

CN=Robert

Page 45: PowerShellを使用したWindows Serverの管理

45

組織ツリーの復旧

1. 親を復旧

2. 親が「Finance_Department」であるものを復旧

3. 親が「Admins」であるものを復旧

Page 46: PowerShellを使用したWindows Serverの管理

46

ユーザーIDのプロビジョニング - Before

従来のプロビジョニング(WS2003~WS2008)

各種属性所属グループメンバーシップ

Page 47: PowerShellを使用したWindows Serverの管理

47

ユーザーIDのプロビジョニング - After

Windows Server 2008 R2では

各種属性所属グループメンバーシップ

Page 48: PowerShellを使用したWindows Serverの管理

48

ユーザーIDのプロビジョニング - After+

さらなる内製化

監査ログ

各種属性所属グループメンバーシップ

Page 49: PowerShellを使用したWindows Serverの管理

49

ユーザー属性の変更を追跡するには①

[ADSIエデゖタ] で Everyoneに対して「すべてのプロパテゖの書き込み」を監査

監査の設定

Page 50: PowerShellを使用したWindows Serverの管理

50

ユーザー属性の変更を追跡するには②

デゖレクトリサービスのゕクセスの監査 を有効にする

Page 51: PowerShellを使用したWindows Serverの管理

51

ベントID 5136department 属性が 「営業部」から「経理部」に変わったことがわかる

Page 52: PowerShellを使用したWindows Serverの管理

52

EventID 5136 を検索する

searchEvent.ps1

Page 53: PowerShellを使用したWindows Serverの管理

53

出力結果例

Page 54: PowerShellを使用したWindows Serverの管理

54

AD Recycle Bin + PowerShell + 監査ログ

業務に与えるンパクト

データ復旧時のシステム停止時間を大幅に削減従来

Authoritative Restore によるバックゕップからの復元

Snapshot から取り出し(Windows Server 2008)

今後Windows PowerShell によって簡単に復元

局所的に復元が可能

簡易的なユーザーIDプロビジョニングシステムの実現導入コストの大幅な軽減

中小規模システムへの適用が可能に

Page 55: PowerShellを使用したWindows Serverの管理

55

まとめ

Page 56: PowerShellを使用したWindows Serverの管理

56

まとめ

難しくて面倒なWMIが身近に

コードの量が半分以下に(VBS比)

慣れたコマンドを併用可能

GUIでは知りえない情報も取得

今後、多くのServer製品にコマンドレットが付属

Page 57: PowerShellを使用したWindows Serverの管理

5757

Page 58: PowerShellを使用したWindows Serverの管理

58

Appndix- WMI による Windows Server の 監視

(VBScript編)

Page 59: PowerShellを使用したWindows Serverの管理

5959

WMI とは

WBEM/CIMに準拠

各種管理情報への共通ンターフェース

Windows Management Serviceとして実装

Windows 2000以上のOSに標準搭載

WMIプロバダはベンダーが拡張可能

別途エージェントは一切必要なし

もちろんタダ!

Windows Management Instrumentation

Page 60: PowerShellを使用したWindows Serverの管理

6060

Page 61: PowerShellを使用したWindows Serverの管理

6161

WMI にゕクセスするには

バッチフゔルから

WMICコマンド(Windows XP以降)

Windows Script Host から

Windows PowerShell から

Visual Studio から

GUIツールから

WMI Admin Tools など

Page 62: PowerShellを使用したWindows Serverの管理

6262

WMIの構造

Namespace

Class

%WinDir%¥System32¥wbem 配下の mof (Managed Object Format)フゔルに定義されている

Namespace によって使えるClass が異なることに注意

規定のNamespaceはRoot¥CIMV2

(例) ROOT¥COMV2Win32_OperatingSystemWin32_NTLogEventLog・・

ROOT¥DefaultSTDREGPROV

ROOT¥microsoft¥SqlServer¥ComputerManagement10SqlService・・

Page 63: PowerShellを使用したWindows Serverの管理

6363

WMIの主役 Win32_クラス

Win32_ActiveRouteWin32_ComputerShutdownEventWin32_ComputerSystemEventWin32_ConnectionShareWin32_CurrentTimeWin32_DeviceChangeEventWin32_DiskQuotaWin32_GroupInDomainWin32_IP4PersistedRouteTableWin32_IP4RouteTableWin32_IP4RouteTableEventWin32_JobObjectStatusWin32_LoggedOnUserWin32_LogonSessionWin32_LogonSessionMappedDiskWin32_NetworkAdapterWin32_ComputerSystem

・・

Win32_ModuleTraceWin32_NamedJobObjectWin32_NTDomainWin32_PingStatusWin32_ProcessStartTraceWin32_ProcessStopTraceWin32_ProxyWin32_QuotaSettingWin32_ServerConnectionWin32_SessionConnectionWin32_TokenGroupsWin32_TokenPrivilegesWin32_VolumeChangeEventWin32_WindowsProductActivationWin32_ControllerHasHub

・・・

一部抜粋

Page 64: PowerShellを使用したWindows Serverの管理

6464

WMI Tools ~ CIM Studioブラウザを使用して、WMIの構造、実際のンスタンスを確認クエリを発行して戻り値を確認リモートコンピュータに接続も可能

Page 65: PowerShellを使用したWindows Serverの管理

6565

VBScriptからWMIを使う

Page 66: PowerShellを使用したWindows Serverの管理

6666

WMI Scriptingの基本形

'SWbemLocator オブジェクトの作成Set Locator = CreateObject("WbemScripting.SWbemLocator")

‘ローカルコンピュータへの接続Set Service = Locator.ConnectServer("", "root¥cimv2", "", "")

‘クエリーの定義(WQL:WMI Query Language)strQuery = "Select * from Win32_NetworkAdapterConfiguration " & _

"where IPEnabled = True"

‘クエリーの実行(インスタンスを取得する)Set objNet = Service.ExecQuery(strQuery)

'結果の参照For each n in objNet

WScript.Echo n.captionWScript.Echo n.MACAddress

Next

Page 67: PowerShellを使用したWindows Serverの管理

6767

WMIスクリプトの実行権限

Set Service = Locator.ConnectServer(RemoteHost,Namespace,User,Password)

リモートコンピュータに対するゕクセス権の取得

特殊権限の取得

Set Locator = CreateObject("WbemScripting.SWbemLocator")

Set Service = Locator.ConnectServer("DC01", "root¥cimv2", "Dom¥administrator", "pass")

Service.Security_.Privileges.AddAsString "SeBackupPrivilege", TrueService.Security_.Privileges.AddAsString "SeSecurityPrivilege", True

strQuery = "Select * from Win32_NTEventlogFile" & _" Where LogfileName = 'Security' "

Set obj = Service.ExecQuery(strQuery)

For each n in objr = n.BackupEventLog("C:¥tmp¥Security.evt")

Next

Page 68: PowerShellを使用したWindows Serverの管理

6868

(注意)リモートコンピュータにゕクセスする前に①

リモートからの接続が許可されていることを確認規定ではシステム管理者にはゕクセスが許可されている

Page 69: PowerShellを使用したWindows Serverの管理

6969

(注意)リモートコンピュータにゕクセスする前に②

Page 70: PowerShellを使用したWindows Serverの管理

7070

Windows Serverを監視する

Page 71: PowerShellを使用したWindows Serverの管理

7171

ベントの監視

システムで発生したベントをトリガーとして処理を実行

一時監視と永続的監視

以下のベント監視用クラスが用意されている

__InstanceCreationEvent

あたらしいンスタンスが作成された

__InstanceModificationEvent

ンスタンスの属性が変更された

__InstanceDeletionEvent

既存のンスタンスが削除された

Page 72: PowerShellを使用したWindows Serverの管理

7272

監視のメージ

WORDが起動

ベントログにベントが書かれた

ユーザーがログオン

USBデバスが挿された

タムゾーンが変更

メモ帳が終了IPゕドレス変更

シャットダウン

Page 73: PowerShellを使用したWindows Serverの管理

7373

一時的な監視例①

Set objLocator = CreateObject("WbemScripting.SWbemLocator")Set objService = objLocator.ConnectServer(TargetComputer, _

"", AdminUser, AdminPass)

strQueryCreate = "Select * " & _"FROM __InstanceCreationEvent WITHIN 5 " & _"WHERE TargetInstance ISA 'Win32_Process' "

Set objEventsCreation = objService.ExecNotificationQuery(strQueryCreate)

DoSet CreationEvent = objEventsCreation.NexteventProcessName = CreationEvent.TargetInstance.NameWscript.Echo ProcessName

Loop

__InstanceCreationEventによる新たに作成されたインスタンスの監視

Win32_Procassのプロパテゖ

監視したいクラス

Page 74: PowerShellを使用したWindows Serverの管理

7474

一時的な監視例②

Set objLocator = CreateObject("WbemScripting.SWbemLocator")Set objService = objLocator.ConnectServer(TargetComputer, _

‚ROOT¥CIMV2", AdminUser, AdminPass)

strQuery= "Select * " & _"FROM __InstanceModificationEvent WITHIN 5 " & _"WHERE TargetInstance ISA 'Win32_ComputerSystem' "

Set objEventsModification = objService.ExecNotificationQuery(strQuery)

DoSet ModificationEvent = objEventsModification.NexteventUserName = ModificationEvent.TargetInstance.UserNameWscript.Echo UserName

Loop

__InstanceModificationEventによるユーザーログオンの監視

Page 75: PowerShellを使用したWindows Serverの管理

7575

そこでこんな方法…

現在のログオンセッション一覧をキャッシュログオンしたらセッション作成ログオフしたらセッション削除

ログオン時に割り振られた番号

ログオンのタプ(対話、ネットワーク…)

現在ログオンしているユーザーのユーザーIDとログオンIDをキャッシュ

ログオンしたユーザーID

ログオン時に割り振られた番号

Page 76: PowerShellを使用したWindows Serverの管理

7676

一時的な監視例③

Set objLocator = CreateObject("WbemScripting.SWbemLocator")Set objService = objLocator.ConnectServer("demo2008", "ROOT¥CIMV2", "", "")Wscript.Echo "接続が完了しました"strQueryCreate = "Select * FROM __InstanceCreationEvent WITHIN 5 " & _

"WHERE TargetInstance ISA 'Win32_LogonSession' ‚Set objEventsCreation = objService.ExecNotificationQuery(strQueryCreate)Do

Set CreationEvent = objEventsCreation.NexteventLogonId= CreationEvent.TargetInstance.LogonIDLogonType = CreationEvent.TargetInstance.LogonTypestrQueryLU = "Select * " & _

‚FROM Win32_LoggedOnUser‛ ' Where Dependent like ‘%" & LogonId & "%’‚Set objLoggedOnUser = objService.ExecQuery(strQueryLU)For Each u in objLoggedOnUser

If instr(u.Dependent, LogonId) ThenWscript.Echo u.AntecedentWscript.Echo u.Dependent

End IfNext

Loop

__InstanceCreationEventによるユーザーログオンの監視

ユーザーID

ログオンID

Page 77: PowerShellを使用したWindows Serverの管理

7777

一時的な監視例③‘ (③をブラッシュアップ)Set objLocator = CreateObject("WbemScripting.SWbemLocator")Set objService = objLocator.ConnectServer("demo2008", "ROOT¥CIMV2", "", "")

Wscript.Echo "接続が完了しました"strQueryCreate = "Select * FROM __InstanceCreationEvent WITHIN 5 " & _

"WHERE TargetInstance ISA 'Win32_LogonSession' ‚Set objEventsCreation = objService.ExecNotificationQuery(strQueryCreate)Do

Set CreationEvent = objEventsCreation.NexteventLogonId= CreationEvent.TargetInstance.LogonIDLogonType = CreationEvent.TargetInstance.LogonTypeSelect Case LogonType

Case 0 strLogonType = "System"Case 2 strLogonType = "Interactive"Case 3 strLogonType = "Network"Case 4 strLogonType = "Batch"Case 5 strLogonType = "Service"Case 6 strLogonType = "Proxy"Case 7 strLogonType = "Unlock"Case 8 strLogonType = "NetworkClearText"Case 9 strLogonType = "NewCredentials"Case 10 strLogonType = "RemoteInteractive(TS)"Case 11 strLogonType = "CachedInteractive"Case 12 strLogonType = "CachedRemoteInteractive"Case 13 strLogonType = "CachedUnlock"

End Select

Page 78: PowerShellを使用したWindows Serverの管理

7878

strQueryLoggedOnUser = "Select * " & _"FROM Win32_LoggedOnUser"

Set objLoggedOnUser = objService.ExecQuery(strQueryLoggedOnUser)

For Each u in objLoggedOnUserIf instr(u.Dependent, LogonId) Then

arrAntecedent = Split(u.Antecedent,".")Wscript.Echo Date & "," & Time & "," & _

LogonId & "," & arrAntecedent(2) & "," & strLogonTypeExit For

End IfNext

Loop

Page 79: PowerShellを使用したWindows Serverの管理

7979

一時的な監視例④

Set objLocator = CreateObject("WbemScripting.SWbemLocator")Set objService = objLocator.ConnectServer("demo2008", "ROOT¥CIMV2", "", "")

Wscript.Echo "接続が完了しました"strQueryCreate = "Select * " & _

"FROM __InstanceDeletionEvent WITHIN 5 " & _"WHERE TargetInstance ISA 'Win32_LogonSession' "

Set objEventsDeletion = objService.ExecNotificationQuery(strQueryCreate)

DoSet DeletionEvent = objEventsDeletion.NexteventLogonId= DeletionEvent.TargetInstance.LogonIDLogonType = DeletionEvent.TargetInstance.LogonType

Wscript.Echo Date & "," & Time & "," & LogonId & "," & strLogonType

Loop

__InstanceDeletionEventによるユーザーログオフの監視

セッションの削除はログオフしてから1分程度を要する

Page 80: PowerShellを使用したWindows Serverの管理

8080

③’と④を組み合わせると

ログDB

ログオンID をキーにしてログデータベースに書き込むことでサーバーを使用したユーザーの履歴を管理できる

ServerName LogonID LogonType LogonDateTime LogoffDateTime Domain UserID

demo2008 5443965 Interactive 2009/03/01 10:00:00

2009/03/01 12:15:30

dom anno

demo2008 6220879 TS 2009/03/01 12:00:00

2009/03/01 13:10:01

dom administrator

Page 81: PowerShellを使用したWindows Serverの管理

8181

スクリプトをサービス化

Page 82: PowerShellを使用したWindows Serverの管理

8282

ベントコンシューマ

• ActiveScriptEventConsumer– イベントが発生したらスクリプトを実行

• LogFileEventConsumer– ベントが発生したらテキストフゔルに書き込み

• NTEventLogEventConsumer– ベントが発生したらベント

• SMTPEventConsumer– ベントが発生したらメール送信

• CommandLineEventConsumer– ベントが発生したらコマンドを実行

イベントコンシューマとは….

システムで発生したイベントをトリガーに特定のアクションを実行する機構

システムに登録されるのでログオンする必要が無いただし、監視できるのはローカルコンピュータ

Page 83: PowerShellを使用したWindows Serverの管理

8383

MOFフゔルによる永続的監視

#pragma namespace("¥¥¥¥.¥¥root¥¥subscription")

instance of ActiveScriptEventConsumer as $Cons{

Name = "LogonUserLogging";ScriptingEngine = "VBScript";ScriptFileName = "c:¥¥tmp¥¥demoscript¥¥wmisample08.vbs";

};

instance of __EventFilter as $Filt{

Name = "LogonUser";Query = "SELECT * FROM __InstanceCreationEvent WITHIN 5 "

"WHERE TargetInstance ISA ¥"Win32_LogonSession¥" ";QueryLanguage = "WQL";EventNamespace = "root¥¥cimv2";

};

instance of __FilterToConsumerBinding{

Filter = $Filt;Consumer = $Cons;

};

ActiveScriptEventConsumerによるmofフゔルの例

Page 84: PowerShellを使用したWindows Serverの管理

8484

コマンドプロンプトからコンパルC:¥>mofcomp.exe <mofフゔル名>

拡張子mofで保存

Page 85: PowerShellを使用したWindows Serverの管理

8585

呼び出されるスクリプト(③‘’)Set objLocator = CreateObject("WbemScripting.SWbemLocator")Set objService = objLocator.ConnectServer("demo2008", "ROOT¥CIMV2", "", "")Set objFS = CreateObject("Scripting.FileSystemObject")

Wscript.Echo "接続が完了しました"strQueryCreate = "Select * FROM __InstanceCreationEvent WITHIN 5 " & _

"WHERE TargetInstance ISA 'Win32_LogonSession' ‚Set objEventsCreation = objService.ExecNotificationQuery(strQueryCreate)Do

Set CreationEvent = objEventsCreation.NexteventLogonId= CreationEventTargetEvvent.TargetInstance.LogonIDLogonType = CreationEventTargetEvent.TargetInstance.LogonTypeSelect Case LogonType

Case 0 strLogonType = "System"Case 2 strLogonType = "Interactive"Case 3 strLogonType = "Network"Case 4 strLogonType = "Batch"Case 5 strLogonType = "Service"Case 6 strLogonType = "Proxy"Case 7 strLogonType = "Unlock"Case 8 strLogonType = "NetworkClearText"Case 9 strLogonType = "NewCredentials"Case 10 strLogonType = "RemoteInteractive(TS)"Case 11 strLogonType = "CachedInteractive"Case 12 strLogonType = "CachedRemoteInteractive"Case 13 strLogonType = "CachedUnlock"

End Select

Page 86: PowerShellを使用したWindows Serverの管理

8686

strQueryLoggedOnUser = "Select * FROM Win32_LoggedOnUser"Set objLoggedOnUser = objService.ExecQuery(strQueryLoggedOnUser)

For Each u in objLoggedOnUserIf instr(u.Dependent, LogonId) ThenarrAntecedent = Split(u.Antecedent,".")Set objLogFile = objFS.OpenTextFile("C:¥tmp¥demoscript¥userlog.txt",8,True)objLogFile.WriteLine Date & "," & Time & "," & LogonId & "," & _

arrAntecedent(2) & "," & strLogonTypeobjLogFile.CloseWscript.Echo Date & "," & Time & "," & _

LogonId & "," & arrAntecedent(2) & "," & strLogonTypeExit For

End IfNext

Loop

Page 87: PowerShellを使用したWindows Serverの管理

8787

リソース

MSDN - Windows Management Instrumentationhttp://msdn.microsoft.com/en-us/library/aa394582(VS.85).aspx

Script Guy!http://www.microsoft.com/japan/technet/scriptcenter/resources/qanda/default.mspx

Page 88: PowerShellを使用したWindows Serverの管理

8888