Пример #1
0
def adduser():
    try:
        user = request.form['UID']
        password = request.form['pass']
        conpass = request.form['conpass']
        Tower = request.form['tower'].lower()
        context = request.form['context'].lower()
        user_en = encryption.encrypt_password("AutoFact", user)
        pass_en = encryption.encrypt_password("AutoFact", password)

        #to_csv(user_en,pass_en,Tower,context)
        if (password == conpass):
            write_CSV = open('./text.csv', 'a')
            check = exists(user_en, Tower)
            if (check == "notexists"):
                write_CSV.write(
                    str(user_en) + "::!::" + str(pass_en) + "::!::" +
                    str(Tower) + "::!::" + str(context) + "\n")
                write_CSV.close()
                return 'Hello   User {} is created for {} Sucessfully...!!!'.format(
                    user, Tower)
            else:
                write_CSV.close()
                return 'Hello   User {} for {} already exists...!!!'.format(
                    user, Tower)
        else:
            return 'Please enter same value for password and confirm password...!!!'
        return listuser()
    except Exception as e:
        LogGenModule.exception(e)
Пример #2
0
def re_assignto_none(tname, ticket_number):
    try:

        LogGenModule.info("Updating Ticket...")
        LogGenModule.info("opening INCIDENT table of ServiceNow Client..")
        #opens the incident table'
        #tname = snow_client.resource(api_path='/table/incident')
        #collects the provided data for the updation of ticket

        update = {"assigned_to": " "}
        LogGenModule.info(
            "Updating ticket with the details provided ServiceNow Client..\n "
            + str(update))

        updated_value = tname.update(
            query={'number': ticket_number},
            payload=update)  #loads the ticket with provided data

        LogGenModule.info("Ticket " + str(updated_value['number']) +
                          "Updated..")
        #assigned_to = updated_value['assigned_to']
        #print(assigned_to)

    except Exception as e:
        LogGenModule.error(e)
Пример #3
0
def upuser():
    try:
        user = request.form['UID']
        expass = request.form['oldspass']
        password = request.form['pass']
        conpass = request.form['conpass']
        Tower = request.form['tower'].lower()
        context = request.form['context'].lower()
        user_en = encryption.encrypt_password("AutoFact", user)
        pass_en = encryption.encrypt_password("AutoFact", expass)
        verification = verify_pass(user_en, Tower, pass_en)
        if (verification == "success"):
            if (len(conpass) > 0):
                if (password == conpass):
                    newpass_en = encryption.encrypt_password(
                        "AutoFact", conpass)
                    res = mod_csv(user_en, newpass_en, Tower, context)
                else:
                    return "Please enter same vale for password and confirm password"
            else:
                res = mod_csv(user_en, pass_en, Tower, context)
        else:
            return "correct value for old password"
        #return render_template('listuser')
        return listuser()
    except Exception as e:
        LogGenModule.exception(e)
Пример #4
0
def cred(tower, context):
    try:
        file_csv = open('./text.csv', 'r')
        user = "******"
        password = "******"
        flag = 0
        for line in file_csv:
            row = line.split("::!::")
            if ((str(tower).lower()) == row[2]):
                row[3] = row[3].replace("\n", "")
                data = row[3].split(",")
                #print(data)
                if (row[3] == "*"):
                    user = encryption.decrypt("AutoFact", row[0])
                    password = encryption.decrypt("AutoFact", row[1])
                for i in data:
                    if (str(i) == str(context)):
                        #print(i)
                        user = encryption.decrypt("AutoFact", row[0])
                        password = encryption.decrypt("AutoFact", row[1])
                        flag = 1
                        break
                if (flag == 1):
                    break

        op_data = [user, password]
        return op_data

    except Exception as e:
        LogGenModule.Exception(
            "Issue while fetching the data for given context and tower")
        LogGenModule.Exception(e)
def run_s():
    try:

        print(Number)
        print(Escalation_Group)  #escalation group
        # Use paramiko for os command execution
        client = paramiko.SSHClient()
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        #login to the router
        client.connect(hostname=Configuration_Item,
                       username=user,
                       password=passwrd)
        #executes the command and capures the output and input
        stdin, stdout, stderr = client.exec_command('ls -lrt')
        result = str(stdout.read())
        print(result)  #importent to update notes
        client.close()
        print("executed")  # this will resolve the ticket

    except Exception as e:
        print("result")  #important to update notes
        print("reassign_group")  # this will fail the ticket
        LogGenModule.Exception(
            "Issue while running the wintel CPU utilization")
        LogGenModule.Exception(e)
Пример #6
0
def move_file(srcpath, despath, srcfile):
    try:
        destination = despath + srcfile
        source = srcpath + srcfile
        shutil.copyfile(source, destination)
        os.remove(source)
    except Exception as e:
        LogGenModule.Exception("Issue while mpving the files")
        LogGenModule.Exception(e)
