Showing posts with label windows. Show all posts
Showing posts with label windows. Show all posts

Thursday, July 31, 2014

Poor man's IP to to Username, using Powershell & Domain Controller logs

This customer had many offices and needed to get rid of Windows XP machines.
Due to the lack of inventory and computer management, we were unable to know who were the people behind them!
Ping and remote access were shut off from the host so we couldn't gather information via WMI.

But the LastLogonTimeStamp was being updated for these computers which led us to believe they were still in use.
The solution I came up with : if someone was still using these XP machines, they were authenticating against the domain controllers, and a "logon event" was created with the source ip and the username.

Once you load the quick and dirty function called "Get-UserName-for_PC-by-DC-events (silly name sorry), run these 2 commands to get some results

Import-module ActiveDirectory
Get-ADComputer -Filter {Enabled -eq $true -and operatingsystem -like '*xp*'} -Properties IPv4Address | %{Get-UserName-for-PC-by-DC-events -DCname "DC01" -Ip $_.IPv4Address}

7/31/2014 1:18:33 PM  --  john.doe at this address -->  10.26.1.15  using  Kerberos


A nice enhancement would be to query all domain controllers.
Finally, your mileage may vary depending on how big your security logs are, how often they rotate and how often these XP users log on (you could run a scheduled task)
Function Get-UserName-for-PC-by-DC-events
{
  param(
        [Parameter(Mandatory=$True)]
        [string]$DCname,
        [Parameter(Mandatory=$True)]
        [string]$Ip
       )
    $xpathfilter = 'Event[System[EventID=4624] and EventData[Data[@Name="IpAddress"]="'+$ip+'"]]'

    Foreach ($event in get-winevent -ComputerName $DCname -LogName Security -FilterXPath $xpathfilter -MaxEvents 1)
    {
        Write-host $event.TimeCreated " -- " $event.Properties[5].Value "at this address --> " $event.Properties[18].Value " using " $event.Properties[9].Value

    }
}

Wednesday, July 16, 2014

DCHP server migration from Debian to Windows Server 2008

My customer wanted to migrate DHCP server function from Debian Wheezy 7.50 running ISC-DHCP to Windows Server 2008.
The task can broken in 6 parts

  1. parse dhcpd.conf on the DHCP server (Linux)
  2. import the parsed file to your *new* DHCP server
  3. setup DHCP role on *new*server
  4. run a script on the *new* DHCP server which creates scopes,pools and reservations (Windows) according to the parsed file.
  5. manually rename the scopes to "friendly" names
  6. manually set the server,scope and/or reservation options and scope lease times
Parse dhcpd.conf
get this great AWK parser onto the Debian box https://gist.github.com/mattpascoe/4039747
make it executable
chmod +x dhcpparse.awk
parse the file
cat /etc/dhcp/dhcpd.conf | dhcpparse.awk > dhcp-config.txt

Import the parsed file to your Windows Server
have a look at it to remove errors.
Setup DHCP role on Windows Server
skipping this part as it's pretty self explanatory
Run script
You will need this Powershell module , referred to as "Microsoft.DHCP.Powershell.Admin.psm1" in the script. If Window Server is version 2012 R2 , I guess you can use the DHCP server cmdlets from Microsoft instead.
You will also need to make a Powershell module -which is a combination of this function and this function. Just add one function under the other and put the line "export-modulemember IsIpAddressInRange,Get-IPrange". This module is referred as "IPutil.psm1"

Import-Module .\Microsoft.DHCP.Powershell.Admin.psm1

Import-Module .\IPutil.psm1



#Group by line types

$subnets = Select-String -Pattern 'subnet' -Path .\dhcp-config.txt |%{$_.Line}

$pools = Select-String -Pattern 'pool' -Path .\dhcp-config.txt | %{$_.Line}

$hosts = Select-string -Pattern ‘host’ -path  .\dhcp-config.txt |%{$_.Line}



#Create scopes

$scopes = $subnets |%{$l=$_.Split(','); New-DHCPScope -Server $env:COMPUTERNAME -Address $l[1] -SubnetMask $l[2] -Name $l[3]}





