>_ IzzyLab

Hands-on task

This task is step 15 of the course “Monitoring and metrics”

Check Service Availability

medium~7 min

Write /usr/local/bin/portcheck host port: if the TCP port is open — exit 0, if closed — exit 1. It's tested against a live service (port 6500) and a closed one (port 6599).

The script is easiest to write in the Editor tab: /usr/local/bin shows up there in the file tree; run and test it in the terminal.

What you'll practise:
  • exit code
  • /dev/tcp
  • port check
  • bash script
  • timeout

Topic breakdown

"Port is open" = a TCP connection can be established; a refusal (connection refused) means the port is closed. The key idea of the task is to turn the result of a connection attempt into the script's exit code: 0 on success, non-zero on failure. You can connect from pure bash via the pseudo-device /dev/tcp/<host>/<port> (wrapped in timeout so it doesn't hang) or with the nc utility in scan mode; then all that's left is to carefully pass the right exit status through via if or the last command's code. The script accepts arguments $1/$2, begins with a shebang, and must be executable (chmod +x).

What's checked

  1. portcheck is executable
  2. open port 6500 gives code 0
  3. closed port 6599 gives code 1

What it looks like