Пример #7
0
def exists(user_en, Tower):
    try:
        file_csv = open('./text.csv', 'r')
        flag = "notexists"
        for line in file_csv:
            row = line.split("::!::")
            if (str(user_en) == row[0]):
                if (str(Tower) == row[2].lower()):
                    flag = "exists"
        return flag
    except Exception as e:
        LogGenModule.exception(e)
Пример #8
0
def verify_pass(user_en, Tower, passphrase):
    try:
        file_csv = open('./text.csv', 'r')
        flag = "failed"
        for line in file_csv:
            row = line.split("::!::")
            if (str(user_en) == row[0]):
                if (str(Tower) == row[2].lower()):
                    if (str(passphrase) == row[1]):
                        flag = "success"
        return flag
    except Exception as e:
        LogGenModule.exception(e)
def to_xml(data, name_of_file):  #creates the XML files
    try:
        xml = dicttoxml(data, custom_root='test',
                        attr_type=False)  #converts the dictonary data into XML
        filename = "./Queue/InputFiles/" + name_of_file + ".xml"
        file = open(filename, "w")
        xml = str(xml).replace("b'", "")
        xml = str(xml).replace("'", "")
        file.write(str(xml) + "\n")
        file.close()
    except Exception as e:
        LogGenModule.Exception("Not able to create XML File")
        LogGenModule.Exception(e)
Пример #10
0
def deleteuser():
    try:
        user = request.args.get('UID')
        Tow = request.args.get('tower')
        Tower = Tow.lower()
        cont = request.args.get('context')
        context = cont.lower()
        user_en = encryption.encrypt_password("AutoFact", user)
        result = []
        result.append(user + "!" + Tower + "!" + context)
        results = result
        return render_template('del_user.html', results=results)
    except Exception as e:
        LogGenModule.exception(e)
Пример #11
0
def listuser():
    try:
        dic = []
        file_csv = open('./text.csv', 'r')
        for line in file_csv:
            row = line.split("::!::")
            user = encryption.decrypt("AutoFact", row[0])
            row[3] = row[3].replace("\n", "")
            dic.append(user + "!" + row[2] + "!" + row[3])
            #print(dic)
        #(dic)
        results = dic
        return render_template('list.html', results=results)
    except Exception as e:
        LogGenModule.exception(e)
def StatusValuetoString(
        Value):  # converts the status value from integer to string
    try:
        LogGenModule.info("converting the status value to string...")
        status = {
            '1': 'New',
            '2': 'In Progress',
            '3': 'Pending',
            '4': 'Resolved',
            '5': 'Closed'
        }
        return status[Value]
    except Exception as e:
        LogGenModule.Exception("Issue in converting status value to string" +
                               e)
def fetch_details(
    tablepath, attribute, value, outval
):  # fetches the data from the given table for mentioned attribute and provides the result for desired attribute
    try:
        LogGenModule.info("Fetching the details from : {}".format(tablepath))
        respond = snow_client.resource(api_path=tablepath)
        groupname = respond.get(query={attribute: value})
        for res in groupname.all():
            #print(res[outval])
            return res[outval]

    except Exception as e:
        LogGenModule.Exception(
            "Issue while fetching the Ticket data from table : " + tablepath +
            "\natrribute : " + attribute)
        LogGenModule.Exception(e)
Пример #14
0
def delete_user():
    try:
        user = request.form['UID']
        expass = request.form['oldspass']
        Tower = request.form['tower'].lower()
        context = request.form['context'].lower()
        user_en = encryption.encrypt_password("AutoFact", user)
        pass_en = encryption.encrypt_password("AutoFact", expass)
        verification = verify_pass(user_en, Tower, pass_en)
        if (verification == "success"):
            res = del_csv(user_en, pass_en, Tower, context)
        else:
            return "provide correct value for password"
        #return render_template('listuser')
        return listuser()
    except Exception as e:
        LogGenModule.exception(e)
Пример #15
0
def find_flow(ticket_summary):
    try:
        #print(ticket_summary)
        with open(
                '../json_files/keys.json'
        ) as key_data:  # reads the Keys and Flows data from json file
            key_to_flow = json.load(key_data)

        Summary = ticket_summary
        Matches = 0
        Flow = "NF"
        Escalate_to = "Not Found"
        tower = "NF"
        suffix = "NF"
        Summary = Summary.lower()
        for Combs in key_to_flow['KeytoFlowCombination']:
            Matches = 0
            for key in Combs['KeyWords']:
                if key.lower() in Summary:
                    Matches += 1
                #print(key+ " " +str(Matches))
            if Matches == len(Combs['KeyWords']):
                Flow = Combs['Flow']
                Escalate_to = Combs['EscalateTo']
                tower = Combs['Tower']
                suffix = Combs['suffix']
                key_data = [Flow, Escalate_to, tower, suffix]

                #print("Selected Flow for summarry : "+ Flow)
                break

        key_data = [Flow, Escalate_to, tower, suffix]

        #print("Selected Flow for summarry : "+ key_data)
        return key_data

    except Exception as e:
        LogGenModule.Exception("Issue while fetching the Flow for the ticket")
        LogGenModule.Exception(e)


