sysadmber
Joined: 08 Dec 2015 Posts: 50
|
Posted: Sun Jun 03, 2018 11:20 pm Post subject: PS: Check TCP Port in use and running process |
|
|
Hostmon provides TCP Test by sending data to the port and checks it's answer. I needed a check whether the TCP port is open and if so by which process.
This scripts runs only locally, in my case via rma.
Here is the code:
Code: |
param(
[string]$param_port,
[string]$param_proc,
[string]$param_proc_desc = "'Please provide Program Description as third parameter'"
)
If (!$param_port){
Return "ScriptRes:Bad:Program Abort - Please provide Port number as first parameter"
}
If (!$param_proc){
Return "ScriptRes:Bad:Program Abort - Please provide process name as second parameter"
}
$process = get-process $param_proc
If (!$process.id){
Return "ScriptRes:Bad: " + $param_proc_desc + " is not started"
}
$netcon = Get-NetTCPConnection -LocalPort $param_port
If ($netcon.State -eq "listen"){
if ($netcon.OwningProcess -ne $process.id){
$proc_alt = get-process -id $netcon.OwningProcess
Return "ScriptRes:Bad:TCP Port " + $param_port + " is not in use by " + $param_proc_desc + " but " + $proc_alt.Name + " (PID: " + $proc_alt.Id + ")"
}
else{
Return "ScriptRes:Ok:TCP Port " + $param_port + " is used by " + $param_proc_desc
}
}
else{
Return "ScriptRes:Bad:TCP Port " + $param_port + " is not in use"
}
|
|
|