<commit_before>"""
This internal module serves as an interface between a python application and
the net-snmp binaries on the host system. This module provides a function
for each of the most popular net-snmp binary commands, runs that binary 
with custom options, parse its output, and delivers it back in a meaningful 
form. 
"""

# Standard Library imports
import csv
from subprocess import run, PIPE

# imports for type-hinting purposes
from typing import Union, Optional, List, Tuple, Dict

# Internal module imports
from .exceptions import SNMPTableError, SNMPWriteError
from .helpers import validate_ip_address, check_for_timeout, \
    handle_unknown_error


def snmpget(ipaddress: str, oid: str, community: str = 'public',
            port: Union[int, str] = 161, timeout: Union[int, str] = 3) \
        -> Optional[str]:
    """
    Runs Net-SNMP's 'snmpget' command on a given OID, and returns the result.
    :param community: the snmpv2 community string
    :param ipaddress: the IP address of the target SNMP server
    :param oid: the Object IDentifier to request from the target SNMP server
    :param port: the port on which SNMP is running on the target server
    :param timeout: the number of seconds to wait for a response from the 
    SNMP server  
    :return: 
    """
    ipaddress = validate_ip_address(ipaddress)
    host = '{}:{}'.format(ipaddress, port)

    cmdargs = [
        'snmpget', '-Oqv', '-Pe', '-t', str(timeout), '-r', '0', '-v', '2c',
        '-c', community, host, oid]

    cmd = run(cmdargs, stdout=PIPE, stderr=PIPE)

    # Handle any errors that came up
    if cmd.returncode is not 0:
        check_for_timeout(cmd.stderr, host)

        # if previous check didn't generate an Error, this handler will be
        # called as a sort of catch-all
        handle_unknown_error(' '.join(cmdargs), cmd.stderr)
    # Process results
    else:
        # subprocess returns stdout from completed command as a single bytes
        # string. We'll convert it into a regular python string for easier
        # handling
        cmdoutput = cmd.stdout.decode('utf-8')
        # Check for no such instance
        if 'No Such Instance' in cmdoutput:
            return None
        else:
            return cmdoutput


def snmpgetbulk(ipaddress: str, oids: List[str], community: str = 'public',
                port: Union[str, int] = 161, timeout: Union[int, str] = 3
                ) -> List[Tuple[str, str]]:
    """
    Runs Net-SNMP's 'snmpget' command on a list of OIDs, and returns a list 
    of tuples of the form (oid, result).
    :param community: the snmpv2 community string
    :param ipaddress: the IP address of the target SNMP server
    :param oids: a list of Object IDentifiers to request from the target 
    SNMP server
    :param port: the port on which SNMP is running on the target server
    :param timeout: the number of seconds to wait for a response from the 
    SNMP server 
    :return: 
    """
    ipaddress = validate_ip_address(ipaddress)
    host = '{}:{}'.format(ipaddress, port)<commit_msg>renamed function and added README<commit_after>"""
This module provides the individual SNMP commands for use in one-off 
situations, or situations where you would need to make a single SNMP request 
to many devices. If you plan on making multiple calls to the same device, you 
might want to check out api.py instead.
"""

# Standard Library imports
import csv
from subprocess import run, PIPE

# imports for type-hinting purposes
from typing import Union, Optional, List, Tuple, Dict

# Internal module imports
from .exceptions import SNMPTableError, SNMPWriteError
from .helpers import validate_ip_address, check_for_timeout, \
    handle_unknown_error


def snmpget(ipaddress: str, oid: str, community: str = 'public',
            port: Union[int, str] = 161, timeout: Union[int, str] = 3) \
        -> Optional[str]:
    """
    Runs Net-SNMP's 'snmpget' command on a given OID, and returns the result.
    :param community: the snmpv2 community string
    :param ipaddress: the IP address of the target SNMP server
    :param oid: the Object IDentifier to request from the target SNMP server
    :param port: the port on which SNMP is running on the target server
    :param timeout: the number of seconds to wait for a response from the 
    SNMP server  
    :return: 
    """
    ipaddress = validate_ip_address(ipaddress)
    host = '{}:{}'.format(ipaddress, port)

    cmdargs = [
        'snmpget', '-Oqv', '-Pe', '-t', str(timeout), '-r', '0', '-v', '2c',
        '-c', community, host, oid]

    cmd = run(cmdargs, stdout=PIPE, stderr=PIPE)

    # Handle any errors that came up
    if cmd.returncode is not 0:
        check_for_timeout(cmd.stderr, host)

        # if previous check didn't generate an Error, this handler will be
        # called as a sort of catch-all
        handle_unknown_error(' '.join(cmdargs), cmd.stderr)
    # Process results
    else:
        # subprocess returns stdout from completed command as a single bytes
        # string. We'll convert it into a regular python string for easier
        # handling
        cmdoutput = cmd.stdout.decode('utf-8')
        # Check for no such instance
        if 'No Such Instance' in cmdoutput:
            return None
        else:
            return cmdoutput


def snmpgetsome(ipaddress: str, oids: List[str], community: str = 'public',
                port: Union[str, int] = 161, timeout: Union[int, str] = 3
                ) -> List[Tuple[str, str]]:
    """
    Runs Net-SNMP's 'snmpget' command on a list of OIDs, and returns a list 
    of tuples of the form (oid, result).
    :param community: the snmpv2 community string
    :param ipaddress: the IP address of the target SNMP server
    :param oids: a list of Object IDentifiers to request from the target 
    SNMP server
    :param port: the port on which SNMP is running on the target server
    :param timeout: the number of seconds to wait for a response from the 
    SNMP server 
    :return: 
    """
    ipaddress = validate_ip_address(ipaddress)
    host = '{}:{}'.format(ipaddress, port)
{'fraction_non_alphanumeric': 0.08533988533988535, 'fraction_numerical': 0.004586404586404586, 'mean_word_length': 2.9368149580915537, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4473375', 'n_tokens_mistral': 1791, 'n_tokens_neox': 1731, 'n_words': 747}