#summary =input("enter summary")
#find_flow(summary)
#print("Flowname "+find_flow(summary)[0])
Пример #16
0
def encrypt(msg):
    try:
        key = "AutoFactCIS1569"
        encryped = []
        encoded = base64.b64encode((msg).encode('utf-8'))
        for i, c in enumerate(str(encoded.decode('ascii'))):
            key_c = ord(key[i % len(key)])
            msg_c = ord(c)
            encryped.append(chr((msg_c + key_c) % 127))
        return ''.join(encryped)
    except Exception as e:
        LogGenModule.Exception("error occured while encrypting the data")
Пример #17
0
def reassign_group(ticket_number,group,status,comments):
    try:
        LogGenModule.info("Updating Ticket...")
        LogGenModule.info("opening INCIDENT table of ServiceNow Client..")
        tname = snow_client.resource(api_path='/table/incident')
        update = {"assignment_group" : group,'state': status ,'work_notes': comments}
        
        updated_value = tname.update(query={'number': ticket_number}, payload=update)#loads the ticket with provided data
        return "done"
        LogGenModule.info("Updating ticket with the details provided ServiceNow Client..\n "+str(update))
    except Exception as e:
        
        LogGenModule.error(e)
        return "not done"
Пример #18
0
def run_script(
        suffix, Number, Flow, Configuration_Item, Escalation_Group, Summary,
        Tower, userID, location,
        Department):  # executes the use case flow in the backend process
    try:
        path = '../Queue/InputFiles/'
        file = Number + '.xml'

        if suffix == 'NONE':
            cmd = 'start /b ' + Flow + ' ' + Number + ' ' + "\"" + Flow + "\"" + ' ' + "\"" + Configuration_Item + "\"" + ' ' + "\"" + Escalation_Group + "\"" + ' ' + "\"" + Summary + "\"" + ' ' + "\"" + userID + "\"" + ' ' + "\"" + location + "\"" + ' ' + "\"" + Department + "\""
        else:
            cmd = 'start /b ' + suffix + ' ' + Flow + ' ' + Number + ' ' + "\"" + Flow + "\"" + ' ' + "\"" + Configuration_Item + "\"" + ' ' + "\"" + Escalation_Group + "\"" + ' ' + "\"" + Summary + "\"" + ' ' + "\"" + userID + "\"" + ' ' + "\"" + location + "\"" + ' ' + "\"" + Department + "\""  #+' >> D:\\custom_orch\\executing_files\\'+Number+'.txt' #command to choose the script flile
        #cmd = python ping.py asdfdf sdfdfs 10.181.11.121 fgfgfdgfg
        LogGenModule.info(cmd)
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
        LogGenModule.Exception("executing the usecase flow" + str(Flow))
        move_files.move_file(
            path, '../Queue/ProcessingFilesXML/',
            file)  # Moves the source file from processed files
    except Exception as e:
        LogGenModule.Exception("Issue while triggering the identified Flow")
        LogGenModule.Exception(e)
Пример #19
0
def del_csv(user, passw, tow, context):
    try:
        file1 = open('text.csv', 'r')
        file2 = open('filedel.csv', 'a')
        for line in file1:
            #print(line)
            row = line.split("::!::")
            if (row[0] == user):
                if (row[2] == tow):
                    continue
                    sol = "Sucessfully Updated the User Data...!!!!!!!"
            else:
                sol = "not able to find the user..!!!"
            file2.write(
                str(row[0]) + "::!::" + str(row[1]) + "::!::" + str(row[2]) +
                "::!::" + str(row[3]))
        file1.close()
        file2.close()
        shutil.move("./filedel.csv", "./text.csv")
        return sol
    except Exception as e:
        LogGenModule.exception(e)
