Labels

Friday, October 30, 2009

VMware PowerCLI commands

The VMware PowerCLI PowerShell interface provided for managing vSphere systems is a fantastic tool that should be useful for all VMware admins.

I've gathered these commands while implementing and managing ESXi 4.0 clusters, use with caution on any production system.

This is an extension of a previous post:
VMware vSphere PowerCLI commands



Join a cluster by moving an ESX host from one location to the cluster
Move-Inventory -Item (Get-VMHost -Name esxHost) -Destination (Get-Cluster -Name clusterName)

Get the VMware.Vim.ClusterComputeResource MO from the PowerCLI cluster object
$clusterview = get-view $cluster.Id

Reconfigure a host for VMware HA (high availability)
$vmhost = get-vmhost -name esxHost; $hostMO = Get-View -ID $vmhost.ID; $hostMO.ReconfigureHostForDAS()

Find migration events for the last day
$events = Get-VIEvent -Start (Get-Date).AddDays(-1) | where {$_.fullFormattedMessage -match "Migrating.*"}

Find events other than CPU Alarms or user login/logout for the last day
$events = Get-VIEvent -Start (Get-Date).AddDays(-1) | where {$_.fullFormattedMessage -notmatch "Alarm.*CPU.*|User.*logged.*"}

Find events for degraded MPIO path redundancy 
$events = Get-VIEvent -Start (Get-Date).AddDays(-1) | where {$_.fullFormattedMessage -match "Path redundancy to storage.*degraded"}

Report the date, host and description for MPIO path redundancy errors
foreach ($event in $events) {write-output ($event.createdTime.ToString() + "," + $event.host.get_name() + "," + $event.fullFormattedMessage)}

List a table of VI events with only the date and message
$events | format-table -wrap -autosize -property createdTime,fullFormattedMessage

List the physical networks adapters and the current link speed (ESX 4.0)
$hostSystem = get-view -ViewType HostSystem; $hostConfigManager = $hostSystem.get_ConfigManager(); $hostNetworkSystem = $hostConfigManager.get_NetworkSystem(); $netSystem = Get-View $hostNetworkSystem; $netSystem.NetworkConfig.pnic; foreach ($pnic in  $netSystem.NetworkConfig.pnic) {Write-Output ($pnic.Device + "," + $pnic.spec.linkspeed.SpeedMB)}

List the vSwitches and the uplinks currently attached
$hostSystem = get-view -ViewType HostSystem; $hostConfigManager = $hostSystem.get_ConfigManager(); $hostNetworkSystem = $hostConfigManager.get_NetworkSystem(); $netSystem = Get-View $hostNetworkSystem; foreach ($vswitch in  $netSystem.NetworkConfig.vSwitch) {Write-Output ($vSwitch.Name + "," + $vswitch.spec.policy.NicTeaming.NicOrder.ActiveNic)}

Remove snapshots from a group of machines
$VMs = Get-VM -Location (get-folder -name "vmFolder"); foreach ($vm in $vms) {remove-snapshot -snapshot (Get-Snapshot -vm $vm) -confirm:$false}

Take snapshots of a group of machines
$VMs = Get-VM -Location (get-folder -name "vmFolder"); foreach ($vm in $VMs) {New-Snapshot -Name "snapshot 01" -description "Snapshot description" -vm $vm -Quiesce:$false}

