Labels

Sunday, October 26, 2008

NTLM Trusts between 2003 and NT4

This post includes a few notes and example on an NTLM trust between two domains in a scenario I was working on - creating a trust between a 2003 user domin and an NT4 resource domain.

I realise NT4 was a long time ago, but NT 4.0 was one end of a trust I set up earlier this year (2008), so other people might be in a similar situation. Note that to have a forest trust - even if it's only a one way trust - both the domain and the forest have to be in Windows 2003 functional mode, so whenever you're talking about trusts between external domains/forests, if one side is NT4 or 2000 then it's an NTLM trust.

The types of access through the trust that will need to be considered:

  • Cross-domain resource access, including pass-through authentication, Trusted Client->Trusting Server->Trusting DC->Trusted DC
  • Authenticating access requests for a cross-domain object, Trusting DC -> Trusted DC
  • Using the object picker and retrieving a list of trusted domains and trusted accounts also results in PDC->PDC communication between trusting and trusted.
  • Establishing the trust, the PDC of the trusting NT4 domain will try and resolve and then query the PDC of the trusted domain. TCP and NetBIOS sessions will be established, with named pipes, SMB and RPC. A combination of LSA RPC and Netlogon RPC
  • Sometimes there may be a need to control the DC Locator process on the NT4 DCs to ensure that only the single DC is contacted to authenticate cross-domain access requests. This will be a local lmhosts #PRE #DOM: entry, or a static WINS record, but this would only work when controlling authentication, some other operations require PDC emulator connectivity.

How pass-through authentication across domains between 2003 and NT4 typically works:

  1. Client from 2003 sends a request to the resource server in the NT4 domain
  2. NT4 resource domain server passes the request to a NT4 DC in the local trusting domain
  3. The NT4 DC checks the request is from a trusted domain, then establishes NetBIOS/SMB sessions with a DC in the trusted domain
  4. Netr netlogon RPCs to create a secure channel and authenticate the samlogon request

If you need network security between the trusts, I recommend this be completed in a lab first. Otherwise you will probably end up with the connection between here and there looking like swiss cheese, or at the very least having larger holes than really required. VMware is great for creating a test-lab for this type of exercise, you could reproduce your existing production configuration and monitor the traffic going between various locations - this also requires something of a test network though.

Note that this information can also be used in concert with the 'Replica Domain for Authentication' post to create a trust with a replica of your production domain, reducing the risk of exposing your domain.

Both the RPC and SMB will be over NetBIOS when coming from NT4:

nbname 137/UDP
nbname 137/TCP
nbdatagram
138/UDP
nbsession 139/TCP

In the scenario I was working on, the applications in the resource domain were either accessed via windows authenticated HTTP or direct SQL connectivity. Two examples below show the conversation in authenticating over the trust, between an XP member of the 2003 domain to a member server in the NT4 domain.

Assuming there’s a 2003 member server running IIS using windows authentication in the NT 4.0 resource domain, and XP clients from the corporate forest are accessing the application directly:

  1. Internet Explorer from the workstation initiates a HTTP session with the web server
  2. HTTP 401 is returned by the web server, indicating that authentication is required, with the WWW-Authenticate response headers indicating Negotiate and NTLM are the available schemes.
  3. NTLM Negotiate (0x00000001) is then sent from the client to the server indicating supported NTLM options
  4. The web server responds with a challenge message (0x00000002) for the client to prove their identity
  5. The workstation responds with an authenticate message (0x00000003) – an encrypted challenge response based on the logged on users’ password hash
  6. A Netlogon RPC call is initiated from the web server to the NT 4.0 DC the server has its secure channel with to initiate the samlogon request, providing the username, domain name, challenge, and challenge-response.
  7. The NT 4.0 DC checks the information and determines that it has a trust with the named domain.
  8. The NT 4.0 DC establishes a secure channel with the trusted replica domain (or uses the existing channel)
  9. A second Netlogon RPC call is then passed through to the replica 2003 domain using the same information as the first call (wrapped in NetBIOS in this case)
  10. The replica DC retrieves the hash of the specified user’s password, the original challenge is then encrypted using this hash and compared to the challenge-response provided with the request.
  11. Assuming passwords are synchronised, the hashes match and the trusted netlogon call is successful
  12. The Netlogon call from the web server is also returned as successful
  13. The web page is served to the XP workstation

Connecting across domains to SQL in NT4 from an XP workstation in 2003:

  1. The user starts the local MDE (which has an embedded connection to remote SQL)
  2. The workstation initiates a connection over TCP 1433 to the SQL server
  3. The workstation tries to verify the name/IP of the SQL server, with a reverse lookup DNS query and a NetBIOS Adapter Status Request to the IP over UDP 137 NBNS.
  4. The local Active Directory KDS is queried to see if there is a matching SPN for the requested SQL service. This is unsuccessful and the authentication protocol falls back to NTLM.
  5. A TDS NTLMSSP challenge/response occurs between the workstation and the cross-domain SQL server, including:
    a. The negotiate response from the workstation contains the client name and the database (0x1)
    b. The NT4 challenge from the SQL server (0x2)
    c. The authenticate response messages, containing response to the challenge using the currently logged in credentials (of the XP workstation)
  6. A Netlogon RPC call is initiated from the SQL server to the NT4 DC the server has its secure channel with to initiate the samlogon request, providing the username, challenge, and challenge-response.
  7. The NT4 DC checks the information and determines that it has a trust with the named domain (the 2003 user domain)
  8. The NT4 DC establishes a secure channel with the trusted domain
  9. A second Netlogon RPC call is then passed through to a trusted DC using the same information as the first call
  10. The NT4 DC retrieves the hash of the specified user’s password, the original challenge is then encrypted using this hash and compared to the hash provided with the request.
  11. Assuming the password is correct, the hashes match and the trusted netlogon call is successful across the trust.
  12. The Netlogon call between workstation SQL server is also returned as successful

References

Replica Domain for Authentication
http://waynes-world-it.blogspot.com/2008/08/replica-domain-for-authentication.html

How Domain and Forest Trusts Work
http://technet2.microsoft.com/windowsserver/en/library/f5c70774-25cd-4481-8b7a-3d65c86e69b11033.mspx?mfr=true

Trust Technologies
http://technet2.microsoft.com/windowsserver/en/library/9d688a18-15c7-4d4e-9d34-7a763baa50a11033.mspx?mfr=true

Establishing Trust Relationships
http://www.microsoft.com/technet/archive/winntas/plan/capacityplanning/a03_trst.mspx?mfr=true

NTLM user authentication in Windows
http://support.microsoft.com/kb/102716

Direct hosting of SMB over TCP/IP
http://support.microsoft.com/KB/204279

How to configure a firewall for domains and trusts
http://support.microsoft.com/kb/179442