foreach ($scope in $scopes)

{

    # generate all the IP addresses in this scope

    $ips=Get-IPrange -ip $scope.Address -mask $scope.SubnetMask

    # Create pools

    Write-host "Creating pool(s) for " $scope.Address

    foreach ($line in $pools)

    {

        if($ips -contains $line.split(',')[1])

        {

            Add-DhcpIPRange -scope $scope -startaddress $line.split(',')[1] -endaddress $line.split(',')[2]

        }

    }

    # Create reservations

    Write-host "Creating reservation(s) for " $scope.Address

    foreach ($line in $hosts)

    {

        if($ips -contains $line.split(',')[1])

        {

            New-DHCPReservation -scope $scope -IPAddress $line.split(',')[1] -MACAddress $line.split(',')[2] -Description $line.split(',')[4]

        }

    }

}

Write-host “You should now rename the scopes to friendly names”

Write-host “You should manually set options and lease times"

Thursday, December 1, 2011

PowerShell - count folders in folders

Counting the number of files in a directory is easy
(dir).Count
Here's a more complex example that I will break down, like a tutorial. Unlike the previous example, this is taking advantage of the object oriented nature of PowerShell. You should understand about_pipelines before you continue reading

The problem
An invoice scanning system uploads files to a file server. The directory structure is the following.
\\server\files\<country_code-invoices>\<date>\<invoice_id></invoice_id></date></country_code-invoices>

Here's an German invoice folder scanned on December 1st 2011
\\server\files\DE-invoices\2011-12-01\2ad52000-32d5-4d72-925a-98ac442d2381

The question is : "How many invoices have been created every day by country ?" . The output has to be a table to be analyzed with Excel.

The proposed solution

Get all the country folders
dir \\server\files\*-invoices
For each (% is the operator) country folder ($_ is the pipeline object), display only its name
dir \\server\files\*-invoices | %{$_.Name}
#
Display the date folders for each country
dir \\server\files\*-invoices | %{dir $_}
#
We'll store the country name in $country, to use it later as we bring it up the pipeline.
dir \\server\files\*-invoices | %{$country=$_.Name}
#


Now it's getting a bit tricky.We'll put a pipeline inside a pipeline!
Because we need to process each date folder in each country folder.

  • For Each country folder display its name
  • For Each date folder in a country folder display its name
  • For Each date folder, count the number of folders it contains

Display the country name and the date folder

dir \\server\files\*-invoices | %{$country=$_.Name;dir $_ |%{Write-Host $country $_.Name}}
#
outputs
DE-invoices 2011-12-01
DE-invoices 2011-11-30
etc..

Display the folder count
dir \\server\files\*-invoices | %{$country=$_.Name;dir $_ |%{Write-Host $country $_.Name (dir $_).count}}
#


outputs

DE-invoices 2011-12-01 5
DE-invoices 2011-11-30 18
etc..

The result can now be imported as CSV file ,using the space character as the separator.

Monday, July 4, 2011

Microsoft Windows - delete a local user profile whose account is missing from AD

Here's a post on how I helped my helpdesk colleagues to solve a strange problem.

John Doe's user account was deleted from Active Directory (he left the company over a year ago), but we could not delete his local profile on a Windows Server 2003:
  • through the user profiles control panel, it is not present
  • deleting the folder in "c:\documents and settings" said ntuser.dat is in use
  • The "User Profile Deletion Utility" (delprof) from Windows Server 2003 Resource Kit Tools doesn't find this profile either.
I checked with "Process Explorer" and saw his ntuser.dat was loaded.

NTUSER.DAT is a file containing the user's registry hive. it is loaded in the machine-wide registry under HKEY_USERS.

So we need to unload this user's registry hive, in order to delete his profile in "c:\document and settings"



You need to find out which SID (the S-1-5-21 ..etc) correspond to this user
So check the loaded hives in HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\hivelist

Then go back to HKEY_USERS , select the SID and go to file > unload hive.
You should now be able to delete his profile in "c:\documents and settings"