Пример #20
0
def table_details(
    tablepath, attribute1, value1, attribute2, value2
):  # fetches the data from the given table for mentioned attribute and provides the result for desired attribute
    try:
        LogGenModule.info("Fetching the details from : {}".format(tablepath))
        respond = snow_client.resource(api_path=tablepath)
        groupname = respond.get(query={attribute1: value1, attribute2: value2})
        data = []
        #print(attribute2)
        for res in groupname.all():
            a = res['item_option_new']['value']
            res_d = ["sys_name", "choice_table"]
            res_Data = fetch_details("/table/item_option_new", "sys_id", a,
                                     res_d)
            ques = res_Data[0]
            #print(ques)
            #print(res['value'])
            if len(str(res_Data[1])) != 0:
                val = fetch_details("/table/" + res_Data[1], "sys_id",
                                    res['value'], ["name"])
                if len(val) == 0:
                    val = res['value']
                else:
                    val = val[-1]
            else:
                val = res['value']
            items = {ques: val}
            #print(items)
            data.append(items)
            #print(res)
        return data

    except Exception as e:
        LogGenModule.Exception(
            "Issue while fetching the Ticket data from table : " + tablepath +
            "\natrribute : " + attribute1)
        LogGenModule.Exception(e)
Пример #21
0
def encrypt_password(key, msg):
    try:

        encryped = []
        encoded = base64.b64encode((msg).encode('utf-8'))
        #print(encoded)
        #print(str(encoded.decode('ascii')))
        for i, c in enumerate(str(encoded.decode('ascii'))):
            key_c = ord(key[i % len(key)])
            msg_c = ord(c)
            encryped.append(chr((msg_c + key_c) % 127))
        #print(''.join(encryped).encode('utf-8'))
        return ''.join(encryped)
    except Exception as e:
        LogGenModule.Exception("error occured")
Пример #22
0
def decrypt(key, encryped):
    try:
        msg = []
        for i, c in enumerate(encryped):
            key_c = ord(key[i % len(key)])
            enc_c = ord(c)
            msg.append(chr((enc_c - key_c) % 127))
        encoded = ''.join(msg)
        encoded = encoded.replace("b'", "")
        encoded = encoded.encode('utf-8')
        #print(encoded)
        data = base64.b64decode(encoded.decode('utf-8'))
        #print(data)
        return data.decode('utf-8')
    except Exception as e:
        LogGenModule.Exception("error occured")
Пример #23
0
def reassign_group(tname, ticket_number, group):
    try:
        LogGenModule.info("Updating Ticket...")
        LogGenModule.info("opening INCIDENT table of ServiceNow Client..")
        update = {"assignment_group": group}
        LogGenModule.info(
            "Updating ticket with the details provided ServiceNow Client..\n "
            + str(update))
        updated_value = tname.update(
            query={'number': ticket_number},
            payload=update)  #loads the ticket with provided data

    except Exception as e:
        LogGenModule.error(e)


#reassign_group(ticket_number,"Network")

#re_assignto_none(ticket_number)
Пример #24
0
                    "r")  # Open the JSON file for reading
    data = json.load(jsonFile)  # Read the JSON into the buffer
    jsonFile.close()  # Close the JSON file

    ## Working with buffered content
    #tmp = data["location"]
    data['Instance Details'][0]['user'] = user
    data['Instance Details'][0]['password'] = password
    data['Instance Details'][0]['instance'] = instance
    ## Save our changes to JSON file
    jsonFile = open("./json_files/snow_login.json", "w+")
    jsonFile.write(json.dumps(data))
    jsonFile.close()


if __name__ == '__main__':
    try:
        #logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s',datefmt='%a, %d-%b-%Y %H:%M:%S -', filename = datetime.datetime.now().strftime('../Logs/log_%d_%m_%Y.log'))
        instance = input("Enter the Servicenow Instance ")
        ins_user = input("Enter the Servicenow user ")
        ins_password = getpass.getpass("Enter the Servicenow password ")

        user = encrypt(ins_user)
        password = encrypt(ins_password)
        updateJsonFile(user, password, instance)
        print("Servicenow user : "******"Servicenow password : "******"error occured")
                )  # fetches the data from the output text file
                result = lines[-1]
                Number = lines[0]
                notes = lines[-2]
                escalate = lines[1]
            textfile.close()
            #### Moves the source file from processed files depending on the keyword ###
            if (result == "failed"):
                print("result is failed need to escalate")
                move_files.move_file(path, './Queue/executing_files/', file)

            if (result == "executed"):
                res = update_incident.update_ticket(Number, "Closed", notes)
                print(res)
                if (res == "done"):
                    LogGenModule.info("Moving the source file.." + str(file))
                    move_files.move_file(path, './Queue/closed/', file)

            if (result == "remove_assignee"):
                res = update_incident.re_assignto_none(Number)
                print(res)
                if (res == "done"):
                    LogGenModule.info("Moving the source file.." + str(file))
                    move_files.move_file(path, './Queue/closed/', file)

            if (result == "reassign_group"):
                res = update_incident.reassign_group(Number, escalate,
                                                     "Assigned", notes)
                print(res)
                if (res == "done"):
                    LogGenModule.info("Moving the source file.." + str(file))