Windows NT 4.0 tries to resolve manually-typed names by contacting the PDC for the remote user's domain (UDP 138). If that communication fails, a Windows NT 4.0-based computer contacts its own PDC, and then asks for resolution of the name.

Describes some of the network traffic between 2003 trusts, including methods of setting the LSA and Network RPC ports used for various operations.
http://technet2.microsoft.com/windowsserver/en/library/108124dd-31b1-4c2c-9421-6adbc1ebceca1033.mspx?mfr=true

I've also used this document in the past, touching on some topics such as DNS, netlogon optimisation/site synchronisation
http://www.microsoft.com/technet/prodtechnol/windowsserver2003/technologies/directory/activedirectory/mtfstwp.mspx

Forest trust information – the flow and types of traffic for cross-forest authentication, which shows the workstation from the account domain (trusted), contacting a KDC in the resource domain (trusting) for kerberos authentication, often overlooked - this means traffic goes directly from all workstation endpoints to DCs in the resource domain, as opposed to an NTLM trust where DCs normally talk to each other)
http://technet2.microsoft.com/windowsserver/en/library/517b4fa4-5266-419c-9791-6fb56fabb85e1033.mspx?mfr=true

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


Read more!

Tuesday, October 21, 2008

2003 Servers with Hibernation enabled

How many of your 2003 servers have hibernation enabled and you never realised? If you're like me, possibly a few, and I can't think of a scenario where I would want to hibernate a server.

This post provides a simple method of detecting whether hibernation is enabled, and then a command to remotely disable hibernation on each server. It works based on the premise that if hibernation is enabled, you'll have a file called hiberfil.sys on the root of your system drive.

  1. Create a text file called servers.txt listing one server per-line and then run the following command
  2. for /f %i in (servers.txt) do @if exist \\%~i\c$\hiberfil.sys (echo %~i,Enabled) else (echo %~i,Disabled)
  3. Save the output filterd by Disabled (find /i "Disabled" results.txt) and run the following command to disable on each (assuming you have psexec)
  4. for /f %i in (servers_hibernate.txt) do psexec \\%i powercfg /HIBERNATE off

This should automatically delete the hibernation file, reclaiming the hard disk space equal to the RAM of the machine.

Note that this assumes your systemdrive is C: and that you have administrative shares enabled (C$). To accurately distinguish between servers that don't have C:/C$. you could also run a nested if command (which assumes an installation directory of Windows):
for /f %i in (servers.txt) do @if exist \\%~i\c$\windows (if exist \\%~i\c$\hiberfil.sys (echo %~i,Enabled) else (echo %~i,Disabled)) else echo %~i,Not Found

You can also manually run the command to disable hibernation against one server:
psexec \\%server% powercfg /HIBERNATE off

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


Read more!

Sunday, September 28, 2008

Reading Shortcuts with PowerShell and VBS

This post provides a simple method of enumerating shortcuts and retrieving their properties, either using PowerShell or VBScript. There is nothing particularly clever here, but I had a need a while back to use the enumeration, and I wrote the simple powershell equivalent to see how easy it would be. Note that I couldn't easily see a managed code .Net method to process shortcuts, so I fell back on the wscript COM object. More than likely there is a better method (get it? :) than this.

Run the scripts:


powershell . .\ReadShortcut.ps1 -p \\%server%\%share%\folder\path
powershell . .\ReadShortcut.ps1 -f \\%server%\%share%\shortcut.lnk
cscript //nologo "ReadShortcut.vbs" \\%server%\%share%\folder\path
cscript //nologo "ReadShortcut.vbs" \\%server%\%share%\shortcut.lnk

#
param(
   [string] $path = "",
   [string] $file = ""
   )

$WshShell = new-object -comobject "WScript.Shell"       # Instantiate the wscript.shell COM object

if ($path -ne "") {
    $shortcuts = get-childitem -path $path -filter "*.lnk" -rec    # Find all .lnk files, recursing in to subdirectories
    $shortcuts | foreach-object {$WshShell.CreateShortcut($_.FullName) }  # For each file, pass the fullname to the COM object to open the shortcut and enumerate the properties
} elseif ($file -ne "") {
    $shortcut = get-item -path $file       # Get the single file
    if ($shortcut -ne $null) { $WshShell.CreateShortcut($shortcut) }   # If exists, read the shortcut properties
} else {
    write-output "No arguments specified, please use either -p to specify a path or -f for a specific .lnk file"
}

#-------#


'ReadShortcut.vbs
' Read a shortcut or a top-level directory of shortcuts and write the properties to stdout
If WScript.Arguments.UnNamed.Count = 1 Then
 strShortcut = WScript.Arguments.UnNamed(0)
Else
 WScript.Echo "Please supply the name of an lnk file or directory to read, eg c:\test.lnk or c:\shortcuts"
 WScript.Quit(1)
End If

Set objFSO = CreateObject("Scripting.FileSystemObject")

If objFSO.FolderExists(strShortCut) Then      ' Was a directory specified?
 Set objFolder = objFSO.getFolder(strShortcut)     ' Get the folder
 
 For Each objfile in objFolder.Files      ' For each file in the top-level directory
  If objfile.type = "Shortcut" Then     ' Is this file a shortcut?
   Call Readshortcut(objFile.Path, strProperties)   ' yes, read the properties
   dtmCreationDate = objFile.DateCreated
   WScript.Echo dtmCreationDate & "," & strProperties  ' output the results
  End If 
 Next
ElseIf objFSO.FileExists(strShortCut) Then      ' Was an individual file specified?
 Call Readshortcut(strShortcut, strProperties)     ' read the properties of the file
 WScript.Echo strProperties       ' output the results
Else           ' file-not-found
 WScript.Echo "Error: Could not read '" & strShortcut & "'"
 WScript.Quit(2)
End If
Set objFSO = Nothing

