Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 623
JSN Avatar asked Apr 08 '26 05:04

JSN


1 Answers

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.

like image 97
Kevin J Avatar answered Apr 10 '26 20:04

Kevin J



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!