SlideShare a Scribd company logo
Windows Remote Management
Kirill Nikolaev
MCSE, MCITP
TOC
1.Legacy technologies
1.WMI
2.RPC
2.PowerShell
3.Tools
Windows Remote Management:
Overview
Overview of remote management technologies in Windows-based infrastructure.
Windows Management Instrumentation
• One of the first technologies to manage both local and remote
Windows computers (NT5.0+).
• WMI – Microsoft’s implementation of Web-Based Enterprise
Management (WBEM)
• WBEM – enterprise-grade standard information access technology,
based on Common Information Model (CIM).
• CIM – describes IT infrastructure, its manageable elements and how
they are connected. (http://dmtf.org/standards/cim)
• CIM, WBEM, WMI, in case of Windows – the same thing.
What can you do with WMI:
• Manage local disks, services, event log etc.
• Manage network settings: IP-address, enable/disable DHCP, DNS-
servers.
• Monitor your system: free disk space, for example.
• Retrieve system configuration information: computer name, RAM
size, OS edition, installed updates.
• Retrieve information from installed applications: SCCM, Exchange,
SQL Server.
• etc.
Windows Remote Management - EN
Manageable Resources
Any system component or a component of installed application:
• Local disks
• Event logs
• Services
• SQL Server
• SCCM
• Exchange Server
• System global properties
• Printers
• Shared folders
• Any hardware
WMI Classes
• Every manageable class is a member of another one class.
• Class – description of resource’s properties and available methods.
• Examples:
• Win32_LogicalMemoryConfiguration
• Win32_Service
• Win32_NTLogEvent
• Exchange_Mailbox
• CCM_SoftwareDistributionClientConfig
Windows Remote Management - EN
WMI Providers
• Every resource has its own API.
• WMI uses standardized access model.
• Provides translates WMI requests to manageable resources and vice
versa.
• Providers are just like drivers.
• One provider can present:
• Single class (Registry – StdRegProv)
• Multiple classes (Win32 - Win32_Process, Win32_LogicalDisk etc.)
Provider Examples
Provider DLL Namespace Description
Active Directory dsprov.dll rootdirectoryldap Maps Active Directory objects to WMI
Event Log ntevt.dll rootcimv2 Manages Windows event logs (for example, reads, backs up, clears,
copies, deletes, monitors, renames, compresses, and uncompresses
event log files and changes event log settings)
Performance
Counter
wbemperf.dll rootcimv2 Provides access to raw performance data
Registry stdprov.dll rootdefault Reads, writes, enumerates, monitors, creates, and deletes registry keys
and values
SNMP snmpincl.dll rootsnmp Provides access to SNMP MIB data and traps from SNMP-managed
devices
WDM wmiprov.dll rootwmi Provides access to information about WDM device drivers
Win32 cimwin32.dll rootcimv2 Provides information about the computer, disks, peripheral devices,
files, folders, file systems, networking components, operating system,
printers, processes, security, services, shares, SAM users and groups,
and more
Windows Installer msiprov.dll rootcimv2 Provides access to information about installed software
Exchange Server rootMicrosoftExchangeV2
SCCM rootCCM
Windows Remote Management - EN
WMI Infrastructure
1. WMI Service (winmgmt)
• Manages communication between providers, repository and applications.
2. WMI Repository
• Consists of namespaces (rootdefault, rootcimv2)
• Namespaces are used for access restriction (ala filesystem folders)
• http://wutils.com/wmi/namespaces.html
• Only static data (class definitions)
• At file system - %SYSTEMROOT%System32wbem
Windows Remote Management - EN
How do I access WMI?
If you are programmer: COM API (WMI Component Object Model
(COM) API), Microsoft.Management.Infrastructure (C#)
If you are administrator:
1. GUI
• WMI Explorer
• wbemtest.exe
• WMI Administrative Tools
• Scriptomatic 2.0
• Coretech WMI and PowerShell Browser http://goo.gl/sySC5o
How do I access WMI?
2. CLI
• wmic
• PowerShell
3. Scripting:
• VBScript - Scripting API for WMI (http://goo.gl/EWt23b)
• PowerShell - Get-WmiObject, Get-CimInstance
Demo
WMI Explorer
Questions?
WMI architecture, WMI in general.
Example: VBS – Total Visible Memory
strComputer = "."
Set objWMIService = GetObject("winmgmts:" & strComputer & _
"rootcimv2")
Set colItems = objWMIService.InstancesOf("Win32_OperatingSystem")
For Each objItem In colItems
Wscript.Echo "Total Physical Memory (KB): " & _
objItem.TotalVisibleMemorySize
Next
Example: VBS – Installed Updates
strComputer = "."
Set objWMIService = GetObject("winmgmts:" & strComputer)
Set colItems = objWMIService.ExecQuery(_
"Select * from Win32_QuickFixEngineering")
For Each objItem in colItems
Wscript.Echo "HotFixID: " & objItem.HotFixID
Wscript.Echo "Caption: " & objItem.Caption
Wscript.Echo "Description: " & objItem.Description
Wscript.Echo "InstalledOn: " & objItem.InstalledOn
Next
Example: VBS – Disable User
strComputer = "."
Set objWMIService = GetObject("winmgmts:" & strComputer & _
"rootcimv2")
Set colItems = objWMIService.ExecQuery(_
"SELECT * FROM Win32_UserAccount WHERE Name = 'User'")
For Each objItem In colItems
objItem.Disabled = TRUE
objItem.Put_()
Next
Example: VBS – Restart Service
strComputer = "."
Set objWMIService = GetObject("winmgmts:" & strComputer & "rootcimv2")
Set colServices = objWMIService.ExecQuery _
("SELECT * FROM Win32_Service where Name = 'Themes'")
For Each objService In colServices
Return = objService.StopService()
If Return <> 0 Then
Wscript.Echo "Failed " & VBNewLine & "Error code = " & Return
Else
WScript.Echo "Succeeded"
objService.StartService()
End If
Next
wmic qfe
wmic syntax
• wmic qfe | find "2998527" << external filtering using “find” command
• qfe where HotfixID= "KB2998527" << built-in filtering,
strict compliance only, works in CLI only
• wmic memorychip get Capacity << clear output
while using property’s name
• wmic path win32_QuickFixEngineering get Hotfixid << full path
w/o usage of aliases
Example: wmic – Rich output
wmic /output:C:tempCPU1.htm cpu get Name, MaxClockSpeed,
NumberOfCores, SocketDesignation /format:hform
DCOM (distributed component object model)
• WMI uses it for remote connection.
• Consists of 2 parts:
• COM – standardized Microsoft model for application communication.
• RPC (Remote Procedure Calls) – client-server technology. Used for remote
functions call, transfer of objects etc.
How does RPC work:
CLIENT_PROC
SERVER_PROC
END POINT
MAPPER
0 REG
1 REQ
2 RESP
3 REQ
4 RESP
135PORT
DYNAMICALLYASSIGNED
PORT
Example: VBS – Remote DHCP Enable
strComputer = “CLT1.exchange12rocks.net“
Set objWMIService = GetObject(_
"winmgmts:" & strComputer & "rootcimv2")
Set colNetAdapters = objWMIService.ExecQuery _
("Select * from Win32_NetworkAdapterConfiguration " _
& "where IPEnabled=TRUE")
For Each objNetAdapter In colNetAdapters
errEnable = objNetAdapter.EnableDHCP()
Next
Demo
wbemtest
WinRM
•Microsoft’s implementation of WS-Management
•Single network port – 5985/6 (HTTP/S)
•To enable:
•2003-2008 R2: winrm qc
•2012+: enabled by default
How do I use WinRM?
• Remote interactive shell:
• winrs -r:<ServerName> cmd.exe
• To start a service:
• winrm invoke StartService wmicimv2/Win32_Service?Name=Themes
• Reboot:
• winrm invoke reboot wmicimv2/Win32_OperatingSystem -r:<ServerName>
• Get system info:
• [xml]$osInfo = winrm get wmicimv2/Win32_OperatingSystem /format:pretty
• $osInfo.Win32_OperatingSystem
Questions?
WMI usage in VBScript, wmic, WinRM.
Coffee-break
15 minutes.
PowerShell: Quick Overview
What is PowerShell?
• Script language
• Command-line interface with auto-completion
• Available as built-in from Windows Vista
• Object-oriented – result of each command is an object but no text
string
• “Verb-Noun” system of commands (cmdlets)
• Get-Process
• Stop-Service
• Set-Mailbox
• Easily extensible
PS primitives
• Pipeline – transfers objects between commands:
• Get-Process mmc.exe | Stop-Process
• Variable – text string starting with “$” sign:
• $Counter = 10
• $Files = Get-ChildItem -Path C:temp
• “this” variable ($_) – contains current object:
• 1, 2, 3 | ForEach-Object {echo ($_+5)}
• Properties – each object is described by one or many properties:
• $Files.Count
• Methods – most objects have methods to execute:
• $Files.GetType()
PS Aliases
Short aliases exist for some of the built-in cmdlets:
• where -> Where-Object
• cd -> Set-Location
• man -> help
Main cmdlets
• Get-Help (help)
• Get-Command
• Get-Member
• Select-Object (select)
• Get-Content (gc)
• ForEach-Object (foreach, %)
• Write-Output (echo)
• Where-Object (where)
Comparison operators
-eq - Equal to. Includes an identical value. -Match - Matches a string using regular expressions.
-ne - Not equal to. Includes a different value. -NotMatch - Does not match a string. Uses regular
expressions.
-gt - Greater-than. -Contains - Tells whether a collection of reference
values includes a single test value.
-ge - Greater-than or equal to. -NotContains
-lt - Less-than. -In
-le - Less-than or equal to. -NotIn
-Like - Match using the wildcard character (*). -Replace - Replace operator. Changes the specified
elements of a value.
-NotLike - Does not match using the wildcard
character (*).
Complex Example
$Files | where {$_.LastWriteTime -gt '01.01.2010'} | select Name,
Length
PowerShell: Remoting
Cmdlets: CIM vs. WMI
• Get-WmiObject:
• PowerShell 2.0
• DCOM/RPC
• Get-CimInstance:
• PowerShell 3.0
• WS-Man/HTTP(S)
• Improved compatibility (non-Windows systems, down-level OS)
Example: PS – OLD
$Service = Get-WmiObject -Query "SELECT * FROM
Win32_Service WHERE Name = 'Themes'"
$Return = $Service.ChangeStartMode("Manual")
if ($Return.ReturnValue -eq 0) { "Success" }
else { "$($Return.ReturnValue) was reported" }
Example: PS – NEW
$Return = Invoke-CimMethod -Query "SELECT * FROM
Win32_Service WHERE Name = 'Themes'"
-MethodName 'ChangeStartMode'
-Arguments @{StartMode = 'Manual'}
if ($Return.ReturnValue -eq 0) { "Success" }
else { "$($Return.ReturnValue) was reported" }
Remote-enabled PowerShell-cmdlets
Get-WmiObject Get-EventLog Stop-Computer
Remove-WmiObject Show-EventLog Restart-Computer
Invoke-WmiMethod New-EventLog Get-Service
Register-WmiEvent Remove-EventLog Set-Service
Set-WmiInstance Clear-EventLog Get-Process
Limit-EventLog Get-Counter
Get-WinEvent Get-HotFix
PowerShell Remoting
1. Execute PowerShell commands remotely:
Invoke-Command
2. Interactive remote PowerShell session:
*-PSSession*
PS Remoting – minimum requirements
1. Windows XP SP3
2. .NET Framework 2.0 SP1
3. Windows Management Framework
1. Windows PowerShell 2.0
2. Windows Remote Management (WinRM) 2.0
PS Remoting - activation
• Enable-PSRemoting
• Enabled by default on Windows 2012 and later.
• Remote activation:
• http://gallery.technet.microsoft.com/scriptcenter/Enable-PSRemoting-
Remotely-6cedfcb0
• Network ports: 5985 (HTTP), 5986 (HTTPS) (same as WinRM)
PS Remoting – command execution
Invoke-Command -ComputerName SRV1, SRV2 -ScriptBlock {Get-Process}
• ComputerName accepts any PowerShell-list as an input:
• (Get-Content C:ScriptsServers.txt)
• ScriptBlock accepts both single (with parameters) and multiple cmdlets as an
input:
• {Get-Process mmc | Stop-Process},
• {$myScript}
• -FilePath {C:ScriptsTestScript.ps1}
PS Remoting – RunAs
Invoke-Command … -Credential:
1. (Get-Credential)
2. $cred variable
• $cred = Get-Credential
PS Remoting - Sessions
• Command completion works even if cmdlets aren’t installed at your
box.
• Get-Help, Get-Command works against remote cmdlet set.
• Less typing, commands are shorter – same as you’d run them locally.
PS Remoting – Session cmdlets
• Enter-PSSession
• Exit-PSSession
• Permanent sessions for Invoke-Command cmdlet:
1. $S = New-PSSession $ComputerName
2. Invoke-Command -Session $S -ScriptBlock {Start-Job -ScriptBlock {$Script}}
PS Remoting – Background Jobs
1. Run command as a job:
Invoke-Command SRV1 -ScriptBlock {(Get-ChildItem C: -Recurse).Count} -AsJob
2. Grab the result:
Get-Job -Id 2 | Receive-Job
Useful for long operations, especially with multiple computers.
Questions
PowerShell
Windows Remote Management:
Tools
Tools, which are useful to any network administrator in Windows-based
infrastructure.
Administrative shares
• “Hidden” networks share
• Its name ends with “$” sign. Windows Explorer and “net view” command
don’t show such network shares.
• One for each logical volume:
• C$, D$, E$ etc.
• admin$ - %SYSTEMROOT%
• print$ - contains printer objects
• ipc$ - not a part of a file system. Used for inter-process
communication
By default, accessible by administrators only.
MMC
• Microsoft Management Console – GUI which hosts many
administrative tools to manage your machines locally and remotely.
• Installed at each Windows PC starting from NT4.0
• Many snap-ins ship separately
• Remote Server Administration Tools
• Exchange Management Console
• DPM Administration Console
• Kaspersky Security Center
MMC snap-ins
• Standard Microsoft snap-ins located in “Control PanelAll Control
Panel ItemsAdministrative Tools”
• Most useful for you – “Computer Management”
• You can create your own set of snap-ins and save as a single file
Remote registry
• Depends on “Remote Registry” service
• Use common regedit.exe tool
• File -> Connect network registry
Built-in command-line tools
• tasklist/taskkill
• /s
• shutdown
• /m
• netsh
• -r
• w32tm
• /computer
Sysinternals PsTools
• PsExec - execute processes remotely
• PsFile - shows files opened remotely
• PsGetSid - display the SID of a computer or a user
• PsInfo - list information about a system
• PsPing - measure network performance
• PsKill - kill processes by name or process ID
• PsList - list detailed information about processes
• PsLoggedOn - see who's logged on locally and via resource sharing (full source is included)
• PsLogList - dump event log records
• PsPasswd - changes account passwords
• PsService - view and control services
• PsShutdown - shuts down and optionally reboots a computer
• PsSuspend - suspends processes
Final questions?
Anything.
About me
• Every contact/social networks:
• http://about.me/exchange12rocks
• My technical blog:
• https://exchange12rocks.org

More Related Content

PDF
2013 london advanced-replication
PPTX
Replication and Replica Sets
PPTX
Getting Started with Datatsax .Net Driver
PPTX
Become a Java GC Hero - ConFoo Conference
PDF
Node 관계형 데이터베이스_바인딩
PPTX
MongoDB London 2013: Basic Replication in MongoDB presented by Marc Schwering...
PDF
【Unity】Scriptable object 入門と活用例
PDF
Secure .NET programming
2013 london advanced-replication
Replication and Replica Sets
Getting Started with Datatsax .Net Driver
Become a Java GC Hero - ConFoo Conference
Node 관계형 데이터베이스_바인딩
MongoDB London 2013: Basic Replication in MongoDB presented by Marc Schwering...
【Unity】Scriptable object 入門と活用例
Secure .NET programming

What's hot (20)

PPTX
Grand Central Dispatch
PPTX
Hazelcast
PPTX
Webinar: Replication and Replica Sets
PPT
Lecture 04
PPTX
CloudClustering: Toward a scalable machine learning toolkit for Windows Azure
PDF
Hidden pearls for High-Performance-Persistence
PDF
QA Fest 2019. Антон Молдован. Load testing which you always wanted
PDF
Big Data in Real-Time: How ClickHouse powers Admiral's visitor relationships ...
PPTX
Jafka guide
PPTX
Hazelcast and MongoDB at Cloud CMS
PDF
Nvidia® cuda™ 5 sample evaluationresult_2
PPTX
Don't dump thread dumps
PDF
Cutting Edge Data Processing with PHP & XQuery
PPT
Moar tools for asynchrony!
PPTX
Replication and replica sets
PPTX
MongoDB Live Hacking
PDF
NoSQL @ CodeMash 2010
PDF
Nvidia® cuda™ 5.0 Sample Evaluation Result Part 1
PPTX
Pune-Cocoa: Blocks and GCD
PDF
Ice mini guide
Grand Central Dispatch
Hazelcast
Webinar: Replication and Replica Sets
Lecture 04
CloudClustering: Toward a scalable machine learning toolkit for Windows Azure
Hidden pearls for High-Performance-Persistence
QA Fest 2019. Антон Молдован. Load testing which you always wanted
Big Data in Real-Time: How ClickHouse powers Admiral's visitor relationships ...
Jafka guide
Hazelcast and MongoDB at Cloud CMS
Nvidia® cuda™ 5 sample evaluationresult_2
Don't dump thread dumps
Cutting Edge Data Processing with PHP & XQuery
Moar tools for asynchrony!
Replication and replica sets
MongoDB Live Hacking
NoSQL @ CodeMash 2010
Nvidia® cuda™ 5.0 Sample Evaluation Result Part 1
Pune-Cocoa: Blocks and GCD
Ice mini guide
Ad

Similar to Windows Remote Management - EN (20)

PPTX
Inventory your network and clients with PowerShell
PDF
Win32 Perl Wmi
PPTX
Windows Command Line Tools
PPSX
Automating Windows Server 2008 R2 Administration with Windows PowerShell
PPTX
WMI for Penetration Testers - Arcticcon 2017
PDF
Advanced Pen Testing Techniques-DNS-WMI
PDF
DEFCON 23 - Ballenthin Graeber Teodorescu - WMI Attacks Defense
PPTX
Building Better Backdoors with WMI - DerbyCon 2017
PPSX
Sunil phani's take on windows powershell
PPT
windows administration basics Introduction.ppt
PPTX
Systems Administration
DOC
To Get To The Command Prompt In Windows Xp Go To
PPTX
Windows Server 2008 Management
PPTX
Windows Server 2008 Management
PPT
W7 Enterprise
PPT
W7 for IT Professionals
PPTX
Windows 7 Feature Overview
PPTX
Powershell Tech Ed2009
PPT
Microsoft Operating System Vulnerabilities
Inventory your network and clients with PowerShell
Win32 Perl Wmi
Windows Command Line Tools
Automating Windows Server 2008 R2 Administration with Windows PowerShell
WMI for Penetration Testers - Arcticcon 2017
Advanced Pen Testing Techniques-DNS-WMI
DEFCON 23 - Ballenthin Graeber Teodorescu - WMI Attacks Defense
Building Better Backdoors with WMI - DerbyCon 2017
Sunil phani's take on windows powershell
windows administration basics Introduction.ppt
Systems Administration
To Get To The Command Prompt In Windows Xp Go To
Windows Server 2008 Management
Windows Server 2008 Management
W7 Enterprise
W7 for IT Professionals
Windows 7 Feature Overview
Powershell Tech Ed2009
Microsoft Operating System Vulnerabilities
Ad

Windows Remote Management - EN

  • 1. Windows Remote Management Kirill Nikolaev MCSE, MCITP
  • 3. Windows Remote Management: Overview Overview of remote management technologies in Windows-based infrastructure.
  • 4. Windows Management Instrumentation • One of the first technologies to manage both local and remote Windows computers (NT5.0+). • WMI – Microsoft’s implementation of Web-Based Enterprise Management (WBEM) • WBEM – enterprise-grade standard information access technology, based on Common Information Model (CIM). • CIM – describes IT infrastructure, its manageable elements and how they are connected. (http://dmtf.org/standards/cim) • CIM, WBEM, WMI, in case of Windows – the same thing.
  • 5. What can you do with WMI: • Manage local disks, services, event log etc. • Manage network settings: IP-address, enable/disable DHCP, DNS- servers. • Monitor your system: free disk space, for example. • Retrieve system configuration information: computer name, RAM size, OS edition, installed updates. • Retrieve information from installed applications: SCCM, Exchange, SQL Server. • etc.
  • 7. Manageable Resources Any system component or a component of installed application: • Local disks • Event logs • Services • SQL Server • SCCM • Exchange Server • System global properties • Printers • Shared folders • Any hardware
  • 8. WMI Classes • Every manageable class is a member of another one class. • Class – description of resource’s properties and available methods. • Examples: • Win32_LogicalMemoryConfiguration • Win32_Service • Win32_NTLogEvent • Exchange_Mailbox • CCM_SoftwareDistributionClientConfig
  • 10. WMI Providers • Every resource has its own API. • WMI uses standardized access model. • Provides translates WMI requests to manageable resources and vice versa. • Providers are just like drivers. • One provider can present: • Single class (Registry – StdRegProv) • Multiple classes (Win32 - Win32_Process, Win32_LogicalDisk etc.)
  • 11. Provider Examples Provider DLL Namespace Description Active Directory dsprov.dll rootdirectoryldap Maps Active Directory objects to WMI Event Log ntevt.dll rootcimv2 Manages Windows event logs (for example, reads, backs up, clears, copies, deletes, monitors, renames, compresses, and uncompresses event log files and changes event log settings) Performance Counter wbemperf.dll rootcimv2 Provides access to raw performance data Registry stdprov.dll rootdefault Reads, writes, enumerates, monitors, creates, and deletes registry keys and values SNMP snmpincl.dll rootsnmp Provides access to SNMP MIB data and traps from SNMP-managed devices WDM wmiprov.dll rootwmi Provides access to information about WDM device drivers Win32 cimwin32.dll rootcimv2 Provides information about the computer, disks, peripheral devices, files, folders, file systems, networking components, operating system, printers, processes, security, services, shares, SAM users and groups, and more Windows Installer msiprov.dll rootcimv2 Provides access to information about installed software Exchange Server rootMicrosoftExchangeV2 SCCM rootCCM
  • 13. WMI Infrastructure 1. WMI Service (winmgmt) • Manages communication between providers, repository and applications. 2. WMI Repository • Consists of namespaces (rootdefault, rootcimv2) • Namespaces are used for access restriction (ala filesystem folders) • http://wutils.com/wmi/namespaces.html • Only static data (class definitions) • At file system - %SYSTEMROOT%System32wbem
  • 15. How do I access WMI? If you are programmer: COM API (WMI Component Object Model (COM) API), Microsoft.Management.Infrastructure (C#) If you are administrator: 1. GUI • WMI Explorer • wbemtest.exe • WMI Administrative Tools • Scriptomatic 2.0 • Coretech WMI and PowerShell Browser http://goo.gl/sySC5o
  • 16. How do I access WMI? 2. CLI • wmic • PowerShell 3. Scripting: • VBScript - Scripting API for WMI (http://goo.gl/EWt23b) • PowerShell - Get-WmiObject, Get-CimInstance
  • 19. Example: VBS – Total Visible Memory strComputer = "." Set objWMIService = GetObject("winmgmts:" & strComputer & _ "rootcimv2") Set colItems = objWMIService.InstancesOf("Win32_OperatingSystem") For Each objItem In colItems Wscript.Echo "Total Physical Memory (KB): " & _ objItem.TotalVisibleMemorySize Next
  • 20. Example: VBS – Installed Updates strComputer = "." Set objWMIService = GetObject("winmgmts:" & strComputer) Set colItems = objWMIService.ExecQuery(_ "Select * from Win32_QuickFixEngineering") For Each objItem in colItems Wscript.Echo "HotFixID: " & objItem.HotFixID Wscript.Echo "Caption: " & objItem.Caption Wscript.Echo "Description: " & objItem.Description Wscript.Echo "InstalledOn: " & objItem.InstalledOn Next
  • 21. Example: VBS – Disable User strComputer = "." Set objWMIService = GetObject("winmgmts:" & strComputer & _ "rootcimv2") Set colItems = objWMIService.ExecQuery(_ "SELECT * FROM Win32_UserAccount WHERE Name = 'User'") For Each objItem In colItems objItem.Disabled = TRUE objItem.Put_() Next
  • 22. Example: VBS – Restart Service strComputer = "." Set objWMIService = GetObject("winmgmts:" & strComputer & "rootcimv2") Set colServices = objWMIService.ExecQuery _ ("SELECT * FROM Win32_Service where Name = 'Themes'") For Each objService In colServices Return = objService.StopService() If Return <> 0 Then Wscript.Echo "Failed " & VBNewLine & "Error code = " & Return Else WScript.Echo "Succeeded" objService.StartService() End If Next
  • 24. wmic syntax • wmic qfe | find "2998527" << external filtering using “find” command • qfe where HotfixID= "KB2998527" << built-in filtering, strict compliance only, works in CLI only • wmic memorychip get Capacity << clear output while using property’s name • wmic path win32_QuickFixEngineering get Hotfixid << full path w/o usage of aliases
  • 25. Example: wmic – Rich output wmic /output:C:tempCPU1.htm cpu get Name, MaxClockSpeed, NumberOfCores, SocketDesignation /format:hform
  • 26. DCOM (distributed component object model) • WMI uses it for remote connection. • Consists of 2 parts: • COM – standardized Microsoft model for application communication. • RPC (Remote Procedure Calls) – client-server technology. Used for remote functions call, transfer of objects etc.
  • 27. How does RPC work: CLIENT_PROC SERVER_PROC END POINT MAPPER 0 REG 1 REQ 2 RESP 3 REQ 4 RESP 135PORT DYNAMICALLYASSIGNED PORT
  • 28. Example: VBS – Remote DHCP Enable strComputer = “CLT1.exchange12rocks.net“ Set objWMIService = GetObject(_ "winmgmts:" & strComputer & "rootcimv2") Set colNetAdapters = objWMIService.ExecQuery _ ("Select * from Win32_NetworkAdapterConfiguration " _ & "where IPEnabled=TRUE") For Each objNetAdapter In colNetAdapters errEnable = objNetAdapter.EnableDHCP() Next
  • 30. WinRM •Microsoft’s implementation of WS-Management •Single network port – 5985/6 (HTTP/S) •To enable: •2003-2008 R2: winrm qc •2012+: enabled by default
  • 31. How do I use WinRM? • Remote interactive shell: • winrs -r:<ServerName> cmd.exe • To start a service: • winrm invoke StartService wmicimv2/Win32_Service?Name=Themes • Reboot: • winrm invoke reboot wmicimv2/Win32_OperatingSystem -r:<ServerName> • Get system info: • [xml]$osInfo = winrm get wmicimv2/Win32_OperatingSystem /format:pretty • $osInfo.Win32_OperatingSystem
  • 32. Questions? WMI usage in VBScript, wmic, WinRM.
  • 35. What is PowerShell? • Script language • Command-line interface with auto-completion • Available as built-in from Windows Vista • Object-oriented – result of each command is an object but no text string • “Verb-Noun” system of commands (cmdlets) • Get-Process • Stop-Service • Set-Mailbox • Easily extensible
  • 36. PS primitives • Pipeline – transfers objects between commands: • Get-Process mmc.exe | Stop-Process • Variable – text string starting with “$” sign: • $Counter = 10 • $Files = Get-ChildItem -Path C:temp • “this” variable ($_) – contains current object: • 1, 2, 3 | ForEach-Object {echo ($_+5)} • Properties – each object is described by one or many properties: • $Files.Count • Methods – most objects have methods to execute: • $Files.GetType()
  • 37. PS Aliases Short aliases exist for some of the built-in cmdlets: • where -> Where-Object • cd -> Set-Location • man -> help
  • 38. Main cmdlets • Get-Help (help) • Get-Command • Get-Member • Select-Object (select) • Get-Content (gc) • ForEach-Object (foreach, %) • Write-Output (echo) • Where-Object (where)
  • 39. Comparison operators -eq - Equal to. Includes an identical value. -Match - Matches a string using regular expressions. -ne - Not equal to. Includes a different value. -NotMatch - Does not match a string. Uses regular expressions. -gt - Greater-than. -Contains - Tells whether a collection of reference values includes a single test value. -ge - Greater-than or equal to. -NotContains -lt - Less-than. -In -le - Less-than or equal to. -NotIn -Like - Match using the wildcard character (*). -Replace - Replace operator. Changes the specified elements of a value. -NotLike - Does not match using the wildcard character (*).
  • 40. Complex Example $Files | where {$_.LastWriteTime -gt '01.01.2010'} | select Name, Length
  • 42. Cmdlets: CIM vs. WMI • Get-WmiObject: • PowerShell 2.0 • DCOM/RPC • Get-CimInstance: • PowerShell 3.0 • WS-Man/HTTP(S) • Improved compatibility (non-Windows systems, down-level OS)
  • 43. Example: PS – OLD $Service = Get-WmiObject -Query "SELECT * FROM Win32_Service WHERE Name = 'Themes'" $Return = $Service.ChangeStartMode("Manual") if ($Return.ReturnValue -eq 0) { "Success" } else { "$($Return.ReturnValue) was reported" }
  • 44. Example: PS – NEW $Return = Invoke-CimMethod -Query "SELECT * FROM Win32_Service WHERE Name = 'Themes'" -MethodName 'ChangeStartMode' -Arguments @{StartMode = 'Manual'} if ($Return.ReturnValue -eq 0) { "Success" } else { "$($Return.ReturnValue) was reported" }
  • 45. Remote-enabled PowerShell-cmdlets Get-WmiObject Get-EventLog Stop-Computer Remove-WmiObject Show-EventLog Restart-Computer Invoke-WmiMethod New-EventLog Get-Service Register-WmiEvent Remove-EventLog Set-Service Set-WmiInstance Clear-EventLog Get-Process Limit-EventLog Get-Counter Get-WinEvent Get-HotFix
  • 46. PowerShell Remoting 1. Execute PowerShell commands remotely: Invoke-Command 2. Interactive remote PowerShell session: *-PSSession*
  • 47. PS Remoting – minimum requirements 1. Windows XP SP3 2. .NET Framework 2.0 SP1 3. Windows Management Framework 1. Windows PowerShell 2.0 2. Windows Remote Management (WinRM) 2.0
  • 48. PS Remoting - activation • Enable-PSRemoting • Enabled by default on Windows 2012 and later. • Remote activation: • http://gallery.technet.microsoft.com/scriptcenter/Enable-PSRemoting- Remotely-6cedfcb0 • Network ports: 5985 (HTTP), 5986 (HTTPS) (same as WinRM)
  • 49. PS Remoting – command execution Invoke-Command -ComputerName SRV1, SRV2 -ScriptBlock {Get-Process} • ComputerName accepts any PowerShell-list as an input: • (Get-Content C:ScriptsServers.txt) • ScriptBlock accepts both single (with parameters) and multiple cmdlets as an input: • {Get-Process mmc | Stop-Process}, • {$myScript} • -FilePath {C:ScriptsTestScript.ps1}
  • 50. PS Remoting – RunAs Invoke-Command … -Credential: 1. (Get-Credential) 2. $cred variable • $cred = Get-Credential
  • 51. PS Remoting - Sessions • Command completion works even if cmdlets aren’t installed at your box. • Get-Help, Get-Command works against remote cmdlet set. • Less typing, commands are shorter – same as you’d run them locally.
  • 52. PS Remoting – Session cmdlets • Enter-PSSession • Exit-PSSession • Permanent sessions for Invoke-Command cmdlet: 1. $S = New-PSSession $ComputerName 2. Invoke-Command -Session $S -ScriptBlock {Start-Job -ScriptBlock {$Script}}
  • 53. PS Remoting – Background Jobs 1. Run command as a job: Invoke-Command SRV1 -ScriptBlock {(Get-ChildItem C: -Recurse).Count} -AsJob 2. Grab the result: Get-Job -Id 2 | Receive-Job Useful for long operations, especially with multiple computers.
  • 55. Windows Remote Management: Tools Tools, which are useful to any network administrator in Windows-based infrastructure.
  • 56. Administrative shares • “Hidden” networks share • Its name ends with “$” sign. Windows Explorer and “net view” command don’t show such network shares. • One for each logical volume: • C$, D$, E$ etc. • admin$ - %SYSTEMROOT% • print$ - contains printer objects • ipc$ - not a part of a file system. Used for inter-process communication By default, accessible by administrators only.
  • 57. MMC • Microsoft Management Console – GUI which hosts many administrative tools to manage your machines locally and remotely. • Installed at each Windows PC starting from NT4.0 • Many snap-ins ship separately • Remote Server Administration Tools • Exchange Management Console • DPM Administration Console • Kaspersky Security Center
  • 58. MMC snap-ins • Standard Microsoft snap-ins located in “Control PanelAll Control Panel ItemsAdministrative Tools” • Most useful for you – “Computer Management” • You can create your own set of snap-ins and save as a single file
  • 59. Remote registry • Depends on “Remote Registry” service • Use common regedit.exe tool • File -> Connect network registry
  • 60. Built-in command-line tools • tasklist/taskkill • /s • shutdown • /m • netsh • -r • w32tm • /computer
  • 61. Sysinternals PsTools • PsExec - execute processes remotely • PsFile - shows files opened remotely • PsGetSid - display the SID of a computer or a user • PsInfo - list information about a system • PsPing - measure network performance • PsKill - kill processes by name or process ID • PsList - list detailed information about processes • PsLoggedOn - see who's logged on locally and via resource sharing (full source is included) • PsLogList - dump event log records • PsPasswd - changes account passwords • PsService - view and control services • PsShutdown - shuts down and optionally reboots a computer • PsSuspend - suspends processes
  • 63. About me • Every contact/social networks: • http://about.me/exchange12rocks • My technical blog: • https://exchange12rocks.org

Editor's Notes

  • #5: Windows Management Instrumentation Одна из первых технологий Windows для управления локальным и удалёнными компьютерами. Она предоставляет единый способ управления различными компонентами Windows и другими продуктами, установленными на компьютере.   Немного сокращений: WMI это Майкрософтовская реализация Web-Based Enterprise Management (WBEM). WBEM - это стандартная технология доступа к информации в корпоративных средах. WBEM – частная реализация CIM. Common Information Model (CIM) (схему, описывающую всевозможные поля и их св-ва) для представления информации о системе, приложениях, сетях, устройствах и других управляемых компонентах. Так что когда увидите сокращения CIM, WBEM, WMI знайте, что в случае Windows - речь пойдёт, скорее всего, об одном и том же.
  • #7: Мы пойдём снизу-вверх по этой схеме: Управляемые ресурсы (управляемые объекты): любой компонент системы или установленного приложения. Примеры: Локальные диски Журналы ОС Службы ОС SQL Server SCCM Exchange Сама система Принтеры Общие папки Оборудование   У каждого из них есть свой API (Application Programming Interface), который используют другие компоненты системы для взаимодействия с ресурсом. В WMI каждому управляемому ресурсу соответствует свой собственный класс. Класс - это описание ресурса, его свойств и доступных методов (команд), которые можно выполнить для ресурса.   Примеры классов: Win32_LogicalMemoryConfiguration Win32_Service Win32_NTLogEvent Exchange_Mailbox CCM_SoftwareDistributionClientConfig
  • #10: Провайдер транслирует запросы между службой WMI и непосредственно управляемыми ресурсами. Т.к. у каждого ресурса есть свой собственный API, его нужно перевести к виду стандартной модели доступа, использующейся в WMI. То есть именно они реализуют основное преимущество WMI - универсальность для конечного пользователя, ему не нужно изучать множество различных API.   В этом смысле, провайдеры напоминают драйверы.   Некоторый провайдеры представляют только один класс (Registry - StdRegProv), некоторые - несколько (Win32 - Win32_Process, Win32_LogicalDisk etc.) http://msdn.microsoft.com/en-us/library/aa394570(v=vs.85).aspx
  • #11: Провайдер транслирует запросы между службой WMI и непосредственно управляемыми ресурсами. Т.к. у каждого ресурса есть свой собственный API, его нужно перевести к виду стандартной модели доступа, использующейся в WMI. То есть именно они реализуют основное преимущество WMI - универсальность для конечного пользователя, ему не нужно изучать множество различных API.   В этом смысле, провайдеры напоминают драйверы.   Некоторый провайдеры представляют только один класс (Registry - StdRegProv), некоторые - несколько (Win32 - Win32_Process, Win32_LogicalDisk etc.) http://msdn.microsoft.com/en-us/library/aa394570(v=vs.85).aspx
  • #12: Провайдер транслирует запросы между службой WMI и непосредственно управляемыми ресурсами. Т.к. у каждого ресурса есть свой собственный API, его нужно перевести к виду стандартной модели доступа, использующейся в WMI. То есть именно они реализуют основное преимущество WMI - универсальность для конечного пользователя, ему не нужно изучать множество различных API.   В этом смысле, провайдеры напоминают драйверы.   Некоторый провайдеры представляют только один класс (Registry - StdRegProv), некоторые - несколько (Win32 - Win32_Process, Win32_LogicalDisk etc.) http://msdn.microsoft.com/en-us/library/aa394570(v=vs.85).aspx
  • #13: Служба WMI (winmgmt) и WMI-репозиторий   Репозиторий WMI организован из WMI namespaces. Некоторые (root\default, root\cimv2) установлены в системе по умолчанию, некоторые появляются при установке приложений или добавлении компонентов. Namespaces это аналог папок файловой системы. Они, в основном, используются для разграничения доступа.   В репозитории хранятся только статические данные, такие как описания классов. В основном, все данные, запрашиваемые через WMI являются динамическими и предоставляются в реальном времени. Служба WMI обеспечивает взаимодействие между провайдерами, репозиторием и приложениями, работающими с WMI.
  • #14: Служба WMI (winmgmt) и WMI-репозиторий   Репозиторий WMI организован из WMI namespaces. Некоторые (root\default, root\cimv2) установлены в системе по умолчанию, некоторые появляются при установке приложений или добавлении компонентов. Namespaces это аналог папок файловой системы. Они, в основном, используются для разграничения доступа.   В репозитории хранятся только статические данные, такие как описания классов. В основном, все данные, запрашиваемые через WMI являются динамическими и предоставляются в реальном времени. Служба WMI обеспечивает взаимодействие между провайдерами, репозиторием и приложениями, работающими с WMI.
  • #15: И, наконец, на самом верхнем уровне расположен API самого WMI
  • #20: WQL исполняется на целевом компьютере – меньше траффика. objSWbemServices.InstancesOf("Win32_Service") 157,398 objSWbemServices.ExecQuery("SELECT * FROM Win32_Service") 156,222 strComputer = "." Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") Set colItems = objWMIService.InstancesOf("Win32_OperatingSystem") For Each objItem In colItems Wscript.Echo "Total Physical Memory (KB): " & objItem.TotalVisibleMemorySize Next
  • #21: WQL исполняется на целевом компьютере – меньше траффика. objSWbemServices.InstancesOf("Win32_Service") 157,398 objSWbemServices.ExecQuery("SELECT * FROM Win32_Service") 156,222 strComputer = "." Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") Set colItems = objWMIService.ExecQuery("Select * from Win32_QuickFixEngineering") For Each objItem in colItems Wscript.Echo "HotFixID: " & objItem.HotFixID Wscript.Echo "Caption: " & objItem.Caption Wscript.Echo "Description: " & objItem.Description Wscript.Echo "InstalledOn: " & objItem.InstalledOn Next
  • #22: strComputer = "." Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_UserAccount WHERE Name = 'User'") For Each objItem In colItems objItem.Disabled = TRUE objItem.Put_() Next
  • #23: strComputer = "." Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") Set colServices = objWMIService.ExecQuery _ ("SELECT * FROM Win32_Service where Name = 'Themes'") For Each objService In colServices Return = objService.StopService() If Return <> 0 Then Wscript.Echo "Failed " &VBNewLine & "Error code = " & Return Else WScript.Echo "Succeeded" objService.StartService() End If Next
  • #25: Доп. глаголы: Call – вызов метода Set – задание значения свойства (если оно read/write) Доступные операции: <alias>/path <class> /?
  • #26: wmic /output:C:\temp\CPU1.htm cpu get Name, MaxClockSpeed, NumberOfCores, SocketDesignation /format:hform
  • #27: Мы поговорили о том, как использовать WMI на локальной машине. Но тема-то лекции - удалённое управление компьютерами. Да, всё то, что вы делаете с WMI локально можно проделать и на любом удалённом компьютере (если открыты соответствующие сетевые порты). Для удалённых подключений WMI использует DCOM.   DCOM (distributed component object model) это технология для взаимодействия приложений, в случае, если они расположены на разных компьютерах. DCOM используется не только WMI, но и многими другими приложениями.
  • #28: Как именно работает RPC? Клиент обращается к серверу на TCP 135, с идентификатором приложения, которое ему нужно. Сервер возвращает клиенту динамический (то есть неизвестный заранее) порт, на котором это приложение готово принимать сейчас от этого клиента запросы Клиент начинает общаться с приложением через заданный порт.   Важно понимать, что в случае МСЭ, выбранный сервером динамический порт может быть закрытым на МСЭ. Поэтому, либо ограничиваем динамические порты, до уменьшенного диапазона, который разрешаем на МСЭ, либо убираем МСЭ вообще, либо использует МСЭ с RPC-фильтром, который поймёт, что началось RPC-соединение. http://support.microsoft.com/kb/154596/en-us
  • #29: IPEnabled – протокол TCP/IP активирован на этом адаптере strComputer = "." Set objWMIService = GetObject(_ "winmgmts:\\" & strComputer & "\root\cimv2") Set colNetAdapters = objWMIService.ExecQuery _ ("Select * from Win32_NetworkAdapterConfiguration " _ & "where IPEnabled=TRUE") For Each objNetAdapter In colNetAdapters errEnable = objNetAdapter.EnableDHCP() Next
  • #31: Начиная с Windows Server 2003 R2, MS внедрила в Windows ещё один протокол удалённого управления, WinRM. Как и в случае с WMI, это тоже частная реализация стандартного протокола - WS-Management (Web Services for Management), SOAP-based, все сообщения – XML.   WinRM это тоже средство доступа к WMI, только он не требует открытия большого кол-ва портов, т.к. работает через HTTP(S), вместо DCOM.   По факту, голый WinRM не представляет ничего интересного и революционного, из пользы - только упрощение жизни с файрволами.   Тем не менее, позволяет удалённо выполнять команды при помощи средства WinRS: winrs -r:ServerName cmd.exe   Как активировать (серверная часть)? 2003+ - winrm qc 2012 - включён по умолчанию   Порт 5985/6
  • #32: winrm enumerate wmicimv2/Win32_Service   winrs -r:machinename msiexec.exe /i c:\install.msi /quiet   winrm g wmicimv2/Win32_Processor?DeviceID=CPU0 -fragment:LoadPercentage -r:<some computer>
  • #38: Как вы думаете, какой командлет получает список всех алиасов? Get-Alias
  • #41: $Files = Get-ChildItem -Path C:\temp\ $Files | where {$_.LastWriteTime -gt '01.01.2010'} | select Name, Length
  • #43: *Cim работает через WS-Man (HTTP/HTTPS). Лучше всегда использовать его.
  • #44: Можно использовать параметр -Filter или -Query или pipeline в Where. $Service = Get-WmiObject -Class Win32_Service -Namespace root\cimv2 | Where-Object { $_.name -eq 'Themes' } $Return = $Service.ChangeStartMode("Manual") if ($Return.ReturnValue -eq 0) { "Success" } else { "$($Return.ReturnValue) was reported" } $Return = Invoke-CimMethod -Query "SELECT * FROM Win32_Service WHERE Name = 'Themes'" -MethodName 'ChangeStartMode' -Arguments @{StartMode = 'Manual'} if ($Return.ReturnValue -eq 0) { "Success" } else { "$($Return.ReturnValue) was reported" }
  • #45: Можно использовать параметр -Filter или -Query или pipeline в Where. $Service = Get-WmiObject -Class Win32_Service -Namespace root\cimv2 | Where-Object { $_.name -eq 'Themes' } $Return = $Service.ChangeStartMode("Manual") if ($Return.ReturnValue -eq 0) { "Success" } else { "$($Return.ReturnValue) was reported" } $Return = Invoke-CimMethod -Query "SELECT * FROM Win32_Service WHERE Name = 'Themes'" -MethodName 'ChangeStartMode' -Arguments @{StartMode = 'Manual'} if ($Return.ReturnValue -eq 0) { "Success" } else { "$($Return.ReturnValue) was reported" }
  • #46: В PowerShell есть несколько командлетов, у которых можно указать имя удалённого компьютера. Эти командлеты используют стандартные способы удалённого доступа через RPC, которые мы обсуждали ранее, с соответствующими недостатками. Для других командлетов способа выполнить их на удалённом компьютере - нет.
  • #47: Начиная с PS 2.0 на базе WS-Management и службы WinRM родилась прекраснейшая технология PS remoting. PS remoting позволяет: Выполнять произвольные команды PS на удалённых компьютерах Invoke-Command Удалённую командную строку (ssh для Windows) *-PSSession* Да, у нас была раньше winrs -r:ServerName cmd.exe
  • #48: https://support.microsoft.com/kb/968929
  • #51: Credential хочет на вход объект типа SecureString. Сделать его можно командлетом Get-Credential.
  • #54: Receive-Job на незавершённом задании возвращает те результаты, что уже получены. Задание продолжается. Объекты задания создаются на локальной машине. Для полностью удалённых заданий используйте Invoke-Command -Session $S -ScriptBlock {Start-Job -ScriptBlock {$Script}}
  • #59: В Computer Management подключена оснастка WMI Control, которой управляются разрешения на namespaces.
  • #60: Как удалённо активировать RDP: HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server\fDenyTSConnection=0
  • #62: http://technet.microsoft.com/en-us/sysinternals/bb896649