def read_ticket(groupname, status):
    try:

        total = 0
        count = 0
        esc = 0
        found = 0

        LogGenModule.info(
            "reading the data for the given Assignment group and status...")
        tname = snow_client.resource(api_path='/table/incident')
        response = tname.get(query={
            'assignment_group': groupname,
            'state': status
        })

        for result in response.all():
            total += 1
            if ((result['sys_updated_on']) >
                    prvtime):  # compares with previous time
                if (
                    (result['sys_updated_on']) <= curr_time
                ):  # compares with the captured current time                                                                                               #reads the result for the provided attributes
                    #print(result['assignment_group']['value'])
                    if len(str(result['assignment_group'])
                           ) == 0:  #checks the length of the assignment_group
                        group = result['assignment_group']
                    else:
                        inval = result['assignment_group']['value']
                        group = fetch_details(
                            "/table/sys_user_group", "sys_id", inval, "name"
                        )  #triggers the fetch details function and gets the group name

                    if len(str(result['cmdb_ci'])
                           ) == 0:  #checks the length of the CI
                        CI = result['cmdb_ci']
                        CI_sys_id = result['cmdb_ci']
                    else:
                        CI_sys_id = result['cmdb_ci']['value']
                        CI = fetch_details("/table/cmdb_ci", "sys_id",
                                           CI_sys_id, "name")

                    if len(str(result['caller_id'])
                           ) == 0:  #checks the length of the CI
                        user_name = "NA"
                        Loc = "NA"
                        dep = "NA"
                    else:
                        Uid = result['caller_id']['value']
                        user_name = fetch_details("/table/sys_user", "sys_id",
                                                  Uid, "user_name")

                        location_Data = fetch_details("/table/sys_user",
                                                      "sys_id", Uid,
                                                      "location")
                        #print(type(location_Data))
                        #print(location_Data)
                        if len(str(location_Data)) != 0:
                            Locat = location_Data['value']
                            #print(type(Locat))
                            Loc = fetch_details("/table/cmn_location",
                                                "sys_id", Locat, "name")
                        else:
                            Loc = "Not Found"

                        depart_data = fetch_details("/table/sys_user",
                                                    "sys_id", Uid,
                                                    "department")
                        if len(str(depart_data)) != 0:
                            depart = depart_data['value']
                            dep = fetch_details("/table/cmn_department",
                                                "sys_id", depart, "name")
                        else:
                            dep = ""

                    if len(str(result['assigned_to'])
                           ) == 0:  #checks the length of the assigned_to
                        assigneduser = result['assigned_to']
                    else:
                        inuser = result['assigned_to']['value']
                        assigneduser = fetch_details(
                            "/table/sys_user", "sys_id", inuser, "name"
                        )  #triggers the fetch details function and gets the user name

                    status = result['state']
                    statusval = StatusValuetoString(
                        status)  # gets the string for the status value

                    LogGenModule.info((
                        "\n***Details fetched for the Incident : {}***\n Status : {}\n Summary : {}\n Description : {}\n Category : {}\n Sub-Category : {}\n Assigned Group : {}\n Assignee : {}"
                        .format(result['number'], statusval,
                                result['short_description'],
                                result['description'], result['category'],
                                result['subcategory'], group, assigneduser)))

                    #print("number of the Incident : {}\n Status : {}\n Summary : {}\n Description : {}\n Category : {}\n Sub-Category : {}\n Assigned Group : {}\n Assignee : {}".format(result['number'],statusval,result['short_description'],result['description'],result['category'],result['subcategory'],group,assigneduser))

                    Flow_name = Keys_Flows.find_flow(
                        result['short_description'])[0]
                    E_G = Keys_Flows.find_flow(result['short_description'])[1]
                    tower_name = Keys_Flows.find_flow(
                        result['short_description'])[2]
                    #print(len(Flow_name))
                    #if len(Flow_name)==0:
                    #Escalation_Reassign.re_assignto_none(tname,result['number'])
                    name_of_file = result[
                        'number']  #name of the xml file to be created
                    #name_of_file = result['number']

                    if Flow_name == "NF":
                        Flow_Result = "No Flow Found"
                        Flowname = "No Flow Identified"
                        remarks = "Escalated"
                        Escalation_Group = "Notfound"
                        if (EscalateTo == 'NONE'):
                            continue
                        else:
                            Escalation_Reassign.reassign_group(
                                tname, result['number'], EscalateTo)
                        esc += 1
                    else:
                        Flow_Result = "Sent to Orchestrator"
                        remarks = "UID from orchestrator"
                        Flowname = Flow_name
                        Escalation_Group = E_G
                        found += 1

                        dic = {
                            "Incident": {
                                'Sys_ID': result['sys_id'],
                                'Number': result['number'],
                                'Status': result['state'],
                                'Assigned Group': group,
                                'Assignee': assigneduser,
                                'Category': result['category'],
                                'Sub-Category': result['subcategory'],
                                'Summary': result['short_description'],
                                'Description': result['description'],
                                'Flow': Flow_name,
                                'Configuration Item': CI,
                                'Sys_ID_CI': CI_sys_id,
                                'Escalation_Group': Escalation_Group,
                                'Tower': tower_name,
                                'User_ID': user_name,
                                'user_location': Loc,
                                'user_department': dep
                            }
                        }
                        #dictionary.append(dic)
                        #print(dictionary)
                        Xml_data = to_xml(
                            dic, name_of_file
                        )  # calls the function to convert data into XML format
                        capture_scripts(Flow_name)

                    send_data = "<tr><td>" + datetime.datetime.now(
                    ).strftime('%d-%m-%y %H:%M:%S') + "</td><td>" + result[
                        'number'] + "</td><td>" + Flow_Result + "</td><td>" + Flowname + "</td><td>" + remarks + "</td></tr>"
                    create_log_html(send_data)
        replace = open("./Time_Stamps/pre_time.txt", "w")
        replace.write(str(curr_time))  #replaces the previous time
        replace.close()
        count = (total - (found + esc))
        log = open("./Time_Stamps/time_reference.txt", "a")
        log.write(" Total : " + str(total) + " FWD = " + str(found) +
                  " ESC : " + str(esc) + " FLTR : " + str(count) +
                  "\n")  # logs the executed time frame
        log.close()
        parse_xml.exec_xml()

    except Exception as e:

        LogGenModule.Exception("Issue while fetching the Ticket data")
        LogGenModule.Exception(e)
        f = open('./Time_Stamps/pre_time.txt')
        time = f.read()
        f.close()  # if exists time = previous captured timebreak;
    else:
        time = "1994-04-04 06:45:20"  # if not exists hardcodes the value to the previous time

    #print(time)
    curr_time = datetime.datetime.now().strftime(
        '%Y-%m-%d %H:%M:%S')  # captures current time
    data1 = datetime.datetime.strptime(time, '%Y-%m-%d %H:%M:%S')
    prvtime = datetime.datetime.strftime(data1, '%Y-%m-%d %H:%M:%S')
    log = open("./Time_Stamps/time_reference.txt", "a")
    log.write(" > " + str(prvtime) + " <= " + str(curr_time))
    log.close()

    LogGenModule.info("=============================")

    try:
        LogGenModule.info("*******Fetching the Instance Details*******")

        with open('./json_files/snow_login.json'
                  ) as json_data:  #collects the data from the input file
            data = json.load(json_data)
            instancename = data["Instance Details"][0]["instance"]
            username = decrypt(data["Instance Details"][0]["user"])
            paswd = decrypt(data["Instance Details"][0]["password"])
        LogGenModule.info("*******Fetching the Ticket Data*******")
        with open('./json_files/snow_read_ticket.json') as json_ticket:
            ticket = json.load(json_ticket)
            Assigned_Group = ticket["Ticket Details"][0]["Assigned_Group"]
            status = ticket["Ticket Details"][0]["status"]
