Creating a CLI App with Click - Server Status Checker v1.1

Creating a CLI App with Click - Server Status Checker v1.1

In my previous blog post, I introduced you to a Python script that checks the status of a web server. I've received valuable feedback from Luca Gubler (one of the fewest Devnet Experts in the world) and have decided to enhance the user experience by converting it into a Command-Line Interface (CLI) tool using Click.

In this updated post, I'll walk you through the step-by-step process of creating and using the enhanced Server Status Checker CLI tool.

Writing the Enhanced Python Module

File Structure

Create the file following file structure:

project_root/
│
├── site_checker.py
│
├── setup.py

Setup the Development Environment

Before we dive into the code, ensure you have Python installed on your system. If not, download and install it from the official Python website. Additionally, make sure you have the Click library installed. I would recommended you to use a Virtual Environment and then install it using pip:

python -m venv venv
source ./venv/bin/activate
pip install click

Let's start by writing the enhanced Python module, now named site_checker.py. We've improved the code to provide a more user-friendly CLI experience using Click.

  1. Import the necessary libraries at the beginning of your script:

     import socket
     import click
    
  2. To define the options for the "check_site" command, you will need to use the @click.option() decorator. In this scenario, the command will have two options: "host" and "port". The "host" option will represent the website's domain name or IP address, while the "port" option will represent the port number to which the connection should be established.

    By using the @click.option() decorator, you can easily specify these options and their respective default values, types, and help descriptions for a more user-friendly command-line interface experience.

     @click.command()
     @click.option('--host','-h',type=str, required=True, help="Domain name or IPv4 address")
     @click.option('--port','-p', type=int, default=80, show_default=True, help="Port number" )
     def check_site(host,port):
         """This script checks whether a specified web server is online by attempting
           to establish a socket connection using a provided host and port"""
    
  3. Inside the check_site function, use a try...except block to handle exceptions gracefully. This is where your server status checking logic remains unchanged. I will simply reuse that code from my previous post:

         try:
    
             print(f"Attempting to connect to {host} on port {port}")
    
             # Create a socket object
             sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
             # Connect to the server
             sock.connect((host, port))
    
             # Send a simple HTTP HEAD request
             request = f"HEAD / HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n"
             sock.send(request.encode('utf-8'))
    
             # Receive the response
             reply = sock.recv(10000)
             print("Server Online")
    
             # Properly shutdown and close the socket
             sock.shutdown(socket.SHUT_RDWR)
             sock.close()
    
             return 0
    
         except ValueError:
             print("Port must be an integer.")
         except socket.gaierror:
             print("Hostname could not be resolved.")
         except socket.error as e:
             print(f"Server Down - Socket Error: {e}")
         except Exception as e:
             print(f"An error occurred: {e}")
    
  4. Finally, add the following conditional block to allow your script to be run as a standalone program:

     if __name__ == "__main__":
         check_site()
    

Step 3: Creating the setup.py File

  1. Create a Python script file named setup.py. This file is necessary for packaging and distributing your CLI tool.

  2. Import setuptools at the beginning of your setup.py script:

     from setuptools import setup
    
  3. Configure your package setup:

     # setup.py
    
     from setuptools import setup 
    
     setup(
         name='site_checker',
         version='1.1',
         py_modules=[
             'site_checker',
         ],
         install_requires=[
             'click==8.1.7',
         ],
         entry_points={ 
             'console_scripts': [
                 'check_site=site_checker:check_site',
             ]
         }
     )
    
    • name: Specify the name of your Python package.

    • version: Define the version number.

    • py_modules: List the Python modules to include in your package. In this case, include 'site_checker.'

    • install_requires: Specify dependencies needed for your package, such as 'Click.'

    • entry_points: Define the console script entry point. This allows you to run the check_site command from the command line.

Step 4: Installing and Using Your Enhanced CLI Tool

  1. Open your terminal and navigate to the directory containing your setup.py file and your site_checker.py script.

  2. Install your enhanced CLI tool using pip:

     pip install -e .
    

    This command installs your site_check package and makes the check_site command available.

You can now use your enhanced Server Status Checker CLI tool from the command line. For example:

check_site --host example.com --port 80

Replace example.com and 80 with the host and port you want to check as shown below. You'll receive immediate feedback on whether the server is online or if there are any errors.

Download the code from GitHub

git clone https://github.com/wilmeralmazan/site_checker.git

cd site_checker

pip install -e .

Next Steps -> Docker Image? Let's see...

In this step-by-step guide, we've demonstrated how to transform your Python Server Status Checker script into a user-friendly CLI tool using the Click library. This enhanced tool allows you to check the status of web servers effortlessly, making it a valuable addition to your development toolkit.

But the journey doesn't end here. In our next installment, we'll take this tool to the next level by converting it into a Docker image. Stay tuned for an exciting update that will make deploying and running your Server Status Checker even more convenient and versatile.