def main(args):
    """
    Handles various command line args and call collect_inv() function.
    """
    if args.pem is not None:
        if args.session:
            print(
                "Simulating inventory collection with session-based API access..."
            )
            spc1 = rest.Space(args.space_URL,
                              cert=(args.pem, args.key),
                              use_session=True,
                              profile_file='/tmp/api-responses-session.csv')
            collect_inv(spc1, args.threads)
            spc1.logout()
        else:
            print(
                "Simulating inventory collection with non-session-based API access..."
            )
            spc2 = rest.Space(args.space_URL,
                              cert=(args.pem, args.key),
                              use_session=False,
                              profile_file='/tmp/api-responses.csv')
            collect_inv(spc2, args.threads)
    else:
        if args.session:
            print(
                "Simulating inventory collection with session-based API access..."
            )
            spc1 = rest.Space(args.space_URL,
                              args.user,
                              args.passwd,
                              use_session=True,
                              profile_file='/tmp/api-responses-session.csv')
            collect_inv(spc1, args.threads)
            spc1.logout()
        else:
            print(
                "Simulating inventory collection with non-session-based API access..."
            )
            spc2 = rest.Space(args.space_URL,
                              args.user,
                              args.passwd,
                              use_session=False,
                              profile_file='/tmp/api-responses.csv')
            collect_inv(spc2, args.threads)
Exemplo n.º 2
0
    def setup_class(self):
        # Extract Space URL, userid, password from config file
        config = configparser.RawConfigParser()
        import os
        config.read(os.path.dirname(os.path.realpath(__file__)) + "/test.conf")
        url = config.get('space', 'url')
        user = config.get('space', 'user')
        passwd = config.get('space', 'passwd')

        # Create a Space REST end point
        self.space = rest.Space(url, user, passwd, use_session=True)
def main(args):
    spc = rest.Space(args.space_URL, args.user, args.passwd)

    try:
        # Create the output directory
        os.makedirs(os.path.abspath(args.out))
    except OSError as exception:
        if exception.errno != errno.EEXIST:
            raise

    collect_config_files(spc, args.out)
Exemplo n.º 4
0
    def setup_class(self):
        # Extract Space URL, userid, password from config file
        config = configparser.RawConfigParser()
        import os
        config.read(os.path.dirname(os.path.realpath(__file__)) + "/test.conf")
        url = config.get('space', 'url')
        user = config.get('space', 'user')
        passwd = config.get('space', 'passwd')

        # Create a Space REST end point
        self.space = rest.Space(url, user, passwd)

        cglets = self.space.configuration_management.cli_configlets.get(
            filter_={'name': 'Set description - Pytest'})
        if len(cglets) > 0:
            cglets[0].delete()
Exemplo n.º 5
0
    def setup_class(self):
        # Extract Space URL, userid, password from config file
        config = configparser.RawConfigParser()
        import os
        config.read(os.path.dirname(os.path.realpath(__file__)) + "/test.conf")
        url = config.get('space', 'url')
        user = config.get('space', 'user')
        passwd = config.get('space', 'passwd')

        # Create a Space REST end point
        self.space = rest.Space(url, user, passwd)
        try:
            tags_list = self.space.tag_management.tags.get(
                filter_="name starts-with 'ApiTestTag'")
            for t in tags_list:
                t.delete()
        except:
            pass
