Import-Module activedirectory

Write-Output "Förbereder...."

$ErrorActionPreference = "silentlycontinue"

$dclist = (Get-ADForest).Domains | %{ Get-ADDomainController -Filter * -Server $_ } | Select-Object -ExpandProperty ipv4address

$ports2look4 = 445,135,389,636,3268,3269,88,53,123,464,137,139,138,9389

$Resultfile = "currentconnections.csv"

# Hur många minuter vill du logga

$looptime = 3

# Hur många sekunder vill du pausa mellan varje försök

$sleeptime = 10

$TimeStart = get-date

$TimeEnd = $TimeStart.AddMinutes($looptime)

if (!(test-path $resultfile)) {

out-file $resultfile -Encoding utf8

Add-Content $resultfile "LocalIP;PORT;RemoteIP;RemoteHostName;Service"

}

Write-Output "Letar efter anslutningar var $sleeptime sekund i $looptime minuter...."

Do

{

$TimeNow = Get-Date

$connections = netstat -n | Select-String "ESTABLISHED"

$connections += netstat -n | Select-String "TIME_WAIT"

foreach ($connection in $connections)

{

$LocalIP = $null

$LocalPort = $null

$RemoteIP = $null

$RemotePort = $null

$RemoteName = $null

$Localservice = $null

$LocalIP = ((($connection -split '\s+')[2]) -split ":")[0].trim()

$LocalPort = ((($connection -split '\s+')[2]) -split ":")[1].trim()

$RemoteIP = ((($connection -split '\s+')[3]) -split ":")[0].trim()

$RemotePort = ((($connection -split '\s+')[3]) -split ":")[1].trim()

Switch ($LocalPort)

{

389 { $localService = "LDAP" }

135 { $localService = "RPC, EPM" }

636 { $localService = "LDAP SSL" }

3268 { $localService = "LDAP GC" }

3269 { $localService = "LDAP GC SSL" }

88 { $localService = "Kerberos" }

53 { $localService = "DNS" }

445 { $localService = "SMB,CIFS,SMB2, DFSN, LSARPC, NbtSS, NetLogonR, SamR, SrvSvc" }

123 { $localService = "Windows Time" }

464 { $localService = "Kerberos change/set password" }

138 { $localService = "DFSN, NetLogon, NetBIOS Datagram Service" }

9389 { $localService = "AD DS Web Services, SOAP" }

137 { $localService = "NetLogon, NetBIOS Name Resolution" }

139 { $localService = "DFSN, NetBIOS Session Service, NetLogon" }

Default { $localService = "Okänd tjänst"}

}

if ($localip -notlike "127.0.0.1")

{

if ( $localport -notlike $null )

{

if ($dclist -notcontains $remoteip)

{

if ($ports2look4 -contains $localPort )

#if ($ports2look4 -contains $remotePort )

{

$kontroll = $null

$remotename = [System.Net.Dns]::GetHostentry($RemoteIP).hostname

$searchfor = "$localip;$localport;$remoteIP;$remotename;$localservice"

$kontroll = Get-Content $resultfile | Select-String $searchfor

if ($kontroll -eq $null)

{

Write-Output "Ny anslutning hittad: $remoteIP't$remotename't$localport"

Add-Content $resultfile "$localip;$localport;$remoteIP;$remotename;$localservice"

}

}

}

}

}

}

Start-Sleep -Seconds $sleeptime

}

Until ($timeNow -ge $TimeEnd)

Write-Output "Loop avslutad efter $looptime minuter"