Find VM name, description and primary disk datastore
$VMs = get-vm; foreach ($vm in $VMs) {write-output ($vm.Name + ",""" + $vm.Description + """," + $vm.harddisks[0].FileName.Replace(" ", ",")) | out-file -append -filepath c:\temp\VM_Datastores.txt}

Bring a host out of maintenance most
Set-VMHost -VMHost esxHost -State Connected

Generate diagnostic support bundles for all hosts
get-log -vmhost (get-vmhost) -bundle -destinationpath c:\temp\bundles

Find the network adapter type for each VM
$vms = get-vm ; foreach ($vm in $vms) {write-host $vm.Name "-"  $vm.networkadapters[0].type}

Find physical NICs and whether they're set to autonegotiate or hardcoded
foreach ($pnic in $hostNetwork.pnic) {if($pnic.linkSpeed -eq $null) {$ls = "Auto"} else {$ls= $pnic.linkSpeed.speedMB.toString() + ":" + $pnic.linkSpeed.duplex} ;write-output ($pnic.Device + "," + $ls)}

Find host sytem build information
$hostSystems = get-view -ViewType HostSystem; foreach ($hostSystem in $hostSystems) {Write-Output ($hostSystem.Name + "," + $hostSystem.config.product.Fullname)}

Find VMs and whether the VMtools is configured to synchronising time 
$vmSet = Get-VM ; foreach ($vm in $vmSet) { $view = get-view $vm.ID ;$config = $view.config; $tools = $config.tools; Write-Output ($vm.Name + "," + $tools.SyncTimeWithHost) }

Revert to a snapshot
set-vm -vm vmName -snapshot (get-snapshot -vm vmName) -confirm:$false

Remove a virtual machine from inventory and delete from disk
remove-vm -DeleteFromDisk:$true -RunAsync:$true -vm vmName

Shutdown one or more Virtual Machine guests
shutdown-vmguest -vm $vms -confirm:$false

Start one or more Virtual Machine guests
start-vm -vm $vms -confirm:$false

Forcefully power off one or more Virtual Machines
stop-vm $vms -confirm:$false

Get a virtual switch from the specified ESX host
get-virtualswitch -name vSwitch1 -vmhost esxHost

Create a new port group on the specified vSwitch
New-VirtualPortGroup -Name "pgName" -VirtualSwitch $vs

Find ESX memory balloon averages for the last five days
get-stat -entity $hosts -start (Get-Date).AddDays(-5) -finish (Get-Date) -stat mem.vmmemctl.average

Export a list of VMs
$vms | select-object -prop Name | out-file -filepath c:\temp\vms.txt

Export a list of VM guest hostnames 
$vms = get-vm; foreach ($vm in $vms) { write-output $vm.guest.get_HostName()}


Wayne's World of IT (WWoIT), Copyright 2009 Wayne Martin. 


Read more!

Tuesday, October 13, 2009

Service Control Manager Security for non-admins

Allowing non-administrators rights for service control sounds deceptively simple, but unfortunately it’s not. After Windows Server 2003 SP1, the default rights are very focused on administrator-only access for service control.

This post describes how to view and modify the security descriptor for the Service Control Manager (SCM) and individual services as required.

Show the descriptor for SCM:
sc sdshow SCMANAGER

D:(A;;CC;;;AU)(A;;CCLCRPRC;;;IU)(A;;CCLCRPRC;;;SU)(A;;CCLCRPWPRC;;;SY)(A;;KA;;;BA)S:(AU;FA;KA;;;WD)(AU;OIIOFA;GA;;;WD)


In this case, the output shows that by default, Authenticated Users (AU) only have connect, but not enumerate (LC) for SCM.

If you want to allow a non-administrator to connect to the Service Control Manager and enumerate the services, you can modify the security descriptor by using something like the following command to add enumerate, read control and query lock status for Authenticated Users with SCM:
sc sdset SCMANAGER

D:(A;;CCLCRPRC;;;AU)(A;;CCLCRPRC;;;IU)(A;;CCLCRPRC;;;SU)(A;;CCLCRPWPRC;;;SY)(A;;KA;;;BA)S:(AU;FA;KA;;;WD)(AU;OIIOFA;GA;;;WD)


This allows connecting to the SCM and enumerating services. However, if the DACL on the individual services only allows administrators access to the services, then they still won’t be accessible. You’ll need to run specific 'sc sdset' commands against particular services, or use subinacl to change all services with one command.

Note that the sc.exe version with XP does not support this syntax – use the sc.exe on 2003 server.

For individual services, you could then allow query and interrogate with the following command:

subinacl /service \\server\* /grant=domain\user=QSI

Note that to map the ACE flags to the meaning with regards to service control, I went through the following process:

  1. Find the access rights from the flag, eg CC = SDDL_CREATE_CHILD = ADS_RIGHT_DS_CREATE_CHILD (ACE Strings link below)
  2. Find the constant matching this value, eg. 0x1 (ADS_RIGHTS_ENUM Enumeration link below)
  3. Match this to the SCM access right for the hexadecimal value, eg. 0x1 = SC_MANAGER_CONNECT (Service Security and Access Rights link below)
Map between sdshow output, right, hex value and SC/service meaning:

"CC"  ADS_RIGHT_DS_CREATE_CHILD          = 0x1,    SC_MANAGER_CONNECT, SERVICE_QUERY_CONFIG
"DC"  ADS_RIGHT_DS_DELETE_CHILD          = 0x2,    SC_MANAGER_CREATE_SERVICE, SERVICE_CHANGE_CONFIG
"LC"  ADS_RIGHT_ACTRL_DS_LIST            = 0x4,    SC_MANAGER_ENUMERATE_SERVICE, SERVICE_QUERY_STATUS
"SW"  ADS_RIGHT_DS_SELF                  = 0x8,    SC_MANAGER_LOCK, SERVICE_ENUMERATE_DEPENDENTS
"RP"  ADS_RIGHT_DS_READ_PROP             = 0x10,   SC_MANAGER_QUERY_LOCK_STATUS, SERVICE_START, 
"WP"  ADS_RIGHT_DS_WRITE_PROP            = 0x20,   SC_MANAGER_MODIFY_BOOT_CONFIG, SERVICE_STOP
"DT"  ADS_RIGHT_DS_DELETE_TREE           = 0x40,   SERVICE_PAUSE_CONTINUE
"LO"  ADS_RIGHT_DS_LIST_OBJECT           = 0x80,   SERVICE_INTERROGATE
"CR"  ADS_RIGHT_DS_CONTROL_ACCESS        = 0x100   SERVICE_USER_DEFINED_CONTROL
"RC"  READ_CONTROL                       = 0x20000 READ_CONTROL



Access right Description for services and SCM:


SERVICE_QUERY_CONFIG (0x0001) Required to call the QueryServiceConfig and QueryServiceConfig2 functions to query the service configuration. 
SERVICE_CHANGE_CONFIG (0x0002) Required to call the ChangeServiceConfig or ChangeServiceConfig2 function to change the service configuration. Because this grants the caller the right to change the executable file that the system runs, it should be granted only to administrators.  
SERVICE_QUERY_STATUS (0x0004) Required to call the QueryServiceStatusEx function to ask the service control manager about the status of the service. 
SERVICE_ENUMERATE_DEPENDENTS (0x0008) Required to call the EnumDependentServices function to enumerate all the services dependent on the service. 
SERVICE_START (0x0010) Required to call the StartService function to start the service. 
SERVICE_STOP (0x0020) Required to call the ControlService function to stop the service. 
SERVICE_PAUSE_CONTINUE (0x0040) Required to call the ControlService function to pause or continue the service. 
SERVICE_INTERROGATE (0x0080) Required to call the ControlService function to ask the service to report its status immediately. 
SERVICE_USER_DEFINED_CONTROL(0x0100) Required to call the ControlService function to specify a user-defined control code. 
SERVICE_ALL_ACCESS (0xF01FF) Includes STANDARD_RIGHTS_REQUIRED in addition to all access rights in this table. 
READ_CONTROL Required to call the QueryServiceObjectSecurity function to query the security descriptor of the service object. 

SC_MANAGER_CONNECT (0x0001) Required to connect to the service control manager. 
SC_MANAGER_CREATE_SERVICE (0x0002) Required to call the CreateService function to create a service object and add it to the database. 
SC_MANAGER_ENUMERATE_SERVICE (0x0004) Required to call the EnumServicesStatusEx function to list the services that are in the database. 
SC_MANAGER_LOCK (0x0008) Required to call the LockServiceDatabase function to acquire a lock on the database. 
SC_MANAGER_QUERY_LOCK_STATUS (0x0010) 
SC_MANAGER_MODIFY_BOOT_CONFIG (0x0020) Required to call the NotifyBootConfigStatus function. 
SC_MANAGER_ALL_ACCESS (0xF003F) Includes STANDARD_RIGHTS_REQUIRED, in addition to all access rights in this table. 




Directory service object access rights


"RC"  SDDL_READ_CONTROL  READ_CONTROL 
"RP"  SDDL_READ_PROPERTY  ADS_RIGHT_DS_READ_PROP  
"WP"  SDDL_WRITE_PROPERTY  ADS_RIGHT_DS_WRITE_PROP  
"CC"  SDDL_CREATE_CHILD  ADS_RIGHT_DS_CREATE_CHILD  
"DC"  SDDL_DELETE_CHILD  ADS_RIGHT_DS_DELETE_CHILD  
"LC"  SDDL_LIST_CHILDREN  ADS_RIGHT_ACTRL_DS_LIST  
"SW"  SDDL_SELF_WRITE  ADS_RIGHT_DS_SELF  
"LO"  SDDL_LIST_OBJECT  ADS_RIGHT_DS_LIST_OBJECT  
"DT"  SDDL_DELETE_TREE  ADS_RIGHT_DS_DELETE_TREE  
"CR"  SDDL_CONTROL_ACCESS  ADS_RIGHT_DS_CONTROL_ACCESS  



ADS enum:


typedef enum  {
  ADS_RIGHT_DS_CREATE_CHILD          = 0x1,
  ADS_RIGHT_DS_DELETE_CHILD          = 0x2,
  ADS_RIGHT_ACTRL_DS_LIST            = 0x4,
  ADS_RIGHT_DS_SELF                  = 0x8,
  ADS_RIGHT_DS_READ_PROP             = 0x10,
  ADS_RIGHT_DS_WRITE_PROP            = 0x20,
  ADS_RIGHT_DS_DELETE_TREE           = 0x40,
  ADS_RIGHT_DS_LIST_OBJECT           = 0x80,
  ADS_RIGHT_DS_CONTROL_ACCESS        = 0x100 

} ADS_RIGHTS_ENUM;

READ_CONTROL = 0x20000;




References:

Applying Security Descriptors on the Device Object
http://msdn.microsoft.com/en-us/library/ms793368.aspx

Non-administrators cannot remotely access the Service Control Manager after you install Windows Server 2003 Service Pack 1
http://support.microsoft.com/default.aspx?scid=kb;EN-US;907460

Securing a Remote WMI Connection
http://msdn.microsoft.com/en-us/library/aa393266(VS.85).aspx

Configuring a Report Server for Remote Administration
http://msdn.microsoft.com/en-us/library/ms365170(SQL.90).aspx

Service Security and Access Rights
http://msdn.microsoft.com/en-us/library/ms685981(VS.85).aspx

How to grant users rights to manage services in Windows 2000
http://support.microsoft.com/kb/288129

How to troubleshoot WMI-related issues in Windows XP SP2
http://support.microsoft.com/kb/875605

ACE Strings
http://msdn.microsoft.com/en-us/library/aa374928(VS.85).aspx

ADS_RIGHTS_ENUM Enumeration
http://msdn.microsoft.com/en-us/library/aa772285(VS.85).aspx



Wayne's World of IT (WWoIT), Copyright 2009 Wayne Martin. 


Read more!

All Posts

printQueue AD objects for 2003 ClusterVirtualCenter Physical to VirtualVirtual 2003 MSCS Cluster in ESX VI3
Finding duplicate DNS recordsCommand-line automation – Echo and macrosCommand-line automation – set
Command-line automation - errorlevels and ifCommand-line automation - find and findstrBuilding blocks of command-line automation - FOR
Useful PowerShell command-line operationsMSCS 2003 Cluster Virtual Server ComponentsServer-side process for simple file access
OpsMgr 2007 performance script - VMware datastores...Enumerating URLs in Internet ExplorerNTLM Trusts between 2003 and NT4
2003 Servers with Hibernation enabledReading Shortcuts with PowerShell and VBSModifying DLL Resources
Automatically mapping printersSimple string encryption with PowerShellUseful NTFS and security command-line operations
Useful Windows Printer command-line operationsUseful Windows MSCS Cluster command-line operation...Useful VMware ESX and VC command-line operations
Useful general command-line operationsUseful DNS, DHCP and WINS command-line operationsUseful Active Directory command-line operations
Useful command-linesCreating secedit templates with PowerShellFixing Permissions with NTFS intra-volume moves
Converting filetime with vbs and PowerShellDifference between bat and cmdReplica Domain for Authentication
Troubleshooting Windows PrintingRenaming a user account in ADOpsMgr 2007 Reports - Sorting, Filtering, Charting...
WMIC XSL CSV output formattingEnumerating File Server ResourcesWMIC Custom Alias and Format
AD site discoveryPassing Parameters between OpsMgr and SSRSAnalyzing Windows Kernel Dumps
Process list with command-line argumentsOpsMgr 2007 Customized Reporting - SQL QueriesPreventing accidental NTFS data moves
FSRM and NTFS Quotas in 2003 R2PowerShell Deleting NTFS Alternate Data StreamsNTFS links - reparse, symbolic, hard, junction
IE Warnings when files are executedPowerShell Low-level keyboard hookCross-forest authentication and GP processing
Deleting Invalid SMS 2003 Distribution PointsCross-forest authentication and site synchronizati...Determining AD attribute replication
AD Security vs Distribution GroupsTroubleshooting cross-forest trust secure channels...RIS cross-domain access
Large SMS Web Reports return Error 500Troubleshooting SMS 2003 MP and SLPRemotely determine physical memory
VMware SDK with PowershellSpinning Excel Pie ChartPoke-Info PowerShell script
Reading web content with PowerShellAutomated Cluster File Security and PurgingManaging printers at the command-line
File System Filters and minifiltersOpsMgr 2007 SSRS Reports using SQL 2005 XMLAccess Based Enumeration in 2003 and MSCS
Find VM snapshots in ESX/VCComparing MSCS/VMware/DFS File & PrintModifying Exchange mailbox permissions
Nested 'for /f' catch-allPowerShell FindFirstFileW bypassing MAX_PATHRunning PowerSell Scripts from ASP.Net
Binary <-> Hex String files with PowershellOpsMgr 2007 Current Performance InstancesImpersonating a user without passwords
Running a process in the secure winlogon desktopShadow an XP Terminal Services sessionFind where a user is logged on from
Active Directory _msdcs DNS zonesUnlocking XP/2003 without passwords2003 Cluster-enabled scheduled tasks
Purging aged files from the filesystemFinding customised ADM templates in ADDomain local security groups for cross-forest secu...
Account Management eventlog auditingVMware cluster/Virtual Center StatisticsRunning scheduled tasks as a non-administrator
Audit Windows 2003 print server usageActive Directory DiagnosticsViewing NTFS information with nfi and diskedit
Performance Tuning for 2003 File ServersChecking ESX/VC VMs for snapshotsShowing non-persistent devices in device manager
Implementing an MSCS 2003 server clusterFinding users on a subnetWMI filter for subnet filtered Group Policy
Testing DNS records for scavengingRefreshing Computer Account AD Group MembershipTesting Network Ports from Windows
Using Recovery Console with RISPAE Boot.ini Switch for DEP or 4GB+ memoryUsing 32-bit COM objects on x64 platforms
Active Directory Organizational Unit (OU) DesignTroubleshooting computer accounts in an Active Dir...260+ character MAX_PATH limitations in filenames
Create or modify a security template for NTFS perm...Find where a user is connecting from through WMISDDL syntax in secedit security templates

About Me

I’ve worked in IT for over 20 years, and I know just about enough to realise that I don’t know very much.