Exemplo n.º 6
0
    def LoadInputFile(self):
        warnings.filterwarnings("ignore")
        devices = []
        general_settings = []

        #### Read the general settings information
        try:
            with open('conf/fullFetcher.conf') as data_file:
                general_settings = json.load(data_file)
        except IOError:
            msg = "Loading and Verifying Device List failed : Unable to read input or parse file 'assistedFetcher.conf' responsible for storing general settings."
            logging.error(msg)
            return (False, msg)

        self.THREADCOUNT = int(general_settings["parallelProcesses"])

        # Create a Space REST end point
        space = rest.Space(url="https://" + general_settings["url"],
                           user=general_settings["username_js"],
                           passwd=general_settings["password_js"])
        logging.info("Connecting to Junos Space to retrieve the devices list.")
        try:
            domains = space.domain_management.domains.get()
            children = etree.SubElement(domains[0].children, "domain")

            domain_name = general_settings["domain"]
            if domain_name == "":
                domain_name = "Global"
            domain_id = 0
            ip_address = general_settings["ip"]

            for child_domain in domains[0].children.domain:
                domain = etree.SubElement(child_domain, "name")
                if domain_name == str(child_domain.name):
                    domain_id = child_domain.id
            if domain_id != 0:
                if ip_address != "":
                    devices = space.device_management.devices.\
                        get(filter_={'deviceFamily': 'junos', 'connectionStatus': 'up', 'domain-id':str(domain_id), 'ipAddr': ip_address})
                else:
                    devices = space.device_management.devices.\
                        get(filter_={'deviceFamily': 'junos', 'connectionStatus': 'up', 'domain-id':str(domain_id)})
            else:
                if ip_address != "":
                    devices = space.device_management.devices.\
                      get(filter_={'deviceFamily': 'junos', 'connectionStatus': 'up', 'ipAddr':ip_address})
                else:
                    devices = space.device_management.devices.\
                      get(filter_={'deviceFamily': 'junos', 'connectionStatus': 'up'})

        except RestException as ex:
            msg = "An errror occured during the communication with the Junos Space API.\n\tHTTP error code : %s;\n\tJunos Space Message : %s " % (
                ex.response, ex.response.text)
            logging.error(msg)
            return ("False", msg)

        #### Build the in-memory structure
        for device in devices:
            entry = {}
            entry["username"] = general_settings["username_js"]
            entry["password"] = general_settings["password_js"]
            entry["url"] = general_settings["url"]
            entry["serialNumber"] = str(device.serialNumber)
            entry["ipAddr"] = str(device.ipAddr)
            entry["name"] = str(device.name)

            self.jobList.append(entry)

        msg = "Loading and Verifying Device List was successful, loaded (%s) hosts!" % str(
            len(self.jobList))
        logging.info(msg)
        return (True, msg)