Пример #28
0
def exec_xml(ticket):
    try:

        path = '../Queue/InputFiles/'  # path in which input XML files are stored
        listOfFiles = os.listdir(
            path)  #reads all the files in the provided dir
        pattern = '*.xml'

        #print(len(fetch_data))
        dic = []

        try:

            for file in listOfFiles:
                if fnmatch.fnmatch(file, pattern):  # matches the pattern
                    #print(file)
                    tree = ET.parse(path +
                                    file)  # parses the files in the given dir
                    root = tree.getroot()
                    if ticket == "Request":
                        fetch_data = [
                            'suffix', 'Task_Number', 'Flow',
                            'Escalation_Group', 'Task_Description', 'Tower',
                            'Requested_for', 'user_location', 'user_department'
                        ]
                        for app in root.findall(
                                'Request'):  #searches for the parent tag
                            for data in fetch_data:
                                #print(data)
                                for l in app.findall(
                                        data
                                ):  # searches for the mentioned child tag
                                    #print(l.text)            #gives the value of the child tag
                                    dic.append(l.text)
                        print(dic)

                        run_script(str(dic[0]), str(dic[1]), str(dic[2]), "NF",
                                   str(dic[3]), str(dic[4]), str(dic[5]),
                                   str(dic[6]), str(dic[7]), str(dic[8]))
                        del dic[:]

                    if ticket == "Incident":
                        fetch_data = [
                            'suffix', 'Number', 'Flow', 'Configuration_Item',
                            'Escalation_Group', 'Summary', 'Tower', 'User_ID',
                            'user_location', 'user_department'
                        ]
                        for app in root.findall(
                                'Incident'):  #searches for the parent tag
                            for data in fetch_data:
                                #print(data)
                                for l in app.findall(
                                        data
                                ):  # searches for the mentioned child tag
                                    #print(l.text)            #gives the value of the child tag
                                    dic.append(l.text)
                        print(dic)

                        run_script(str(dic[0]), str(dic[1]), str(dic[2]),
                                   str(dic[3]), str(dic[4]), str(dic[5]),
                                   str(dic[6]), str(dic[7]), str(dic[8]),
                                   str(dic[9]))
                        del dic[:]

        except Exception as e:
            LogGenModule.Exception("Issue while running the usecase XML file")
            LogGenModule.Exception(e)

    except Exception as e:
        LogGenModule.Exception("Issue while parsing the XML file")
        LogGenModule.Exception(e)
