netstat open ports code example

Example 1: netstat check port

sudo netstat -plnt

Example 2: how to check listening ports on a server

$ sudo netstat -plnt
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name
tcp        0      0 0.0.0.0:3306                0.0.0.0:*                   LISTEN      3686/mysqld
tcp        0      0 :::443                      :::*                        LISTEN      2218/httpd
tcp        0      0 :::80                       :::*                        LISTEN      2218/httpd
tcp        0      0 :::22                       :::*                        LISTEN      1051/sshd

Example 3: netstat command ports

$netstat = netstat -aon | Select-String -pattern "(TCP|UDP)"
$processList = Get-Process

foreach ($result in $netstat) {
   $splitArray = $result -split " "
   $procID = $splitArray[$splitArray.length – 1]
   $processName = $processList | Where-Object {$_.id -eq $procID} |    select processname
   $splitArray[$splitArray.length – 1] = $procID + " " +      $processName.processname
   $splitArray -join " "
}

Example 4: how to check listening ports on a server

sudo ss -tulwn | grep LISTEN

Tags:

Misc Example