Function Readshortcut(ByRef strShortcut, ByRef strProperties)

 set objWshShell = WScript.CreateObject("WScript.Shell")    ' Create the shell object
 set objShellLink = objWshShell.CreateShortcut(strShortcut)   ' Execute the createshortcut method, which also retrieves an existing shortcut
 strProperties = strShortCut & "," & objShellLink.TargetPath & "," & objShellLink.WindowStyle & "," & objShellLink.Hotkey & "," & objShellLink.IconLocation & "," & objShellLink.Description & "," & objShellLink.Arguments & "," & objShellLink.FullName & "," & objShellLink.WorkingDirectory & """"

 ' This propertly can be set, but not read? - objShellLink.RelativePath
 Set objShellLink = Nothing
 Set objWshshell = Nothing
End Function

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


Read more!

Saturday, September 27, 2008

Modifying DLL Resources

While it wouldn't be supported by Microsoft, there are a few methods you can use to modify the resources contained in DLLs - usually useful if you would like to change how a window or dialog box is displayed. The easiest way I've seen is with a program called reshacker.exe.

A practical example is when you might be trying to display a large legal notice text using the standard MS gina on XP - and you can't actually scroll down to view the whole message due to the lack of scroll bars in the legal notice text dialog box.

To add a dialog box to this display in msgina.dll in a XP SP2 machine, you could:

  1. Use reshacker to open msgina.dll, and modify the dialog number 2500 - with 1033 language in my case (en-au)
  2. Edit the control, allowing the WS_VSCROLL option
  3. Recompile the script and save the new DLL.
  4. You'll then either have to modify WFP behaviour, disable it, or to test this I overwrote the cached copy to fool Windows File Protection in system32\dllcache

Any new logon through the interactive console or TS to a workstation with a legal notice text should display it in a dialog box with a scroll bar.

Resource Hacker homepage:
http://angusj.com/resourcehacker/


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


Read more!

Sunday, September 21, 2008

Automatically mapping printers

A while back I came across one of the new 'features' in server 2003 R2, a method of centrally managing printers through the ‘Print Management’ snap-in, and then deploying those printers to workstations or users through a GPO.

This sounds clever, but I believe it's really just an automated method of creating a computer startup/user logon script, which uses a control file to determine which printers are to be installed and then runs a commandline utility to install those printers (pushprinterconnections.exe).

This made me reconsider the approach to managing printers for workstations, and similar or better functionality could be provided by one or more of the methods below:

  1. Use policy to deploy all printers for a building/floor/subnet to workstations. This would be the least management, but probably the least effective as there could be dozens or hundreds of printers per building/floor/subnet.
  2. Have a startup script that automatically adds a default printer when a user first logs on. The default would have to be either based on AD subnets and a mapping file between these subnets and default printers, or possibly based on user information such as location and department, which would be used to query AD/printer names to map appropriate printers, eg a user location of 'Building 1/Floor 2' and department of 'Finance' for a user could easliy be translated to a printer called FINPRINT1 with an AD location of 'Building 1/Floor 2'.
  3. Have a process that exports MAC/PCs connected per floor switch, which would be used as a control file to automatically map printers based on floor. This would typically require assistance from your friendly data communications team.
  4. Use 'DHCP snooping' to further identify where clients are coming from. For example, DHCP relay agent option 82 can be used to insert the switch MAC address/subscriber VLAN/port, SNMP information to the DHCP request packet (when using layer 2 DHCP relay agents as opposed to layer 3 ip helpers). This information could potentially be parsed by the DHCP server to identify the switch/port clients are coming from by parsing the circuit-id/remote-id. The output could be used as a control file to automatically map printers based on floor.
  5. Use the information from 4 and information on floor patching to construct a virtual map of your floors/buildings, which would place one or more workstations close to one or more printers, and map them automatically.
  6. When you build each workstation (this wouldn't work for roaming devices), create a control file that indicates physically where this workstation is located using the Microsoft format for subnet locations, eg Building/Floor 1/West Corner/Pod 4. Populate printer locations to this degree, and then your logon script could search the AD for matching printers and map those that are closest. You could also use this information to create a shortcut called 'Find printers' that uses 'rundll32 dsquery,OpenSavedDsQuery %Config%.qds' to open a saved query file that you've populated with this location. You would then need processes in place to update this control file as the workstation moves, otherwise it becomes incorrect - worse than nothing at all.
  7. Do nothing clever and let users add their own printers

Of course the 'nothing clever' option normally wins out, but in a large organisation one of the options above could add real value, and if done correctly would not be high maintenance.

References:

Manage Printers with New Group Policy Features in Windows Server 2003 R2
http://www.microsoft.com/technet/technetmag/issues/2006/08/ManagePrinters/

RFC 3046 - DHCP Relay Agent Information Option
http://www.faqs.org/rfcs/rfc3046.html

Configuring the DHCP Option 82 for Subscriber Identification
http://www.cisco.com/en/US/docs/switches/lan/catalyst3550/software/release/12.1_13_ea1/configuration/guide/swdhcp82.html



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


Read more!

Saturday, September 13, 2008

Simple string encryption with PowerShell

While looking for a method to obfuscate passwords in script files, I started with securestring input combined with the convertfrom-securestring and convertto-securestring functions. Unfortunately (or fortunately from a security perspective) the securestring seems relevant only for per session/user/process/computer (or a combination thereof).

From documentation these functions use Rijndael symmetric encryption, so I modified another example for a very simple, key-less passphrase-less encryption/decryption of a string. This isn’t even very good obfuscation, let alone encryption, but if you encrypted a password and then reproduce the last 10 lines to decrypt the encrypted string, it’s slightly better than storing passwords in very visible paintext (sort of). I guess this could be obfuscated further by reading the encrypted string from a secured file or registry key.

This could be made as complex as you like with keys and initialisation vectors, but unless you make people enter the key (and then why not just make them enter the password?), there would still be something in plaintext, so I didn’t think there was much point.

I'm still undecided on whether there is any benefit with such simple obfuscation, but I thought I'd post the script nonetheless.



$string = "LongStringToEncryptAsATest"
$string

$r = new-Object System.Security.Cryptography.RijndaelManaged  # use Rijndael symmetric key encryption
$c = $r.CreateEncryptor((1..16), (1..16))    # Set the key and initialisation vector to 128-bytes each of (1..16)
$ms = new-Object IO.MemoryStream
$cs = new-Object Security.Cryptography.CryptoStream $ms,$c,"Write" # Target data stream, transformation, and mode
$sw = new-Object IO.StreamWriter $cs
$sw.Write($String)       # Write the string through the crypto stream into the memory stream
$sw.Close()
$cs.Close()
$ms.Close()
$r.Clear()
[byte[]]$result = $ms.ToArray()      # Byte array from the encrypted memory stream
$encstring = [Convert]::ToBase64String($result)    # Convert to base64 for transport

$encstring         # The encrypted base64 string representation


$Encrypted = [Convert]::FromBase64String($encstring)   # Convert the encrypted string to a byte array
$r = new-Object System.Security.Cryptography.RijndaelManaged  # use Rijndael symmetric key encryption
$d = $r.CreateDecryptor((1..16), (1..16))    # Set the key and initialisation vector to 128-bytes each of (1..16)

$ms = new-Object IO.MemoryStream @(,$Encrypted)    # Create a memorystream from a single-element name/value pair hash table of the byte array
$cs = new-Object Security.Cryptography.CryptoStream $ms,$d,"Read" # Target data stream, transformation, and mode
$sr = new-Object IO.StreamReader $cs     # Read the string through the crypto stream from the encrypted memory stream
write-output $sr.ReadToEnd()      # Write the unencrypted string
$sr.Close()
$cs.Close()
$ms.Close()
$r.Clear()


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


Read more!

Monday, September 8, 2008

Useful NTFS and security command-line operations

The commands below are a subset of the complete command list found in Useful command-lines, and provide different methods to query, modify and report on aspects of NTFS, including security, MFT, ABE, alternate data streams, security templates and SDDL.

Each command-line can be copied and pasted at the command prompt, if you use a batch file you'll need to reference variables with double-percent (%%).


Disable path parsing to access a file using UNC
type "\\?\UNC\server\share\path\file.txt"

Dump file and security attributes on an NTFS filesystem
filestat %file%

Show the ACL in SDDL format using cacls (2003)
cacls c:\ /s

Add authenticated users:R to the root (not OICI) using SDDL with cacls
cacls c:\ /S:"D:PAI(A;OICI;FA;;;BA)(A;;0x1200a9;;;AU)(A;OICI;FA;;;SY)"

Query Storage Report Management global settings (file screening and quotas)
reg query HKEY_LOCAL_MACHINE\Cluster\SRM\Settings\SrmGlobalSettings /v Data

Show the current mounted volumes on the local system
mountvol OR mountvol c:\ /l

Create a hardlink directory entry linking one file to another
fsutil hardlink create %NewFileLink% %ExistingFile%

create symbolic dir, file links, hard links and dir junctions Vista/2008
mklink

Add a string to an alternate stream stored as a $DATA attribute
echo this content will be stored in the file sub stream > test.txt:stream1

Add the contents of a file to an alternate data strem
type file.txt > test.txt:stream1

Create a new file in an alternate stream as part of a directory
md test & echo alternate stream > test:stream1

Display the stream
more <> test:test.exe

Run the executable in the alternate stream
cmd /c start .\test:test.exe

Retrieve the binary file from an alternate data stream (port of Unix Cat)
cat test:test.exe > note.exe

Remove an NTFS alternate data stream (does not maintain timestamps)
type test.txt>test1.txt

Delete an alternate data stream
streams -d test.txt

Dump NTFS info from the MFT for a File Record Segment (unix port)
ntfsinfo -d /dev/hda1 -i 36

Find cluster disk size and free space
echo clusnode1 > clusternodes.txt & echo clusnode2 >> clusternodes.txt & echo clusnode3 >> clusternodes.txt & echo clusnode4 >> clusternodes.txt & wmic /node:@clusternodes.txt path Win32_LogicalDisk WHERE "FileSystem='NTFS' AND Name != 'C:' AND Name != 'D:'" GET SystemName,Name,Size,FreeSpace,VolumeName

Create a security template from the given directory for SDDL secedit processing
for /d %i in (%source%\*.*) do @for /f "tokens=2" %j in ('cacls.exe %i /S') do @echo Processing %~ni & echo "%i",2,%j >> Security.txt

Make test directories from a security template
for /f "tokens=1,2,3,* delims=\," %i in ('"find /i "dir1\dir2" template.inf"') do md "c:\temp\sectest\%j\%k

Reformat the target of a security template for offline testing
for /f "tokens=1,2,3,* delims=\," %i in ('"find /i "dir1\dir2" template.inf"') do @echo "c:\temp\sectest\%j\%k,%l

Remotely configure filesystem NTFS security using a secedit template
psexec \\%server% secedit /configure /db c:\windows\temp\%random%.sdb /cfg c:\windows\security\templates\%template%.inf /log c:\windows\temp\Configure.log


Disable automatic mounting of volumes added to a 2003 system
automount disable
Remove automatic mount points for volumes that no longer exist
automount scrub

Report the NTFS permissions for restore from a SDDL template
setacl -on c:\windows -ot file -actn list -rec cont_obj -lst f:sddl -bckp test.txt

List the file system filters and instances installed on the system
fltmc filters & fltmc instances

Run diskpart to list NTFS volumes remotely
psexec \\%server% cmd /c "echo list volume diskpart find /i "NTFS""

Find local disks other than C: and D: that are NTFS
wmic /node:"%server%" path Win32_LogicalDisk WHERE "FileSystem='NTFS' AND Name != 'C:' AND Name != 'D:'" GET SystemName,Name

Find local disks using powershell and output to CSV
Get-WmiObject -Namespace root\cimv2 -ComputerName %server% -Query "SELECT * from Win32_LogicalDisk WHERE FileSystem='NTFS' AND Description = 'Local Fixed Disk' AND Name != 'C:' AND Name != 'D:'" export-csv c:\disk.csv

Read directories from a security template, checking if they exist
for /f "skip=2 tokens=1 delims=," %i in ('"find /i "OICI" \\%server%\%Template%"') do @if not exist \\%server%\%drive%$%~pi echo \\%server%\%drive%%~pi

Query the NTFS attributes of a file
nfi "C:\windows\system32\notepad.exe"

Report and save the security on one or more NTFS Filesystem objects
ICACLS %object% /save %outputfile%

Reset the inherited DACL flag on an object to not protected, inherit below
setacl -on %Directory% -ot file -actn setprot -op dacl:np

Reset inherited permissions for specified NTFS objects
setacl -on %Directory%\*.* -ot file -actn rstchldrn -rst DACL

Check user home drive permissions from hmDir (top-level)
for /f %i in (%users.txt%) do @for /f "tokens=*" %m in ('"dsquery user -name %i dsget user -hmdir find /i "%i""') do cacls "%m"

Check Access Based Enumeration is enabled on a top-level share
psexec \\%server% abecmd %share%

Check permissions are being inherited
for /f %i in (%users.txt%) do @for /f "tokens=1" %m in ('"dsquery user -name %i dsget user -hmdir find /i "%i""') do @for /d %p in (%m\*.*) do @echo cacls "%p"

Check ownership of files
for /f %i in (%users.txt%) do @for /f "tokens=1" %m in ('"dsquery user -name %i dsget user -hmdir find /i "%i""') do @dir %m /q/s

Process robocopy /l output to find files/data that would be copied
for /f "tokens=2,5 delims=_:" %i in (output.txt) do @If "!User!" NEQ "%i" (@Set User=%i&@Set Line=%i,%j) else (@Set Line=!Line!,%j & @Echo !Line!)

List ACLs in SDDL format
setacl -on %filepath% -ot file -actn list -lst f:sddl

Change the ownership of all subdirectories and files in a folder
subinacl /subdirectorie %Path%\*.* /setowner=%Domain%\%User%

Change the ownership of a folder
subinacl /file %Path% /setowner=%Domain%\%User%

Logical Disk Information
wmic /node:%server% path Win32_LogicalDisk

Physical Disk Information
wmic /node:%server% path Win32_DiskPartition



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


Read more!

Useful Windows Printer command-line operations

The commands below are a subset of the complete command list found in Useful command-lines, and perform various operations against printers on a Windows 200x server.

The commands are useful for querying information from one or more printers, as well as making changes to configuration items for printers, including queues, shares, AD information and drivers. Generally Microsoft Windows printing is relatively simple - but add MSCS clustering, the plethora of PCL unidrv versions out there and badly written third-party drivers - troubleshooting can be quite difficult.

Each command-line can be copied and pasted at the command prompt, if you use a batch file you'll need to reference variables with double-percent (%%).



Use a custom WMIC alias to report printer info from a cluster node in CSV
wmic /node:"%server%" spoolerjobs list /format:table

Use a custom WMIC alias to report sorted HTML printer info from a cluster node
wmic /node:"%server%" spoolerjobs list /format:htable:"datatype=number":"sortby=TotalJobsPrinted"

Use a custom WMIC alias to report a brief summary of printer statistics
wmic /node:"%server%" spoolerjobs list brief /format:htable:"datatype=number":"sortby=TotalJobsPrinted"

Use a custom WMIC alias and xsl to sort print jobs output descending HTML table
wmic /node:"%server%" spoolerjobs list brief /format:"htabledesc-sortby.xsl":"datatype=number":"orderby=descending":"sortby=TotalJobsPrinted" > test.html

Reset inheritance starting at a folder and recursing
icacls \\UNC\Path /reset /t /c

Open a saved printer query window
rundll32 dsquery,OpenSavedDsQuery %Config%.qds

Query HP printers for the page count using SNMP
for /f %i in (Printers.txt) do @echo %i & @snmputil walk %i public printmib.prtMarker.prtMarkerTable.prtMarkerEntry.prtMarkerLifeCount | find /i "value"

Query printers for job counts >= 1
wmic /node:"%server%" path Win32_PerfFormattedData_Spooler_PrintQueue Where "Jobs>=1" Get Name,Jobs,MaxJobsSpooling,JobErrors,OutOfPaperErrors

Query printer information from AD (speed, memory etc)
dsquery * %serverDN% -limit 0 -filter "(&(objectClass=printQueue)(objectCategory=printQueue))" -attr cn printerName driverName printCollate printColor printLanguage printSpooling driverVersion printStaplingSupported printMemory printRate printRateUnit printMediaReady

Export printer information from AD (speed, memory etc)
csvde -f Printers.csv -d %serverDN% -r "(&(objectClass=printQueue)(objectCategory=printQueue))" -l cn,printerName,location,driverName,printCollate,printColor,printLanguage,printSpooling,driverVersion,printStaplingSupported,printMemory,printRate,printRateUnit,printMediaReady

Modify a printer or all printers on a print server to use the winprint processor
setprinter \\%Server%[\%Printer%] 2 pPrintProcessor="WinPrint"

Query the unidrv DLL versions from a list of pingable computers in an OU
for /f %i in ('"dsquery computer %OU_DN% -limit 0 -o rdn"') do @for /f "tokens=3 delims=: " %m in ('"ping -n 1 %i find /i "reply from""') do @for /f "tokens=1-9" %q in ('"filever \\%~i\C$\windows\system32\spool\drivers\w32x86\3\uni*.dll find /i /v "\\%~i""') do @echo %i,%q,%r,%s,%t,%u,%v,%w,%x,%y

check printers are being published in the directory through setprinter
setprinter -show \\%server% 7

Run the 32-bit version of regsvr32 on an x64 platform to register the prnadmin DLL
c:\WINDOWS\SysWOW64\regsvr32 c:\admin\util\prnadmin.dll

Run the 32-bit version of cscript that accesses a 32-bit DLL on x64
c:\WINDOWS\SysWOW64\cscript portmgr.vbs

Use SetPrinter to capture all settings for a printer
for %i in (0 1 2 3 4 5 6 7 8 9) do setprinter -show \\%server%\%printer% %i

Report print queue current length and various performance statistics
wmic /node:"%server%" path Win32_PerfFormattedData_Spooler_PrintQueue Get Name,Jobs,TotalJobsPrinted,TotalPagesPrinted,MaxJobsSpooling,JobErrors,OutOfPaperErrors

List printer drivers on a physical or cluster Windows 2003 server
cscript drvmgr.vbs -l -c \\%server%

Print a test page to one or more printers
for /f "tokens=1-4 delims=," %i in (%Printer.txt%) do cscript prnctrl.vbs -t -b \\%PrintServer%\%i

Given a list of printers, create an LPR port for each
for /f "tokens=1-4 delims=," %i in (%Printer.txt%) do @cscript portmgr.vbs -a -c \\%PrintServer% -p %i -h %k -t LPR -q %i

Given a list of printers, create a printer using the specified driver/port
for /f "tokens=1-4 delims=," %i in (%Printer.txt%) do @cscript prnmgr.vbs -a -c \\%PrintServer% -b %i -m "%j" -r %i

Given a list of printers, set the location, share name and publish in AD
for /f "tokens=1-4 delims=," %i in (%Printer.txt%) do @cscript prncfg.vbs -s -b \\%PrintServer%\%i -h %i -l "%l" +published

Given a list of printers, set glocal default printer properties to duplex
for /f "tokens=1-4 delims=," %i in (%Printer.txt%) do @setprinter \\%PrintServer%\%i 8 "pDevMode=dmDuplex=2,dmCollate=1,dmFields=duplex collate"

Given a list of printers, set printer permissions to allow for queue management
for /f "tokens=1-4 delims=," %i in (%Printer.txt%) do @c:\util\subinacl /printer \\%PrintServer%\%i /grant=%Domain%\%Group%=M

Find printer event log entries for the last 15 minutes
for /f %i in ('cscript //nologo c:\data\scripts\updated\time\finddatetime.vbs') do wmic /node:"%server%" path Win32_NTLogEvent WHERE "SourceName='Print' AND LogFile='System' AND EventCode=10 AND TimeGenerated > '%i'"

Find printer event log entries for the specified user
wmic /node:"%server" path Win32_NTLogEvent WHERE "SourceName='Print' AND LogFile='System' AND EventCode=10 AND User='%Domain%\\%Username%'" Get User,TimeGenerated,InsertionStrings

Automated Printer configuration
rundll32 printui.dll,PrintUIEntry /?

Create a port using prnadmin.dll on a cluster node
cscript portmgr.vbs -a -c \\%PrintServer% -p %Printer% -h %PrinterIP% -t raw -n 9100

Create a printer using prnadmin.dll on a cluster node
cscript prnmgr.vbs -a -c \\%PrintServer% -b %Printer% -m "HP Universal Printing PCL 6" -r %Printer%

Set printer configuration using prnadmin.dll on a cluster node
cscript prncfg.vbs -s -b \\%PrintServer%\%Printer% -h %Printer% -l "Building/Level 1" +published

Dump printer log entries
dumpel -s \\%PrintServer% -l System -e 10 -m Print -d 1

Add an x64 print driver to a cluster node
rundll32 printui.dll,PrintUIEntry /ia /c \\%PrintServer% /m "HP Color LaserJet 8550 PCL 5c" /h "x64" /v "Windows XP and Windows Server 2003" /f hpc8550t.inf

Add an x86 print driver to a cluster node
rundll32 printui.dll,PrintUIEntry /ia /c \\%PrintServer% /m "HP Color LaserJet 8550 PCL 5c" /h "x86" /v "Windows 2000, Windows XP and Windows Server 2003" /f hpc8550b.inf

Add to the permissions on a printer
subinacl /printer \\%PrintServer%\%Printer% /grant=%Domain%\%Group%=M

List the printers on a server
cscript "c:\Program Files\Windows Resource Kits\Tools\prnmgr.vbs" -l -c \\%PrintServer% find /i "printername"

Set the glocal default printer properties to allow duplexing
setprinter \\%PrintServer%\%i 8 "pDevMode=dmDuplex=2,dmCollate=1,dmFields=duplex collate"

Query the printers published against a specific computer account
dsquery * %ComputerDN%" -attr printShareName

Query all printers published in the Active Directory
dsquery * domainroot -filter "(objectCategory=printQueue)" -limit 0

Show the current default settings send down to clients from a printer
setprinter -show \\%printServer%\%Printer% 8

Find the print processor used by all printers on a print server
setprinter -show \\%server% 2 findstr /c:"pPrinterName" /c:"pPrintProcessor"

Check through SNMP whether a printer supports a duplexing media path
snmputil walk %printer% public printmib.prtMediaPath.prtMediaPathTable.prtMediaPathEntry.prtMediaPathDescription

Check through SNMP the printer device model
snmputil getnext %printer% public host.hrDevice.hrDeviceTable.hrDeviceEntry.hrDeviceDescr

View/Modify the ACL security on spooler pipe
pipesec \\%computer%\pipe\spoolss

Query printer tray configuration of printers on a cluster (HP UPD)
for /f %i in (Printers.txt) do @for /f "tokens=1,2,*" %m in ('"reg query \\%PrintServer%\HKEY_LOCAL_MACHINE\Cluster\Resources\%ClusterResourceGUID%\Parameters\Printers\%i\PrinterDriverData /v InputSlot 2>nul find /i "InputSlot" & if errorlevel 1 echo 1 2 NotFound"') do @echo %i,%o>>PrinterTrays.txt

Use SNMP to get the printer media path, indicating simplex/duplex capabilities
for /f %i in (Printers.txt) do @for /f "tokens=3,*" %m in ('"snmputil walk %i public printmib.prtMediaPath.prtMediaPathTable.prtMediaPathEntry.prtMediaPathDescription 2>nul find /i "value" & if errorlevel 1 echo 1 2 3 NotFound"') do @echo %i,%n



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


Read more!

Useful Windows MSCS Cluster command-line operations

The commands below are a subset of the complete command list found in Useful command-lines, and are command-line operations for Microsoft Windows MSCS server clusters. Most commands are based around the Microsoft cluster.exe utility, with some using WMI, defrag and diruse to provide information on cluster disk resources.

Each command-line can be copied and pasted at the command prompt, if you use a batch file you'll need to reference variables with double-percent (%%).


Find cluster disk size and free space in CSV format
wmic /node:"%server%","%server%","%server%","%server%" path Win32_LogicalDisk WHERE "FileSystem='NTFS' AND Name != 'C:' AND Name != 'D:'" GET SystemName,Name,Size,FreeSpace,VolumeName /format:csv

Find cluster disk size and free space in modified CSV format with thousand sep.
wmic /node:"%server%","%server%","%server%","%server%" path Win32_LogicalDisk WHERE "FileSystem='NTFS' AND Name != 'C:' AND Name != 'D:'" GET Name,Size,FreeSpace,VolumeName /format:csv2

Report the windows MSCS cluster virtual groups
cluster /cluster:%cluster% group /prop | find /i "description" | find /i /v "pbx" | find /i /v "cluster"

Report folders being archived from Enterprise Vault EV FSA
sqlcmd -S sqlServer%\%instance% -o ArchivedFolders.txt -d %enterprisevaultdirectory% -W -s "," -Q "select FSVP.UncName, FSVP.VolumeName, FSFE.FolderPath, FSVP.UncName + '\' + FSVP.VolumeName + '\' + FSFE.FolderPath as 'Path' from dbo.FileServerFolderEntry FSFE inner join dbo.vw_FileServer_Volume_Policy FSVP on FSFE.VolumeEntryID = FSVP.VolumeEntryID"

Report folders from the one or more servers not being archived compared to FSA export
for %i in (\\%server%\share% \\%server%\share% ) do @for /f "tokens=1-4,*" %m in ('"dir %i\* /ad /tc | find "DIR" | find "-""') do @find /i "%q" ArchivedFolders.txt >nul & @If errorlevel 1 (echo %q,%i,%m %n %o) >> NotArchived.csv

Delete a cluster resource type
cluster restype "%resource_name%" /delete /type

Find cluster disk size and free space
echo clusnode1 > clusternodes.txt & echo clusnode2 >> clusternodes.txt & echo clusnode3 >> clusternodes.txt & echo clusnode4 >> clusternodes.txt & wmic /node:@clusternodes.txt path Win32_LogicalDisk WHERE "FileSystem='NTFS' AND Name != 'C:' AND Name != 'D:'" GET SystemName,Name,Size,FreeSpace,VolumeName

show the MSCS cluster multicast address properties
cluster /cluster:%Cluster% network "%PublicNetwork%" /priv

Find the MSCS cluster resources
cluster /cluster:%Cluster% res /prop find /i "sr"

Find the disks currently owned by each cluster node
for %i in (%server1% %server2%) do @wmic /node:"%i" path Win32_LogicalDisk WHERE "FileSystem='NTFS' AND Name != 'C:' AND Name != 'D:'" GET SystemName,Name find /i "%server_prefix%"

In a 2003 cluster, find each disk volume and analyse file fragmentation
for /f "tokens=2,5,6,8" %i in ('"cluster /cluster:%cluster% resource /prop find /i "disk" find /i "description" find /i "%CommonTag%""') do echo \\%i\%k %j %l>> Defrag_%i_%j.txt && psexec \\%i defrag %k -a -v >> Defrag_%i_%j.txt

From cluster defrag analysis, print out details for each cluster volume
for /f "tokens=1,* delims=:" %i in ('"findstr /i /c:%server% /c:"Total files" /c:"Volume size" /c:"Used space" /c:"Percent free space" /c:"Total fragmented files" defrag*"') do @echo %j

Create a cluster file share:
cluster /cluster:%cluster% res "%share_res_name%" /create /group:"%group%" /type:"File Share"
cluster /cluster:%cluster% res "%share_res_name%" /priv path="%path%"
cluster /cluster:%cluster% res "%share_res_name%" /priv Sharename=%share_name%
cluster /cluster:%cluster% res "%share_res_name%" /priv Remark="File Share Remark"
cluster /cluster:%cluster% res "%share_res_name%" /prop Description="File Share Description"
cluster /cluster:%cluster% res "%share_res_name%" /priv security=Everyone,grant,F:security
cluster /cluster:%cluster% res "%share_res_name%" /AddDep:"%networkname_res%"
cluster /cluster:%cluster% res "%share_res_name%" /AddDep:"%disk_res%"
cluster /cluster:%cluster% res "%share_res_name%" /On

Create an ABE resource for the file share
cluster /cluster:%cluster% res "%shareabe_res_name%" /create /group:"%group%" /type:"Generic Application"
cluster /cluster:%cluster% res "%shareabe_res_name%" /priv CommandLine="cmd.exe /k abecmd.exe /enable %share_name%"
cluster /cluster:%cluster% res "%shareabe_res_name%" /priv CurrentDirectory="%SystemRoot%"
cluster /cluster:%cluster% res "%shareabe_res_name%" /priv InteractWithDesktop=0
cluster /cluster:%cluster% res "%shareabe_res_name%" /priv UseNetworkName=0
cluster /cluster:%cluster% res "%shareabe_res_name%" /prop SeparateMonitor=1
cluster /cluster:%cluster% res "%shareabe_res_name%" /prop Description="Access Based Enumeration for %share_name% File Share"
cluster /cluster:%cluster% res "%shareabe_res_name%" /AddDep:"%networkname_res%"
cluster /cluster:%cluster% res "%shareabe_res_name%" /AddDep:"%disk_res%"
cluster /cluster:%cluster% res "%shareabe_res_name%" /AddDep:"%share_res_name%"
cluster /cluster:%cluster% res "%shareabe_res_name%" /On



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


Read more!

Useful VMware ESX and VC command-line operations

The commands below are a subset of the complete command list found in Useful command-lines, and are a combination of ESX service console commands, PowerShell VI Toolkit or SQL commands (reading from a VirtualCenter database). Note that these have been tested on VI3 - ESX 3.0.x, VC 2.0.x, and some have also been used on VI3.5 - ESX 3.5 / VC 2.5.

Each command-line can be copied and pasted at the command prompt, if you use a batch file you'll need to reference variables with double-percent (%%).

ESX service console


Report the hosts controlled by a VirtualCentre instance
sqlcmd -S %sqlServer% -d %Database% -W -s "," -Q "select [Name] from vpxv_hosts order by [Name]"

Report the hosts controlled by a VirtualCentre instance
sqlcmd -S %sqlServer% -d %Database% -W -s "," -Q "select DNS_Name, IP_Address, PRODUCT_FULLNAME from vpx_host Order by DNS_Name"

Query the Virtual Centre/VC database for Virtual Machine LUN mapping and size
sqlcmd -S %sqlServer% -d %Database% -W -s "," -Q "select VMS.Name, TDS.Name, Cast(Round(Sum(Cast(VDISK.CAPACITY as numeric))/1024/1024/1024, 1) as int) as 'Total Disk', Cast(Round(Sum(Cast(VDISK.FREE_SPACE as numeric))/1024/1024/1024, 1) as int) as 'Free Disk' from vpxv_vms VMS inner join vpxv_vm_datastore VVMDS on VMS.VMID = VVMDS.VM_ID inner join vpx_datastore TDS on VVMDS.DS_ID = TDS.ID inner join VPX_GUEST_DISK VDISK on VMS.VMID = VDISK.VM_ID group by VMS.Name, TDS.Name Order by TDS.Name, VMS.Name"

Allow Dell OpenManage Server Administrator traffic through ESX
esxcfg-firewall -o 1311,tcp,in,OpenManageRequest

Dump the VMware IP config
cat /proc/vmware/net/tcpip/ifconfig

View network traffic in the vswif service console interface
/usr/sbin/tcpdump -i vswif0 grep -v ssh

Check the Legato AAM HA agent
cat /opt/LGTOaam512/log/aam_config_util_addnode.log

VMware HA Legato AAM, list the cluster manager
/opt/LGTOaam512/bin/ftcli -domain vmware -timeout 60 -cmd "listrules"
(run 'FT_DIR=/opt/LGTOaam512' and then 'export FT_DIR' first)

VMware HA Legato AAM, list the cluster nodes
/opt/LGTOaam512/bin/ftcli -domain vmware -connect %node% -port 8042 -timeout 60 -cmd "listnodes"
(run 'FT_DIR=/opt/LGTOaam512' and then 'export FT_DIR' first)

Query ESX for SNMPD service firewall configuration
esxcfg-firewall -q snmpd

Query vmfs volumes for snapshot files from the console
ls -Ral /vmfs/volumes/*.* grep .vmsn

Change security on a file in the ESX service console
chmod u+rwx,g+rx,o+rx somefile

Register a Virtual Machine in ESX
vmware-cmd -s register "/path/to/vmx/or/vmtx"

unregister a Virtual Machine in ESX
vmware-cmd -s unregister "/path/to/vmx/or/vmtx"

Enable SSH client out on an ESX host firewall, permitting SCP as well
esxcfg-firewall -e sshClient

Query the ESX firewall to determine whether SSH client is allowed out
esxcfg-firewall -q grep sshClient

Query the VirtualCenter Database

Query VMs and their MAC addresses from the VC database
sqlcmd -S %sqlServer% -d %Database% -W -s "," -q "select ENT.Name, NET.MAC_Address from VPX_GUEST_NET_ADAPTER NET inner join VPX_ENTITY ENT on NET.VM_ID = ENT.ID"

Query the Virtual Centre/VC database for Virtual Machine Disk Totals
sqlcmd -S %sqlServer% -d %Database% -W -s "," -Q "select VM.Name, Cast(Round(Sum(Cast(VDISK.CAPACITY as numeric))/1024/1024/1024, 1) as int) as 'Total Disk', Cast(Round(Sum(Cast(VDISK.FREE_SPACE as numeric))/1024/1024/1024, 1) as int) as 'Free Disk' from dbo.VPX_GUEST_DISK VDISK inner join VPXV_VMS VM on VDISK.VM_ID = VM.VMID group by VM.Name compute sum(Cast(Round(Sum(Cast(VDISK.CAPACITY as numeric))/1024/1024/1024, 1) as int))"

Query the Virtual Centre/VC database for Virtual Machine Disk information
sqlcmd -S %sqlServer% -d %Database% -W -s "," -Q "select VM.Name, VDISK.* from dbo.VPX_GUEST_DISK VDISK inner join VPXV_VMS VM on VDISK.VM_ID = VM.VMID"

Query the Virtual Centre/VC database for Virtual Machine Disk Total
sqlcmd -S %sqlServer% -d %Database% -W -s "," -Q "select Cast(Round(Sum(Cast(VDISK.CAPACITY as numeric))/1024/1024/1024, 1) as int) from dbo.VPX_GUEST_DISK VDISK"

Query VirtualCentre for hot migration events
sqlcmd -S %sqlServer% -d %Database% -W -s "," -Q "select Create_Time as 'Relocation Start', UserName, VM_Name, Host_Name as 'Host Source', (select Host_Name from dbo.VPX_EVENT Where Chain_ID = EVTDEST.Chain_ID and event_type = 'vim.event.VmMigratedEvent') as 'Host Destination', ComputeResource_Name, DataCenter_Name from dbo.VPX_EVENT EVTDEST where event_type = 'vim.event.VmBeingHotMigratedEvent'"

Query VirtualCentre for migration events
sqlcmd -S %sqlServer% -d %Database% -W -s "," -Q "select Create_Time as 'Relocation Start', UserName, VM_Name, Host_Name as 'Host Source', (select Host_Name from dbo.VPX_EVENT Where Chain_ID = EVTDEST.Chain_ID and event_type = 'vim.event.VmRelocatedEvent') as 'Host Destination', ComputeResource_Name, DataCenter_Name from dbo.VPX_EVENT EVTDEST where event_type = 'vim.event.VmBeingRelocatedEvent'"

Query VirtualCentre for DRS migration events
sqlcmd -S %sqlServer% -d %Database% -W -s "," -Q "select Create_Time as 'Relocation Finished', VM_Name, Host_Name as 'Host Destination', (select Host_Name from dbo.VPX_EVENT Where Chain_ID = EVTDEST.Chain_ID and event_type = 'vim.event.VMBeingHotMigratedEvent') as 'Host Source', ComputeResource_Name, DataCenter_Name from dbo.VPX_EVENT EVTDEST where event_type = 'vim.event.DrsVmMigratedEvent'"

Query the Virtual Centre/VC database for Virtual Machine details
sqlcmd -S %sqlServer% -d %Database% -W -s "," -Q "select ENT.Name as 'Name', DNS_Name as 'DNS Name', Guest_OS as 'OS', Mem_Size_MB as 'Mem', Num_VCPU as 'CPU', Num_NIC as 'NIC', IP_Address as 'IP', NET.MAC_Address as 'MAC Address', VM.FILE_Name as 'VMX location' from vpx_vm VM inner join VPX_GUEST_NET_ADAPTER NET on VM.ID = NET.VM_ID inner join VPX_ENTITY ENT on VM.ID = ENT.ID where dns_name like '%'"

Query the Virtual Centre/VC database for Virtual Machine snapshots (GMT+10)
sqlcmd -S %sqlServer% -d %Database% -W -s "," -Q "select ENT.Name as 'Name', DNS_Name as 'DNS Name', Guest_OS as 'OS', Mem_Size_MB as 'Mem', IP_Address as 'IP', VM.FILE_Name as 'VMX location', VM.Suspend_Time as 'Suspend Time', VM.Suspend_Interval as 'Suspend Interval', VMS.Snapshot_Name as 'Snapshot Name', VMS.Snapshot_Desc 'Snapshot Description', DateAdd(Hour, 10, VMS.Create_Time) as 'Snapshot Time', VMS.Is_Current_Snapshot 'Current Snapshot' from vpx_vm VM inner join VPX_GUEST_NET_ADAPTER NET on VM.ID = NET.VM_ID inner join VPX_ENTITY ENT on VM.ID = ENT.ID inner join VPX_SNAPSHOT VMS on VM.ID = VMS.VM_ID

Query the Virtual Centre/VC database for Virtual Machine LUN attachments
sqlcmd -S %sqlServer% -d %Database% -W -s "," -Q "select VMS.Name, TDS.Name from vpxv_vms VMS inner join vpxv_vm_datastore VVMDS on VMS.VMID = VVMDS.VM_ID inner join vpx_datastore TDS on VVMDS.DS_ID = TDS.ID Order by VMS.Name"

Query the Virtual Centre/VC database for Virtual Machine config LUN
sqlcmd -S %sqlServer% -d %Database% -W -s "," -Q "select VMS.Name as 'VM Name', TDS.Name as 'Config Datastore', SubString(ConfigFileName, CharIndex('/', ConfigFileName, Len('sanfs://vmfs'))+1, 255) as 'Config Path' from vpxv_vms VMS inner join vpx_datastore TDS on TDS.Storage_URL = SubString(VMS.ConfigFileName, 1, CharIndex('/', VMS.ConfigFileName, Len('sanfs://vmfs'))) Order By 'Config Datastore'"

Query the Virtual Centre/VC database for volume total and free disk space
sqlcmd -S %sqlServer% -d %Database% -W -s "," -Q "select Name, Cast(Round(Cast(Capacity as numeric)/1024/1024/1024, -1) as int) as 'Total Space', Cast(Round(Cast(Free_Space as numeric)/1024/1024/1024, -1) as int) as 'Free Space', Type from vpx_Datastore"

Find VM distribution on VMware cluster physical nodes
sqlcmd -S %sqlServer% -d %Database% -W -s "," -Q "Select VH.DNS_NAME as 'Host', count(VM.HOST_ID) from vpx_vm VM inner join vpx_host VH on VM.HOST_ID = VH.ID group by VM.HOST_ID, VH.DNS_NAME order by 'Host'"

Query the Virtual Centre/VC database for VM CPU alarms
sqlcmd -S %sqlServer% -d %Database% -W -s "," -Q "select ALR.Created_Time, ENT.Name from vpx_alarm_runtime ALR inner join vpx_alarm AL on ALR.Alarm_ID = AL.Alarm_ID inner join vpx_entity ENT on ALR.Entity_ID = ENT.ID where AL.Name = 'Virtual Machine CPU Usage' order by created_time"

PowerShell VI Toolkit

Use the VI Toolkit Powershell snap-in to query for snapshots
Get-VM Get-Snapshot export-csv -path c:\temp\VMsnapshots.csv

Use the VI Toolkit Powershell snap-in to query for snapshot information
Get-VM Get-Snapshot foreach-object {$out= $_.VM.Name + "," + $_.Name + "," + $_.Description + "," + $_.PowerState; $out}

ESX Server Advanced Configuration Options

Hide LUNs with advanced ESX options
disk.MaskLUNs: vmhba0:0:4-5;vmhba1:0:4-5

Other

SNMP check against ESX
Snmputil.exe get %host% %community% .iso.org.dod.internet.private.enterprises.6876.1.1.0




Wayne's World of IT (WWoIT), Copyright 2008 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.