Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # https://www.reddit.com/r/PowerShell/comments/4emc45/changing_output_of_script_to_csv/
- function Get-PortStats {
- param (
- [string[]]$Computers = $env:computername,
- [string]$User,
- [string]$Password,
- [int]$CollectionInterval,
- [string]$OutputFilePath,
- [string]$PsExecLocation
- )
- begin {
- function ProcessArguments ($paComputers, $paUser, $paPassword) {
- #// Processes the arguments passed into the script such as getting the appropriate credentials if specified.
- $paComputers = $paComputers.Split(';')
- if ($paComputers -isnot [System.String[]]) {
- $paComputers = @($paComputers)
- }
- #// If credentials are passed into this script, then make them secure.
- if ($paUser -ne '') {
- if ($paPassword -ne '') {
- $paPassword = ConvertTo-SecureString -AsPlainText -Force -String $paPassword
- $paCredential = New-Object System.Management.Automation.PsCredential -ArgumentList $paUser, $paPassword
- } else {
- $paCredential = Get-Credential -Credential $paUser
- }
- }
- [pscustomobject]@{
- Computers = $paComputers
- Credential = $paCredential
- }
- }
- function Invoke-PsExec ($peComputer, $peCommand, $peUser, $pePassword, $peCredential) {
- #// Executes PsExec to get data from remote computers.
- if ($PsExecLocation) {
- $PsExec = $PsExecLocation
- } else {
- $PsExec = '.\psexec.exe'
- }
- if ($peUser -ne '') {
- if ($pePassword -eq '') {
- $pePassword = $peCredential.GetNetworkCredential().Password
- }
- $sPsCmd = "$PsExec \\$peComputer /AcceptEula -u $peUser -p `"$pePassword`" -s $peCommand 2> `$null"
- Write-Warning 'Credentials sent in clear text to the remote computer using PsExec! Prevent this by not providing credentials to this script and logging in with a domain account with admin privileges to the remote computer or by using network encryption such as IPSec.'
- } else {
- $sPsCmd = "$PsExec \\$peComputer /AcceptEula $peCommand"
- }
- Invoke-Expression -Command $sPsCmd
- }
- function Get-TcpDynamicPortRange ($tdprComputer, $tdprUser, $tdprPassword, $tdprCredential) {
- $sCmd = 'netsh int ipv4 show dynamicportrange tcp'
- if ($tdprComputer -eq $env:COMPUTERNAME) { # local
- $oOutput = Invoke-Expression -Command $sCmd
- } else { # not local
- #// Use PsExec
- $oOutput = Invoke-PsExec -peComputer $tdprComputer -peCommand $sCmd -peUser $tdprUser -pePassword $tdprPassword -peCredential $tdprCredential
- }
- $oDynamicPortRange = [pscustomobject]@{
- StartPort = 0
- EndPort = 0
- NumberOfPorts = 0
- }
- foreach ($sLine in $oOutput) {
- if ($sLine.IndexOf('Start Port') -ge 0) {
- $aLine = $sLine.Split(':')
- [int]$oDynamicPortRange.StartPort = $aLine[1]
- }
- if ($sLine.IndexOf('Number of Ports') -ge 0) {
- $aLine = $sLine.Split(':')
- [int]$oDynamicPortRange.NumberOfPorts = $aLine[1]
- }
- }
- $oDynamicPortRange.EndPort = $oDynamicPortRange.StartPort + $oDynamicPortRange.NumberOfPorts - 1
- $oDynamicPortRange
- }
- function Get-ActiveTcpConnections ($atcComputer, $atcUser, $atcPassword, $atcCredential) {
- $sCmd = 'netstat -ano -p tcp'
- if ($Computer -eq $env:COMPUTERNAME) { # local
- $oOutput = Invoke-Expression -Command $sCmd
- } else { # not local
- #// Use PsExec
- $oOutput = Invoke-PsExec -peComputer $atcComputer -peCommand $sCmd -peUser $atcUser -pePassword $atcPassword -peCredential $atcCredential
- }
- if ($oOutput -ne $null) {
- $u = $oOutput.GetUpperBound(0)
- $oOutput = $oOutput[4..$u]
- foreach ($sLine in $oOutput) {
- $iPropertyIndex = 0
- $aLine = @($sLine.Split(' ')).where{$_ -notmatch '^\s*$'}
- $oActiveConnection = @{}
- for ($c = 0; $c -lt $aLine.Count;$c++) {
- if ($aLine[$c] -ne '') {
- switch ($iPropertyIndex) {
- 0 {
- $oActiveConnection.Add('Proto', $aLine[$c])
- }
- 1 {
- $aIpPort = $aLine[$c].Split(':')
- $oActiveConnection.Add('LocalAddress', $aIpPort[0])
- $oActiveConnection.Add('LocalPort', [int]$aIpPort[1])
- }
- 2 {
- $aIpPort = $aLine[$c].Split(':')
- $oActiveConnection.Add('ForeignAddress', $aIpPort[0])
- $oActiveConnection.Add('ForeignPort', [int]$aIpPort[1])
- }
- 3 {
- $oActiveConnection.Add('State', $aLine[$c])
- }
- 4 {
- $oActiveConnection.Add('PID', [int]$aLine[$c])
- }
- }
- $iPropertyIndex++
- }
- }
- [pscustomobject]$oActiveConnection
- }
- }
- }
- function Get-EphemeralPortStats ($ArrayOfComputerNames, $epsUser, $epsPassword, $epsCredential) {
- $epsHtDynamicPortRange = @{}
- foreach ($Computer in $ArrayOfComputerNames) {
- if ($epsHtDynamicPortRange.ContainsKey($Computer) -eq $false) {
- $oDynamicPortRange = Get-TcpDynamicPortRange -tdprComputer $Computer -tdprUser $epsUser -tdprPassword $epsPassword -tdprCredential $epsCredential
- [Void]$epsHtDynamicPortRange.Add($Computer, $oDynamicPortRange)
- } else {
- $oDynamicPortRange = $epsHtDynamicPortRange[$Computer]
- }
- [int]$iDynamicStartPort = $oDynamicPortRange.StartPort
- [int]$iDynamicEndPort = $oDynamicPortRange.EndPort
- [int]$iDynamicNumberOfPorts = $oDynamicPortRange.NumberOfPorts
- $oActiveConnections = Get-ActiveTcpConnections -atcComputer $Computer -atcUser $epsUser -atcPassword $epsPassword -atcCredential $epsCredential | Sort LocalPort -Descending
- $aUniqueLocalAddresses = @($oActiveConnections | Sort {[version]$_.LocalAddress} | Select LocalAddress -Unique).where{$_.localaddress -ne '0.0.0.0'}
- $aDynamicPortRangeConnections = @($oActiveConnections).Where{($_.LocalPort -gt $iDynamicStartPort) -and ($_.LocalPort -lt $iDynamicEndPort)}
- foreach ($oUniqueLocalAddress in $aUniqueLocalAddresses) {
- if ($oUniqueLocalAddress.LocalAddress -ne '0.0.0.0') {
- #// Ephemeral ports of each LocalAddress
- [string]$sUniqueLocalAddress = $oUniqueLocalAddress.LocalAddress
- [array]$aIpEphemeralPortConnections = @($aDynamicPortRangeConnections).Where{($_.LocalAddress -eq $sUniqueLocalAddress)} | Select LocalPort -Unique | Sort
- $oStats = @{}
- $oStats.Add('Computer', $Computer)
- $oStats.Add('DateTime', $(Get-Date))
- $oStats.Add('LocalAddress', $sUniqueLocalAddress)
- $oStats.Add('Max#OfEPorts', [int]$oDynamicPortRange.NumberOfPorts)
- if ($aIpEphemeralPortConnections -ne $null) {
- $oStats.Add('#OfEPortsInUse', [int]$aIpEphemeralPortConnections.Count)
- $iPercentage = [int]$aIpEphemeralPortConnections.Count / [int]$oDynamicPortRange.NumberOfPorts * 100
- $iPercentage = [Math]::Round($iPercentage, 1)
- } else {
- $oStats.Add('#OfEPortsInUse', 0)
- $iPercentage = 0
- }
- $oStats.Add('%EPortUsage', $iPercentage)
- #// Listening ports of each LocalAddress
- [array]$aIpListeningPorts = @($oActiveConnections).Where{($_.State -eq 'LISTENING') -and (($_.LocalAddress -eq $sUniqueLocalAddress) -or ($_.LocalAddress -eq '0.0.0.0'))} | Select LocalPort | Sort LocalPort | Get-Unique -AsString
- if ($aIpListeningPorts -ne $null) {
- $oStats.Add('#OfTcpListeningPorts', [int]$aIpListeningPorts.Count)
- } else {
- $oStats.Add('#OfTcpListeningPorts', 0)
- }
- #// Number of PIDs
- [array]$aIpPids = @($oActiveConnections).Where{($_.LocalAddress -eq $sUniqueLocalAddress) -or ($_.LocalAddress -eq '0.0.0.0')} | Select PID -Unique | Sort PID
- if ($aIpPids -ne $null) {
- $oStats.Add('#OfPids', [int]$aIpPids.Count)
- } else {
- $oStats.Add('#OfPids', 0)
- }
- [pscustomobject]$oStats
- }
- }
- }
- }
- }
- process {
- $pa = ProcessArguments -paComputers $Computers -paUser $User -paPassword $Password
- $Computers = $pa.computers
- $Credential = $pa.credential
- if ($CollectionInterval) {
- $stop = $false
- } else {
- $stop = $true
- }
- do {
- $oPortStats = Get-EphemeralPortStats -ArrayOfComputerNames $Computers -epsUser $User -epsPassword $Password -epsCredential $Credential
- $oPortStats | Format-Table -AutoSize
- if ($OutputFilePath) {
- $oPortStats | Export-Csv $OutputFilePath -NoTypeInformation
- }
- if ($CollectionInterval) {
- Write-Host "Sleeping for $CollectionInterval seconds..." -NoNewline
- Start-Sleep -Seconds $CollectionInterval
- }
- Write-Host 'Done!'
- } until ($stop)
- }
- }
- Get-PortStats -Computers $env:computername -OutputFilePath c:\temp\portstats.csv -PsExecLocation C:\PSTools\PsExec.exe
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement