How to Add Ping Module in Aws Lambda Using Python

How to Add Ping Module in Aws Lambda Using Python

I want to monitor a server using AWS Lambda function with Python 3.9 version.

I'm using ping test connection and here's my code

import subprocess
import platform

def lambda_handler(event, context):
    SERVERS = [
        ('203.124.136.164', 'Local Host 1')
    ]

    for (server, name) in SERVERS:
        check_connection(server, name)
            
def check_connection(server, name):
    if ping(server):
        print("%s is UP" % (name))
    else:
        print("%s is DOWN" % (name))

def ping(server):
    try:
        output = subprocess.check_output("ping -{} 1 {}".format('n' if platform.system().lower() == "windows" else 'c', server ), shell=True, universal_newlines=True)
        if 'unreachable' in output:
            print('unreachable')
            return False
        elif 'timed out' in output:
            print('timed out')
            return False
        else:
            print('success')
            return True
    except Exception as err:
        print("An error occurred: %s" % (err.__str__()))
        return False

But I got an error:

/bin/sh: ping: command not found
An error occurred: Command 'ping -c 1 203.124.136.164' returned non-zero exit status 127.

Why I got that error and what is the right implementation to monitor a server using IP? I'm just a beginner. Please help!

Disclaimer: the IP provided on the code is just dummy.

1 Answer

I think AWS Lambda doesn't allow for ICMP to go outbound. It only allows for TCP or UDP outbound so since ping is neither it doesn't work. Even if you try to make a custom layer and import to Lambda you will get a permissions error since ICMP is not allowed.

Sorry my friend, the easiest work around I believe would to make a T1.micro to run the full python code.

1

Your Answer

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

Robert Thorne
Author

Robert Thorne

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.