Пример #29
0
print(interface)
file = Number + '.txt'
tower = "Network"
Login_ID = sys.argv[6]
Password = sys.argv[7]
sys.stdout = open('./Queue/executing_files/' + file, 'w')
print(Number)
print(Escalation_Group)

# -----------------------------Main function--------------------------------
try:

    command = "show interface " + interface
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    LogGenModule.info("connecting")
    ssh.connect(hostname=Switch_IP, username=Login_ID, password=Password)
    LogGenModule.info("connected..." + Switch_IP + "....interface.." +
                      interface)
    ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(command)
    ssh_error = list(
        ssh_stderr.readlines()
    )  # converting to list because sometimes std_error shows up even when empty

    flag_as = 0
    flag_lp = 0
    flag_tod = 0
    flag_ie = 0
    flag_crc = 0
    flag_oe = 0
Пример #30
0
def read_SRticket(groupname, status):
    try:

        total = 0
        count = 0
        esc = 0
        found = 0
        LogGenModule.info("*******Fetching the Service Request Details*******")
        LogGenModule.info(
            "reading the data for the given Assignment group and status...")
        tname = snow_client.resource(api_path='/table/sc_task')
        if (groupname == "any"):
            response = tname.get(query={'state': status})
        else:
            response = tname.get(query={
                'assignment_group': groupname,
                'state': status
            })

        for result in response.all():
            total += 1
            if ((result['sys_updated_on']) >
                    prvtime):  # compares with previous time
                if ((result['sys_updated_on']) <=
                        curr_time):  # compares with the captured current time
                    #---------------------------------------------------SC ITEM DATA---------------------------------------------------------#                                                                                    #reads the result for the provided attributes
                    #print(result)
                    #Assignment Group
                    if len(str(result['assignment_group'])
                           ) == 0:  #checks the length of the assignment_group
                        group = result['assignment_group']
                    else:
                        inval = result['assignment_group']['value']
                        group = fetch_details(
                            "/table/sys_user_group", "sys_id", inval, ["name"]
                        )  #triggers the fetch details function and gets the group name
                    #Assignee
                    if len(str(result['assigned_to'])
                           ) == 0:  #checks the length of the assignment_group
                        assigned = result['assigned_to']
                    else:
                        inval = result['assigned_to']['value']
                        assigned = fetch_details("/table/sys_user", "sys_id",
                                                 inval, ["name"])

                    task_shortDesc = result['short_description']
                    task_Desc = result['description']
                    sc_task_SysID = result['sys_id']
                    #---------------------------------------------------Request ITEM DATA---------------------------------------------------------#
                    #
                    if len(str(result['request_item'])) == 0:
                        Req_Desc = "NA"
                        Req_ShortDes = "NA"
                        Requested_by = "NA"
                        Requested_for = "NA"
                        Catalog_Item = "NA"
                    else:

                        RIT = result['request_item']['value']

                        req_data = [
                            "description", "short_description",
                            "sys_created_on", "opened_by", "request",
                            "cat_item"
                        ]
                        Req_item_data = fetch_details("/table/sc_req_item",
                                                      "sys_id", RIT, req_data)
                        Req_Desc = str(Req_item_data[0])

                        #print(Req_item_data)
                        Req_ShortDes = str(Req_item_data[1])

                        Req_created = Req_item_data[2]

                        Req_by = Req_item_data[3]
                        #print(Req_by)
                        if len(str(Req_by)) != 0:
                            opened = Req_by['value']
                            #print(manager_Data)
                            req_user_data = [
                                "name", "user_name", "location", "department"
                            ]
                            req_user_datas = fetch_details(
                                "/table/sys_user", "sys_id", opened,
                                req_user_data)
                            Requested_by = req_user_datas[0]
                            rq_user = req_user_datas[1]

                            ###############

                            location_Data = req_user_datas[2]
                            #print(type(location_Data))
                            #print(location_Data)
                            if len(str(location_Data)) != 0:
                                Locat = location_Data['value']
                                #print(type(Locat))
                                Loc = fetch_details("/table/cmn_location",
                                                    "sys_id", Locat, ["name"])
                            else:
                                Loc = "Not Found"

                            depart_data = req_user_datas[3]
                            if len(str(depart_data)) != 0:
                                depart = depart_data['value']
                                dep = fetch_details("/table/cmn_department",
                                                    "sys_id", depart, ["name"])
                            else:
                                dep = "Not Found"
                        else:
                            Requested_by = "No Value"
                            rq_user = "******"
                            Loc = "Not Found"
                            dep = "Not Found"

                        Req_table = Req_item_data[4]
                        if len(str(Req_table)) != 0:
                            Requested = Req_table['value']
                            #print(manager_Data)
                            Reques_for = fetch_details("/table/sc_request",
                                                       "sys_id", Requested,
                                                       ["requested_for"])
                            req = Reques_for[0]['value']
                            Requested_for = fetch_details(
                                "/table/sys_user", "sys_id", req, ["name"])
                        else:
                            Requested_for = "No Value"

                        c_item = Req_item_data[5]
                        if len(str(c_item)) != 0:
                            #print(c_item)
                            cat = c_item['value']
                            Catalog_Item = (fetch_details(
                                "/table/sc_cat_item", "sys_id", cat,
                                ["name"]))[0]
                        else:
                            Catalog_Item = "No Value"
    #---------------------------------------------------Cart Variable DATA---------------------------------------------------------#
    #task_cre = result['sys_created_on']
    #print(task_cre)
    #print(Req_created)
                    options = table_details("/table/sc_item_option",
                                            "sys_created_on", Req_created,
                                            "sys_created_by", rq_user)
                    if len(str(options)) != 0:
                        variables = options
                    else:
                        variables = "None"
                    #print(variables)
                    LogGenModule.info((group))
                    name_of_file = result[
                        'number']  #name of the xml file to be created

                    Flows = Keys_Flows.find_flow(result['short_description'])
                    Flow_name = Flows[0]
                    E_G = Flows[1]
                    tower_name = Flows[2]
                    suffix = Flows[3]
                    #print(Flows)
                    if Flow_name == "NF":
                        Flow_Result = "No Flow Found"
                        Flowname = "No Flow Identified"
                        remarks = "Escalated"
                        Escalation_Group = "Notfound"
                        if (EscalateTo == 'NONE'):
                            continue
                        else:
                            Escalation_Reassign.reassign_group(
                                tname, result['number'], EscalateTo)
                        esc += 1
                    else:
                        Flow_Result = "Sent to Orchestrator"
                        remarks = "UID from orchestrator"
                        Flowname = Flow_name
                        Escalation_Group = E_G
                        found += 1
                    dic = {
                        "Request": {
                            'Task_Sys_ID': result['sys_id'],
                            'Task_Number': result['number'],
                            'Task_Status': result['state'],
                            'Assigned Group': group,
                            'Task_Description': result['description'],
                            'Task_ShortDescription':
                            result['short_description'],
                            'Requested_for': Requested_for,
                            'Requested_by': Requested_by,
                            'Tower': tower_name,
                            'Flow': Flow_name,
                            'suffix': suffix,
                            'Escalation_Group': Escalation_Group,
                            'user_location': Loc,
                            'user_department': dep,
                            'Request_Description': Req_Desc,
                            'Request_ShortDescription': Req_ShortDes,
                            'CatalogItem_Name': Catalog_Item,
                            'Cat_Variables': variables
                        }
                    }
                    #dictionary.append(dic)

                    #print(dic)
                    Xml_data = to_xml(
                        dic, name_of_file
                    )  # calls the function to convert data into XML format
                    #capture_scripts(Flow_name)

                send_data = "<tr><td>" + datetime.datetime.now(
                ).strftime('%d-%m-%y %H:%M:%S') + "</td><td>" + result[
                    'number'] + "</td><td>" + Flow_Result + "</td><td>" + Flowname + "</td><td>" + remarks + "</td></tr>"
                create_log_html(send_data)

        count = (total - (found + esc))
        log = open("../Time_Stamps/time_reference.txt", "a")
        log.write(" Total : " + str(total) + " FWD = " + str(found) +
                  " ESC : " + str(esc) + " FLTR : " + str(count) +
                  "\n")  # logs the executed time frame
        log.close()
        #parse_xml.exec_xml()
        return "success"
    except Exception as e:

        LogGenModule.Exception("Issue while fetching the Ticket data")
        LogGenModule.Exception(e)
        return "failed"