Exemplo n.º 7
0
    def job(self, args):
        output = {}
        output["router_%s" % args["ipAddr"]] = ""
        commandOutput = ""
        commandCheck = ""
        flag = 0

        logging.info("Connecting to: " + args["ipAddr"])

        try:
            space = rest.Space("https://" + args["url"], args["username"],
                               args["password"])

            autoDetect = space.device_management.devices.\
                          get(filter_={'serialNumber': args["serialNumber"]})[0].\
                          exec_rpc.post(rpcCommand="<command>show chassis hardware</command>")

        except RestException as ex:
            logging.error(
                "An errror occured during the communication with the Junos Space API.\n\tHTTP error code : %s;\n\tJunos Space Message : %s "
                % (ex.response, ex.response.text))
            return ""

        if self.path == "IB":
            output_xml_ib = autoDetect.xpath(
                'netConfReplies/netConfReply/replyMsgData')
            if len(output_xml_ib) != 1:
                logging.error(
                    "The reply from the server does not contain a valid 'show chassis hardware' reply. Full reply was logged in DEBUG level."
                )
                logging.debug(etree.tostring(output_xml_ib, pretty_print=True))
                return ""

            output_text_ib = etree.tostring(output_xml_ib[0],
                                            pretty_print=True)
            finalTextIB = self.unwrap(output_text_ib)
            commandOutputIB = "root@%s> %s\n" % (
                args["ipAddr"],
                "show chassis hardware") + finalTextIB + "\n\n\n"
            output["router_%s" % args["ipAddr"]] = commandOutputIB
            output[
                'show chassis hardware detail | display xml'] = commandOutputIB
            return output

        autoDetect = etree.tostring(autoDetect, pretty_print=True)

        if autoDetect.find("<description>MX") > -1 or autoDetect.find(
                "<description>VMX") > -1 or autoDetect.find(
                    "<description>M") > -1 or autoDetect.find(
                        "<description>T") > -1 or autoDetect.find(
                            "<description>PTX") > -1 or autoDetect.find(
                                "<description>ACX") > -1:
            try:
                with open("commands/MX_4.txt", "r") as data_file:
                    commandSettings = json.load(data_file)
                    logging.info("Loaded list of commands " + "[" +
                                 args["ipAddr"] + "]")

            except IOError:
                msg = "Loading and Verifying Device List : Unable to read input file 'commands/MX_4.txt.'."
                logging.error(msg)
                return (False, msg)

        elif autoDetect.find("<description>SRX") > -1 or autoDetect.find(
                "<description>VSRX") > -1:
            try:
                with open("commands/SRX_4.txt", "r") as data_file:
                    commandSettings = json.load(data_file)
                    logging.info("Loaded list of commands " + "[" +
                                 args["ipAddr"] + "]")

            except IOError:
                msg = "Loading and Verifying Device List : Unable to read input file 'commands/SRX_4.txt'."
                logging.error(msg)
                return (False, msg)

        elif autoDetect.find("<description>QFX") > -1 or autoDetect.find(
                "<description>EX") > -1:
            try:
                with open("commands/QFX_4.txt", "r") as data_file:
                    commandSettings = json.load(data_file)
                    logging.info("Loaded list of commands " + "[" +
                                 args["ipAddr"] + "]")

            except IOError:
                msg = "Loading and Verifying Device List : Unable to read input file 'commands/QFX_4.txt'."
                logging.error(msg)
                return (False, msg)
        else:
            msg = "The device was not recognized!"
            logging.error(msg)
            return {'result': False}

        for i in xrange(len(commandSettings["commandList"])):
            commandCheck = commandSettings["commandList"][i].strip(
            )  #commandCheck contains the current command being evaluated

            if (commandCheck.split(" ", 1)[0] == "show"
                    or commandCheck == "request support information"
                ) and commandCheck.split("|")[-1].strip() != "display xml":

                result = space.device_management.devices.\
                      get(filter_={'serialNumber': args["serialNumber"]})[0].\
                      exec_rpc.post(rpcCommand="<command>" + commandCheck + "</command>")

                output_xml = result.xpath(
                    'netConfReplies/netConfReply/replyMsgData')

                if len(output_xml) != 1:
                    logging.error(
                        "The reply from the server does not contain a valid \""
                        + commandCheck +
                        "\" reply. Full reply was logged in DEBUG level.")
                    logging.debug(etree.tostring(output_xml,
                                                 pretty_print=True))
                    return ""

                output_text = etree.tostring(output_xml[0], pretty_print=True)
                finalText = self.unwrap(output_text)

                commandOutput = "root@%s> %s\n" % (
                    args["ipAddr"], commandCheck) + finalText + "\n\n\n"
                output["router_%s" % args[
                    "ipAddr"]] += commandOutput  #Preparation for the two types of output: file_host1 contains the output of all the commands ran on host1;
                output[
                    commandCheck] = commandOutput  #file_show_chassis_hardware contains the output of the "show chassis harware" command from all hosts
            else:
                logging.error("The following command is not allowed : %s " %
                              (commandCheck))
                return output

        logging.info("Done [" + args["ipAddr"] + "].")
        return output
Exemplo n.º 8
0
import configparser

from jnpr.space import rest

def main(spc):
    """
    Gets all Roles from Space. For each, it gets details and prints the
    name of the role and all tasks that are part of that role.
    """
    roles_list = spc.user_management.roles.get()
    for role in roles_list:
        print("\n%s" % role.title)
        tasks = role.tasks.get()
        for t in tasks:
            task_detail = t.get()
            print("\t%s (%s)" % (task_detail.title, task_detail.name))

if __name__ == '__main__':
    # Initialize logging
    logging.config.fileConfig('../test/logging.conf')

    # Extract Space URL, userid, password from config file
    config = configparser.RawConfigParser()
    config.read("../test/test.conf")
    url = config.get('space', 'url')
    user = config.get('space', 'user')
    passwd = config.get('space', 'passwd')

    # Create a Space REST end point
    space = rest.Space(url, user, passwd)
    main(space)