VCF Automation Blog

from Stefan Schnell

Invoke ELF Executable with Python


"""
Example how to invoke an ELF executable which is not available in
Photon OS, here traceroute. The traceroute ELF executable is part
of the zip container, which is imported as an action.
traceroute is a tool that displays the path of a data packet from the
calling source to a given destination.

@module de.stschnell

@author Stefan Schnell <mail@stefan-schnell.de>
@license MIT
@version 0.1.0

@runtime python:3.10

@inputType in_host {string}

@outputType Properties
"""

import json
import os
import shutil
import subprocess
import tempfile

def handler(context: dict, inputs: dict) -> dict:

    result: dict = {}
    outputs: dict = {}

    try:

        pathName: str = os.path.dirname(os.path.abspath(__file__))
        exeName: str = pathName + "/traceroute"

        # Copies the traceroute ELF executable from the zip container
        # to the temporary directory.
        shutil.copy(exeName, tempfile.gettempdir())

        # Changes the mode of the traceroute so that it can be executed.
        proc: subprocess.CompletedProcess = subprocess.run(
            ["chmod", "777", tempfile.gettempdir() + "/traceroute"],
            encoding = "utf-8",
            stdout = subprocess.PIPE
        )

        # Executes traceroute with the passed domain or IP address, with
        # the using of the Internet Control Message Protocol (ICMP).
        # ICMP can be used to avoid conflicts with firewall settings.
        proc = subprocess.run(
            [tempfile.gettempdir() + "/traceroute", "-I", inputs["in_host"]],
            encoding = "utf-8",
            stdout = subprocess.PIPE
        )
        print(proc.stdout)

        """
        # Netcat reads and writes data across network connections,
        # using TCP as default or UDP. It can be used to check whether
        # the port of a destination can be reached. If the return code
        # is 0, the connection has been established.
        proc = subprocess.run(
            ["nc", inputs["in_host"], inputs["in_port"]],
            encoding = "utf-8",
            stdout = subprocess.PIPE
        )
        print(proc.returncode)
        """

        result = {"result": proc.stdout}

        outputs = {
            "status": "done",
            "error": None,
            "result": result
        }

    except Exception as err:

        outputs = {
            "status": "incomplete",
            "error": repr(err),
            "result": result
        }

    return outputs