大部份作業系統都依賴netstat這工具,只是在console上要顯示美美的需要加工
function Get-NetworkStatistics
{
$properties = 'Protocol','LocalAddress','LocalPort'
$properties += 'RemoteAddress','RemotePort','State','ProcessName','PID'
netstat -ano | Select-String -Pattern '\s+(TCP|UDP)' | ForEach-Object {
$item = $_.line.split(" ",[System.StringSplitOptions]::RemoveEmptyEntries)
if($item[1] -notmatch '^\[::')
{
if (($la = $item[1] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6')
{
$localAddress = $la.IPAddressToString
$localPort = $item[1].split('\]:')[-1]
}
else
{
$localAddress = $item[1].split(':')[0]
$localPort = $item[1].split(':')[-1]
}
if (($ra = $item[2] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6')
{
$remoteAddress = $ra.IPAddressToString
$remotePort = $item[2].split('\]:')[-1]
}
else
{
$remoteAddress = $item[2].split(':')[0]
$remotePort = $item[2].split(':')[-1]
}
New-Object PSObject -Property @{
PID = $item[-1]
ProcessName = (Get-Process -Id $item[-1] -ErrorAction SilentlyContinue).Name
Protocol = $item[0]
LocalAddress = $localAddress
LocalPort = $localPort
RemoteAddress =$remoteAddress
RemotePort = $remotePort
State = if($item[0] -eq 'tcp') {$item[3]} else {$null}
} | Select-Object -Property $properties
}
}
}
Get-NetworkStatistics | Where-Object {$_.State -eq 'LISTENING'} | Sort-Object -Property PID | Format-Table
#!/bin/ksh
OS_NAME=$( uname -s )
if [[ $OS_NAME == "AIX" ]] ; then
echo "--------------------------------------------------------------------------------------"
printf "| %-20s | %-15s | Protocol | %-30s |\n" "Process" "PID" "Listening On";
echo "--------------------------------------------------------------------------------------"
netstat -Ana | awk '
/[0-9\*].[0-9].+LISTEN/ {
SOCKET=$1;
IPPORT=$5;
"rmsock " SOCKET " tcpcb" | getline SOCKOUT;
split(SOCKOUT, sockarray, " ");
gsub(/[\.\(\)]/, "", sockarray[10]);
LISTENERS[ sprintf("| %-20s | %15d | %8s | %30s |", sockarray[10], sockarray[9], "TCP", IPPORT) ] = 1;
}
/udp.*.[0-9]/ {
SOCKET=$1;
IPPORT=$5;
"rmsock " SOCKET " inpcb" | getline SOCKOUT;
split(SOCKOUT, sockarray, " ");
gsub(/[\.\(\)]/, "", sockarray[10]);
LISTENERS[ sprintf("| %-20s | %15d | %8s | %30s |", sockarray[10], sockarray[9], "UDP", IPPORT) ] = 1;
}
END {
for (var in LISTENERS)
print var
}' | sort | uniq
echo "--------------------------------------------------------------------------------------"
else
echo "ERROR: Requires AIX"
exit 1
fi
jemmy$ lsof -nP -i | grep LISTEN
rapportd 571 jemmy 4u IPv4 0xebbeb717fa1efb2d 0t0 TCP *:49189 (LISTEN)
rapportd 571 jemmy 5u IPv6 0xebbeb717f468155d 0t0 TCP *:49189 (LISTEN)
mosquitto 616 jemmy 5u IPv6 0xebbeb717f468403d 0t0 TCP *:1883 (LISTEN)
mosquitto 616 jemmy 6u IPv4 0xebbeb717fd199dd5 0t0 TCP *:1883 (LISTEN)
sudo netstat -tulpn | grep LISTEN