I need to improve this script:

nmap -PN -p 9292 -sN | grep "open" 

I need to check connectivity to ip on port 9292.

If the port is open, then print "port 9292 is open"

If the port is closed, then print "port 9292 is closed"

The result will be taken from icinga to do a check.

Any idea?


Apart from @DopeGhoti's correct answer using netcat, your script could be improved by changing some of your Nmap options and adding a few.

  • -sN means "TCP NULL scan," which is a very unusual raw-socket scan mode requiring root privileges. It also has the odd property of only labeling ports as "closed" or "unfiltered" but never "open." You probably want a normal TCP Connect scan instead, using the -sT option.
  • Nmap will attempt to do a reverse name lookup (PTR) by default. Avoid this unnecessary delay with the -n option.
  • Using Nmap's normal screen output in a script is not recommended, even for something as simple as this, because it is subject to change between versions. For a stable, machine-parsable output format, use grepable (-oG) or XML (-oX).
  • -PN is an old (deprecated in 2010) spelling of -Pn. It skips the host discovery phase, so probably a good idea for your script.

Example with all of these changes:

nmap -n -Pn -sT -p 9292 -oG - | grep '/open/'

This requires the netcat package:

if nc -z 9292; then
    echo "Port is open"
    echo "Port is closed"

nc -z will attempt to make a connection to the specified host and port; it returns a 0 exit code upon success, and a nonzero code otherwise. It does not actually output anything to the terminal. To get your desired output, I use an if statement to test the results of the connection test, and echo the appropriate result to the terminal.

  • thanks but the command nc -z 9292 output is empty... – Marcelo Martinez Apr 5 '16 at 19:39
  • Thus the if and echo statements. nc does not output anything; it returns an exit code apropos of the results of the connection attempt. – DopeGhoti Apr 5 '16 at 19:40
  • sh check_connection.sh Port is open – Marcelo Martinez Apr 5 '16 at 19:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.