From a bash script how can I quickly find out whether a port 445
is open/listening on a server.
I have tried a couple of options, but I want something q
nmap
is the right tool.
Simply use nmap example.com -p 80
You can use it from local or remote server. It also helps you identify if a firewall is blocking the access.
ss -tl4 '( sport = :22 )'
2ms is quick enough ?
Add the colon and this works on Linux
You can use netcat command as well
[location of netcat]/netcat -zv [ip] [port]
or
nc -zv [ip] [port]
-z – sets nc to simply scan for listening daemons, without actually sending any data to them.
-v – enables verbose mode.
Based on Spencer Rathbun's answer, using bash:
true &>/dev/null </dev/tcp/127.0.0.1/$PORT && echo open || echo closed
There's a very short with "fast answer" here : How to test if remote TCP port is opened from Shell script?
nc -z <host> <port>; echo $?
I use it with 127.0.0.1 as "remote" address.
this returns "0" if the port is open and "1" if the port is closed
e.g.
nc -z 127.0.0.1 80; echo $?
-z Specifies that nc should just scan for listening daemons, without sending any data to them. It is an error to use this option in conjunc- tion with the -l option.
If you're using iptables try:
iptables -nL
or
iptables -nL | grep 445