Esempio n. 1
0
def main():

    # ask user to input a name for a new space
    new_space_name = input('Enter a name for the Webex Teams Space: ')

    # create a new space
    space_id = webex_teams_apis.create_space(new_space_name)
    print('The new space created has the Webex Teams id: ', space_id)

    # ask user to input an email for a Webex Teams user
    new_membership = input('\nEnter an email for a Webex Teams user to invite to the space: ')

    # invite user to join the space
    webex_teams_apis.add_space_membership(new_space_name, new_membership)
    input('Check the space for the new membership, hit any key to continue ')

    # ask user to input the message to be posted in the space
    new_message = input('\nEnter the message to be posted in the space: ')

    # post message to the new space
    webex_teams_apis.post_space_message(new_space_name, new_message)
    input('Check the space for the new message posted, hit any key to continue ')

    # post the same message marked down
    webex_teams_apis.post_space_markdown_message(new_space_name, new_message)
    input('\nCheck the space for the marked down message posted, hit any key to continue ')

    # ask user to input an domain name, and the URL link to be posted in the space
    new_domain_name = input('\nEnter the Domain Name be posted in the space: ')
    new_url = input('Enter the URL to be associated with the Domain Name (format "http://..."): ')

    # post the new Domain Name and URL to the space
    webex_teams_apis.post_space_url_message(new_space_name, new_domain_name, new_url)
    input('Check the space for the URL posted, hit any key to continue ')

    # upload a new image file, one provided SDA_Roles.jpg
    webex_teams_apis.post_space_file(new_space_name, 'SDA_Roles.jpg', 'image/jpg', '')
    input('\nCheck the space for the image file uploaded, hit any key to continue ')
    
    # ask the user invited to post a message to the space
    input('\nAsk the user invited to the space to post a message in the space using the Mobile or Desktop Webex Teams Client \nHit any key to continue')
    
    # check for the last message posted in the space and the identity of the user
    last_message_info = webex_teams_apis.last_user_message(new_space_name)
    
    print('\nLast message posted in the space was - ', last_message_info[0], '\nLast message was posted by the user - ', last_message_info[1])

    # delete the space
    input('\n\nEnter any key to delete the space you created ')
    
    webex_teams_apis.delete_space(new_space_name)
Esempio n. 2
0
def moveGroup(guid, groupGuid, groupName):
    url = f'https://api.amp.cisco.com/v1/FIXME'
    print(url)
    payload = '{"group_guid": "'+str(groupInfo[FIXME])+'"}'
    #print(payload)
    headers = {'content-type': 'application/json'}
    req = requests.patch(url, auth = (AMP_CLIENT_ID, AMP_KEY),data=payload,headers=headers)
    #print(req)

    # error handling if true then the request was HTTP 200, so successful
    if (req.status_code != 202):
        print('An error has ocurred with the following code %s' % req.status_code)
        sys.exit(0)

    output = req.json()
    print()
    print()
    print('*'*110)
    print('The device is now in the {groupName} group with a group GUID of {groupGuid}')
    print('*'*110)
    print()
    print()

#-------------------Section 10-------------------

    moveGroup(guid,groupInfo[0],groupInfo[1])
    WEBEX_MESSAGE = f'The endpoint with GUID of "{guid}" has been moved to the "{groupInfo[1]}" group by StudentXX'
    webex_teams_apis.post_space_message(WEBEX_TEAMS_SPACE_NAME, WEBEX_MESSAGE)


    print('='*30)
    print('Please remediate the endpoint')
    input('Press enter when ready to move from Triage to the home group')
    print('='*30)

    groupInfo=getGroups()
    moveGroup(guid,groupInfo[0],groupInfo[1])
    WEBEX_MESSAGE = f'The endpoint with GUID of "{guid}" has been moved to the "{groupInfo[1]}" group by StudentXX'
    webex_teams_apis.post_space_message(WEBEX_TEAMS_SPACE_NAME, WEBEX_MESSAGE)

    print('='*30)
    print('THE SCRIPT HAS COMPLETED')
    print('='*30)
Esempio n. 3
0
    auth = '%s:%s' % (ikey, sig.hexdigest())
    #print(auth)
    encoded_auth = base64.b64encode(auth.encode('utf-8'))

    # return headers
    return {
        'Date': now,
        'Authorization': 'Basic %s' % str(encoded_auth, 'UTF-8')
    }


if __name__ == "__main__":

    USER_INFO = createDuoUser()
    WEBEX_MESSAGE = f'A DUO user ID of {USER_INFO[1]} with an ID of {USER_INFO[0]}has been created successfully by StudentXX '
    webex_teams_apis.post_space_message(WEBEX_TEAMS_SPACE_NAME, WEBEX_MESSAGE)
    print()
    print()
    PHONE_INFO = createDuoPhone()
    WEBEX_MESSAGE = f'A DUO a phone # of {PHONE_INFO[1]} has been with an ID of {PHONE_INFO[0]}created successfully by StudentXX'
    webex_teams_apis.post_space_message(WEBEX_TEAMS_SPACE_NAME, WEBEX_MESSAGE)
    print()
    print()
    associateUserToPhone()
    WEBEX_MESSAGE = f'A DUO user with ID of {USER_INFO[1]} has been associated with a phone with ID of {PHONE_INFO[1]} successfully by StudentXX'
    webex_teams_apis.post_space_message(WEBEX_TEAMS_SPACE_NAME, WEBEX_MESSAGE)
    print()
    print()
    U_USER_INFO = createUmbrellaUser()
    WEBEX_MESSAGE = f'An umbrella user with an email of {U_USER_INFO[0]} has been created with {U_USER_INFO[1]} access successfully by StudentXX'
    webex_teams_apis.post_space_message(WEBEX_TEAMS_SPACE_NAME, WEBEX_MESSAGE)
def webhook():
    if request.method == 'POST':
        print('Webhook Received')
        request_json = request.json

        # print the received notification
        print('Payload: ')
        pprint(request_json)

        # save as a file, create new file if not existing, append to existing file, full details of each notification
        with open('all_webhooks_detailed.log', 'a') as filehandle:
            filehandle.write('%s\n' % json.dumps(request_json))
        try:
            if 'NETWORK-' in request_json[
                    'eventId']:  # this will select the Cisco DNA Center notifications
                dnac_notification = request_json

                # save all info to variables, prepare to save to file
                severity = str(dnac_notification['severity'])
                category = dnac_notification['category']
                timestamp = str(
                    datetime.datetime.fromtimestamp(
                        int(dnac_notification['timestamp'] /
                            1000)).strftime('%Y-%m-%d %H:%M:%S'))
                issue_name = dnac_notification['details'][
                    'Assurance Issue Name']
                issue_description = dnac_notification['details'][
                    'Assurance Issue Details']
                issue_status = dnac_notification['details'][
                    'Assurance Issue Status']
                url = DNAC_URL + '/dna/assurance/issueDetails?issueId=' + dnac_notification[
                    'instanceId']

                # create the summary DNAC log
                new_info = {
                    'severity': severity,
                    'category': category,
                    'timestamp': dnac_notification['timestamp']
                }
                new_info.update({
                    'Assurance Issue Name': issue_name,
                    'Assurance Issue Details': issue_description
                })
                new_info.update({
                    'Assurance Issue Status': issue_status,
                    'Assurance Issue URL': url
                })

                # append, or create, the dnac_webhooks.log - Cisco DNA C summary logs
                with open('dnac_webhooks.log', 'a') as filehandle:
                    filehandle.write('%s\n' % json.dumps(new_info))

                # append, or create, the all_webhooks.log - Summary all logs
                with open('all_webhooks.log', 'a') as filehandle:
                    filehandle.write('%s\n' % json.dumps(new_info))

                # construct the team message
                teams_message = 'Severity:       ' + severity
                teams_message += '\nCategory:       ' + category
                teams_message += '\nTimestamp:      ' + str(timestamp)
                teams_message += '\nIssue Name:     ' + issue_name
                teams_message += '\nIssue Description:  ' + issue_description
                teams_message += '\nIssue Status:   ' + issue_status
                print('New DNAC Webex Teams_Message\n', teams_message)

                teams_message_title = 'Cisco DNA Center Notification'

                # create PagerDuty incident if status is active
                # format message using the Common Event Format (PD-CEF)
                if issue_status != 'resolved':
                    summary = issue_name
                    source = teams_message_title
                    component = issue_description
                    if severity == '1':
                        sev = 'critical'
                    else:
                        sev = 'warning'
                    group = 'Network'
                    # convert time from epoch to iso 8601
                    time_iso = datetime.datetime.fromtimestamp(
                        int(dnac_notification['timestamp'] /
                            1000)).isoformat()
                    pagerduty_apis.trigger_incident(summary, source, component,
                                                    sev, time_iso, group)

                # create Jira Issue
                jira_project = JIRA_PROJECT
                jira_component = '10016'  # Component id for Cisco DNA Center Notification, as created in Jira
                jira_apis.create_customer_issue(jira_project, jira_component,
                                                issue_name, issue_description,
                                                severity, JIRA_EMAIL)

                # post markdown message in teams space, with title of the message
                webex_teams_apis.post_space_markdown_message(
                    WEBEX_TEAMS_ROOM, teams_message_title)

                # post message in teams space
                webex_teams_apis.post_space_message(WEBEX_TEAMS_ROOM,
                                                    teams_message)
                teams_message_url = 'Issue Details:  Click Here\n'

                # post message in teams space, with url for the issue
                webex_teams_apis.post_space_url_message(
                    WEBEX_TEAMS_ROOM, teams_message_url, url)

        finally:
            pass

        try:
            if 'values' in request_json:
                sdwan_notification = request_json

                # save all info to variables, prepare to save to file
                severity = sdwan_notification['severity']
                timestamp = str(
                    datetime.datetime.fromtimestamp(
                        int(sdwan_notification['entry_time'] /
                            1000)).strftime('%Y-%m-%d %H:%M:%S'))
                try:
                    site_id = str(sdwan_notification['values'][0]['site-id'])
                finally:
                    site_id = ' '
                system_ip = sdwan_notification['values'][0]['system-ip']
                host_name = sdwan_notification['values'][0]['host-name']
                message = sdwan_notification['message']
                issue_status = str(sdwan_notification['active'])
                url = SDWAN_URL + '/index.html#/app/monitor/alarms/details/' + sdwan_notification[
                    'uuid']

                # create the summary SD-WAN log - Cisco SD-WAN summary logs
                new_info = {
                    'severity': severity,
                    'entry_time': sdwan_notification['entry_time']
                }
                new_info.update({
                    'site-id': site_id,
                    'system_ip': system_ip,
                    'host-name': host_name
                })
                new_info.update({
                    'message': message,
                    'active': issue_status,
                    'alarm details': url
                })

                # append, or create, the sdwan_webhooks.log
                with open('sdwan_webhooks.log', 'a') as filehandle:
                    filehandle.write('%s\n' % json.dumps(new_info))

                # append, or create, the all_webhooks.log - Summary all logs
                with open('all_webhooks.log', 'a') as filehandle:
                    filehandle.write('%s\n' % json.dumps(new_info))

                # construct the team message
                teams_message = 'Severity:           ' + severity
                teams_message += '\nTimestamp:          ' + timestamp
                teams_message += '\nSite Id:            ' + site_id
                teams_message += '\nSystem IP:          ' + system_ip
                teams_message += '\nHost Name:          ' + host_name
                teams_message += '\nIssue Description:  ' + message
                teams_message += '\nIssue Status:       ' + issue_status
                print('New SD-WAN Webex Teams_Message\n', teams_message)

                teams_message_title = 'Cisco SD-WAN Notification'

                # create PagerDuty incident
                # format message using the Common Event Format (PD-CEF)
                summary = host_name
                source = teams_message_title
                component = message
                if severity == '1':
                    sev = 'critical'
                else:
                    sev = 'warning'
                group = 'WAN'
                # convert time from epoch to iso 8601
                time_iso = datetime.datetime.fromtimestamp(
                    int(sdwan_notification['timestamp'] / 1000)).isoformat()
                pagerduty_apis.trigger_incident(summary, source, component,
                                                sev, time_iso, group)

                # post markdown message in teams space, with title of the message
                webex_teams_apis.post_space_markdown_message(
                    WEBEX_TEAMS_ROOM, teams_message_title)

                # post message in teams space
                webex_teams_apis.post_space_message(WEBEX_TEAMS_ROOM,
                                                    teams_message)

                # post message in teams space, with url for the issue
                teams_message_url = 'Issue Details:  Click Here\n'
                webex_teams_apis.post_space_url_message(
                    WEBEX_TEAMS_ROOM, teams_message_url, url)

        finally:
            pass
        return {'response': 'Notification Received'}, 200
    else:
        abort(400)
                                                    SNOW_DEV, 3)

        # rollback configuration after 5 seconds
        time.sleep(5)
        cli('configure replace flash:/BlitzAdvanced/ios_xe_programmability/base-config force'
            )
        update_comment = "Configuration rollback to baseline successful - IOS XE Automation"
        service_now_apis.update_incident(incident, update_comment, SNOW_DEV)

        # find existing, or create new Webex Teams room

        webex_team_id = webex_teams_apis.get_team_id(WEBEX_TEAMS_SPACE)
        if webex_team_id is None:
            webex_teams_apis.create_space(WEBEX_TEAMS_SPACE)

        webex_teams_apis.post_space_markdown_message(WEBEX_TEAMS_SPACE,
                                                     'New Incident')
        incident_detail = service_now_apis.get_incident_detail(incident)
        webex_teams_apis.post_space_url_message(WEBEX_TEAMS_SPACE, (
            incident_detail["number"]
        ), ("https://dev48476.service-now.com/nav_to.do?uri=incident.do?sys_id="
            + incident_detail["sys_id"]))
        webex_teams_apis.post_space_message(
            WEBEX_TEAMS_SPACE,
            "Description: " + incident_detail["short_description"])
        webex_teams_apis.post_space_message(
            WEBEX_TEAMS_SPACE,
            'Device Hostname: ' + device_name + '   Location: ' + location)

print('End Application Run - Unauthorized Configuration Change')
Esempio n. 6
0
def main():
    """
    Vendor will join Webex Teams Room with the name {ROOM_NAME}
    It will ask for access to an IP-enabled device - named {IPD}
    The code will map this IP-enabled device to the IP address {10.93.140.35}
    Access will be provisioned to allow connectivity from DMZ VDI to IPD
    """

    # save the initial stdout
    initial_sys = sys.stdout

    # the user will be asked if interested to run in demo mode or in
    # production (logging to files - erna_log.log, erna_err.log))

    # user_input = utils.get_input_timeout('If running in Demo Mode please enter y ', 10)

    user_input = 'y'  # remove this line if you want to run in production
    if user_input != 'y':

        # open a log file 'erna.log'
        file_log = open('erna_log.log', 'w')

        # open an error log file 'erna_err.log'
        err_log = open('erna_err.log', 'w')

        # redirect the stdout to file_log and err_log
        sys.stdout = file_log
        sys.stderr = err_log

        # configure basic logging to send to stdout, level DEBUG, include timestamps
        logging.basicConfig(level=logging.DEBUG,
                            stream=sys.stdout,
                            format='%(asctime)s - %(levelname)s - %(message)s')

    # logging, debug level, to file {erna_run.log}
    logging.basicConfig(
        filename='erna_run.log',
        level=logging.DEBUG,
        format=
        '%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S')

    # the local date and time when the code will start execution

    date_time = str(datetime.datetime.now().replace(microsecond=0))
    print('\nThe Application "ERNA.py" started running at this time ' +
          date_time)

    user_input = utils.get_input_timeout('Enter y to skip next section : ', 10)

    user_input = 'y'  # remove this line if you want to follow the approval process

    if user_input != 'y':
        # verify if Webex Teams Space exists, if not create Webex Teams Space, and add membership (optional)

        webex_teams_room_id = webex_teams_apis.get_space_id(ROOM_NAME)
        if webex_teams_room_id is None:
            webex_teams_room_id = webex_teams_apis.create_space(ROOM_NAME)
            print('- ', ROOM_NAME, ' -  Webex Teams room created')

            # invite membership to the room
            webex_teams_apis.add_space_membership(ROOM_NAME, APPROVER_EMAIL)

            webex_teams_apis.post_space_message(
                ROOM_NAME, 'To require access enter :  IPD')
            webex_teams_apis.post_space_message(ROOM_NAME, 'Ready for input!')
            print('Instructions posted in the room')
        else:
            print('- ', ROOM_NAME, ' -  Existing Webex Teams room found')

            webex_teams_apis.post_space_message(
                ROOM_NAME, 'To require access enter :  IPD')
            webex_teams_apis.post_space_message(ROOM_NAME, 'Ready for input!')
        print('- ', ROOM_NAME, ' -  Webex Teams room id: ',
              webex_teams_room_id)

        # check for messages to identify the last message posted and the user's email who posted the message
        # check for the length of time required for access

        last_message = (webex_teams_apis.last_user_message(ROOM_NAME))[0]

        while last_message == 'Ready for input!':
            time.sleep(5)
            last_message = (webex_teams_apis.last_user_message(ROOM_NAME))[0]
            if last_message == 'IPD':
                last_person_email = (
                    webex_teams_apis.last_user_message(ROOM_NAME))[1]
                webex_teams_apis.post_space_message(
                    ROOM_NAME,
                    'How long time do you need access for? (in minutes)  : ')
                time.sleep(10)
                if (
                        webex_teams_apis.last_user_message(ROOM_NAME)
                )[0] == 'How long time do you need access for? (in minutes)  : ':
                    timer = 30 * 60
                else:
                    timer = int(
                        webex_teams_apis.last_user_message(ROOM_NAME)[0]) * 60
            elif last_message != 'Ready for input!':
                webex_teams_apis.post_space_message(ROOM_NAME,
                                                    'I do not understand you')
                webex_teams_apis.post_space_message(
                    ROOM_NAME, 'To require access enter :  IPD')
                webex_teams_apis.post_space_message(ROOM_NAME,
                                                    'Ready for input!')
                last_message = 'Ready for input!'

        print('\nThe user with this email: ', last_person_email,
              ' asked access to IPD for ', (timer / 60), ' minutes')

    # get the WJT Auth token to access DNA
    dnac_token = dnac_apis.get_dnac_jwt_token(DNAC_AUTH)
    print('\nThe DNA Center auth token is: ', dnac_token)

    # IPD IP address - DNS lookup if available

    IPD_IP = '10.93.140.35'
    last_person_email = '*****@*****.**'
    approver_email = '*****@*****.**'
    timer = 3600

    # locate IPD in the environment using DNA C
    ipd_location_info = dnac_apis.locate_client_ip(IPD_IP, dnac_token)

    remote_device_hostname = ipd_location_info[
        0]  # the network device the IPD is connected to
    vlan_number = ipd_location_info[2]  # the access VLAN number
    interface_name = ipd_location_info[
        1]  # the interface number is connected to

    device_location = dnac_apis.get_device_location(
        remote_device_hostname, dnac_token)  # network device location
    location_list_info = device_location.split('/')
    remote_device_location = location_list_info[-1]  # select the building name

    log_ipd_info = '\n\nThe IPD is connected to this device: ' + remote_device_hostname
    log_ipd_info += '\n\nThis interface: ' + interface_name + ', access VLAN: ' + vlan_number
    log_ipd_info += '\n\nLocated       : ' + remote_device_location
    print(log_ipd_info)

    # request approval

    if user_input != 'y':
        webex_teams_apis.post_space_message(
            ROOM_NAME,
            ('The user with this email ' + last_person_email +
             ' asked access to IPD for ' + str(timer / 60) + ' minutes'))
        webex_teams_apis.post_space_message(
            ROOM_NAME,
            'The IPD is connected to the switch ' + remote_device_hostname +
            ' at our location ' + remote_device_location)
        webex_teams_apis.post_space_message(ROOM_NAME, 'To approve enter: Y/N')

        # check for messages to identify the last message posted and the user's email who posted the message.
        # looking for user - Director email address, and message = 'Y'

        last_message = (webex_teams_apis.last_user_message(ROOM_NAME))[0]

        while last_message == 'To approve enter: Y/N':
            time.sleep(5)
            last_message = (webex_teams_apis.last_user_message(ROOM_NAME))[0]
            approver_email = (webex_teams_apis.last_user_message(ROOM_NAME))[1]
            if last_message == 'y' or 'Y':
                if approver_email == APPROVER_EMAIL:
                    print('Access Approved')
                else:
                    last_message = 'To approve enter: Y/N'

        print('\nApproval process completed')

    # get UCSD API key
    # ucsd_key = ucsd_apis.get_ucsd_api_key()

    # execute UCSD workflow to connect VDI to VLAN, power on VDI
    # ucsd_apis.execute_ucsd_workflow(ucsd_key, UCSD_CONNECT_FLOW)

    log_ucsd_info = '\n\nUCSD connect flow executed'
    print(log_ucsd_info)

    # deployment of cli configuration files to the dc router

    dc_device_hostname = 'PDX-RO'
    template_project = 'ERNA'
    print('\nThe DC device name is: ', dc_device_hostname)

    dc_config_file = 'DC_Config.txt'
    dc_config_templ = dc_config_file.split('.')[
        0]  # select the template name from the template file

    cli_file = open(dc_config_file, 'r')  # open file with the template
    cli_config = cli_file.read()  # read the file

    # validation of dc router cli template
    dc_valid = dnac_apis.check_ipv4_duplicate(dc_config_file)
    log_dc_info = ''
    if dc_valid is False:
        print('\n\nDC Router CLI Template validated')
        log_dc_info = '\n\nDC Router CLI Templates validated'

    dnac_apis.upload_template(dc_config_templ, template_project, cli_config,
                              dnac_token)  # upload the template to DNA C
    depl_id_dc = dnac_apis.deploy_template(dc_config_templ, template_project,
                                           dc_device_hostname,
                                           dnac_token)  # deploy dc template

    log_dc_info += '\n\nDeployment of the configurations to the DC router, ' + dc_device_hostname
    log_dc_info += ' started, deployment id: ' + depl_id_dc
    log_dc_config = '\nDC Router Config \n\n' + cli_config
    print(log_dc_info)

    time.sleep(1)

    # deployment of cli configuration files to the remote router

    remote_config_file = 'Remote_Config.txt'
    remote_config_templ = remote_config_file.split('.')[
        0]  # select the template name from the template file

    cli_file = open(remote_config_file, 'r')  # open file with the template
    cli_config = cli_file.read()  # read the file

    # update the template with the localized info for the IPD
    # replace the $VlanId with the localized VLAN access
    # replace the $IPD with the IPD ip address

    cli_config = cli_config.replace('$IPD', IPD_IP)
    cli_config = cli_config.replace('$VlanId', vlan_number)

    remote_updated_config_file = 'Remote_Config_Updated.txt'
    updated_cli_file = open(remote_updated_config_file, 'w')
    updated_cli_file.write(cli_config)
    updated_cli_file.close()

    # validation of remote router cli template
    remote_valid = dnac_apis.check_ipv4_duplicate(remote_updated_config_file)
    log_remote_info = ''
    if remote_valid is False:
        log_remote_info = '\n\nRemote Device CLI Template validated'
        print(log_remote_info)

    dnac_apis.upload_template(remote_config_templ, template_project,
                              cli_config,
                              dnac_token)  # upload the template to DNA C
    depl_id_remote = dnac_apis.deploy_template(
        remote_config_templ, template_project, remote_device_hostname,
        dnac_token)  # deploy remote template
    time.sleep(1)

    log_remote_info += '\n\nDeployment of the configurations to the Remote device, ' + remote_device_hostname
    log_remote_info += ' started, deployment id: ' + depl_id_remote
    log_remote_config = '\nRemote Device Config \n\n' + cli_config
    print(log_remote_info)

    time.sleep(1)

    # check the deployment status after waiting for all jobs to complete - 10 seconds
    print('\nWait for DNA Center to complete template deployments')
    time.sleep(10)

    dc_status = dnac_apis.check_template_deployment_status(
        depl_id_dc, dnac_token)
    remote_status = dnac_apis.check_template_deployment_status(
        depl_id_remote, dnac_token)

    log_templ_depl_info = '\n\nTemplates deployment status DC: ' + dc_status + ', Remote: ' + remote_status
    print(log_templ_depl_info)

    if dc_status == 'SUCCESS' and remote_status == 'SUCCESS':
        print('\nAll templates deployment have been successful\n')
        templ_deploy_status = True

    # synchronization of devices configured - DC and Remote Router
    dc_sync_status = dnac_apis.sync_device(dc_device_hostname, dnac_token)[0]
    remote_sync_status = dnac_apis.sync_device(remote_device_hostname,
                                               dnac_token)[0]

    if dc_sync_status == 202:
        print('\nDNA Center started the DC Router resync')
    if remote_sync_status == 202:
        print('\nDNA Center started the Remote Router resync')

    dc_router_tunnel = netconf_restconf.get_restconf_int_oper_status(
        'Tunnel201')
    remote_router_tunnel = netconf_restconf.get_netconf_int_oper_status(
        'Tunnel201')

    log_tunnel_info = '\n\nThe Tunnel 201 interfaces operational state: '
    log_tunnel_info += '\n\nFrom ' + remote_device_hostname + ' using NETCONF - ' + dc_router_tunnel
    log_tunnel_info += '\n\nFrom ' + dc_device_hostname + ' using RESTCONF - ' + remote_router_tunnel

    print(log_tunnel_info)

    print('\nWait for DNA Center to complete the resync of the two devices')

    time.sleep(180)

    print('\nSync completed, Path Trace started')
    # start a path trace to check the path segmentation
    path_trace_id = dnac_apis.create_path_trace('172.16.202.1', IPD_IP,
                                                dnac_token)

    print('\nWait for Path Trace to complete')
    time.sleep(30)

    path_trace_info = dnac_apis.get_path_trace_info(path_trace_id, dnac_token)

    log_path_trace = '\n\nPath Trace status: ' + path_trace_info[0]
    log_path_trace += '\n\nPath Trace details: ' + str(path_trace_info[1])
    print(log_path_trace)

    # create ASAv outside interface ACL to allow traffic

    outside_acl_id = asav_apis.get_asav_access_list(OUTSIDE_INT)
    asav_status = asav_apis.create_asav_access_list(outside_acl_id,
                                                    OUTSIDE_INT, VDI_IP,
                                                    IPD_IP)
    if asav_status == 201:
        log_asav_info = '\n\nASAv access list updated to allow traffic from ' + VDI_IP + ' to ' + IPD_IP + ' on the interface ' + OUTSIDE_INT
    else:
        log_asav_info = '\n\nError updating the ASAv access list on the interface ' + OUTSIDE_INT
    print(log_asav_info)

    # Webex Teams notification

    webex_teams_apis.post_space_message(
        ROOM_NAME,
        'Requested access to this device: IPD, located in our office: ' +
        remote_device_location + ' by user ' + last_person_email +
        ' has been granted for ' + str(int(timer / 60)) + ' minutes')
    log_access_info = '\n\nRequested access to this device: IPD, located in our office: '
    log_access_info += remote_device_location + ' by user: '******' has been granted for ' + str(
        int(timer / 60)) + ' minutes'

    # create and update ServiceNow incident

    snow_user = '******'
    snow_description = 'ERNA Automation - Vendor Remote Access to IPD: ' + IPD_IP

    snow_incident = service_now_apis.create_incident(snow_description,
                                                     log_ipd_info, snow_user,
                                                     '2')
    comments = log_ucsd_info + log_dc_info + log_dc_config + log_remote_info + log_remote_config + log_templ_depl_info
    comments += log_tunnel_info + log_path_trace + log_asav_info + log_access_info
    service_now_apis.update_incident(snow_incident, comments, snow_user)

    date_time = str(datetime.datetime.now().replace(microsecond=0))
    print('\n\nEnd of application "ERNA.py" provisioning run at this time ',
          date_time)

    # time.sleep(timer)  # un-comment this line if time limit is required
    input('Press any key to continue de-provisioning  ')

    #
    #  restore configurations to initial state
    #

    #  restore DC router config

    dc_rem_file = 'DC_Remove.txt'
    dc_rem_templ = dc_rem_file.split('.')[0]

    cli_file = open(dc_rem_file, 'r')
    cli_config = cli_file.read()

    dnac_apis.upload_template(dc_rem_templ, template_project, cli_config,
                              dnac_token)
    depl_id_dc_rem = dnac_apis.deploy_template(dc_rem_templ, template_project,
                                               dc_device_hostname, dnac_token)

    print('\nDC Router restored to the baseline configuration')
    log_remove_info = '\n\nDC Router restored to the baseline configuration'

    time.sleep(1)

    #  restore Remote router config

    remote_rem_file = 'Remote_Remove.txt'
    remote_rem_templ = remote_rem_file.split('.')[0]

    cli_file = open(remote_rem_file, 'r')
    cli_config = cli_file.read()

    # update the template with the local info for the IPD
    # replace the $VlanId with the local VLAN access
    # replace the $IPD with the IPD ip address

    cli_config = cli_config.replace('$IPD', IPD_IP)
    cli_config = cli_config.replace('$VlanId', vlan_number)

    remote_updated_remove_file = 'Remote_Remove_Updated.txt'
    updated_cli_file = open(remote_updated_remove_file, 'w')
    updated_cli_file.write(cli_config)
    updated_cli_file.close()

    dnac_apis.upload_template(remote_rem_templ, template_project, cli_config,
                              dnac_token)
    depl_id_remote_rem = dnac_apis.deploy_template(remote_rem_templ,
                                                   template_project,
                                                   remote_device_hostname,
                                                   dnac_token)

    print('\nRemote Router restored to the baseline configuration')
    log_remove_info += '\n\nRemote Device restored to the baseline configuration'

    time.sleep(1)

    # remove the ASAv outside interface ACLE that allowed traffic between VDI and IPD

    outside_acl_id = asav_apis.get_asav_access_list(OUTSIDE_INT)
    asav_status = asav_apis.delete_asav_access_list(outside_acl_id,
                                                    OUTSIDE_INT)
    if asav_status == 204:
        log_asav_remove_info = '\n\nASAv access list on the interface ' + OUTSIDE_INT + ' restored to the baseline configuration'
    else:
        log_asav_remove_info = 'Error while restoring the ASAv access list on the interface ' + OUTSIDE_INT
    print(log_asav_remove_info)

    # execute UCSD workflow to disconnect VDI to VLAN, power on VDI
    # ucsd_apis.execute_ucsd_workflow(ucsd_key, UCSD_DISCONNECT_FLOW)

    log_ucsd_remove_info = '\n\nUCSD disconnect flow executed'
    print(log_ucsd_remove_info)

    # sync the remote and DC device
    dc_sync_status = dnac_apis.sync_device(dc_device_hostname, dnac_token)[0]
    remote_sync_status = dnac_apis.sync_device(remote_device_hostname,
                                               dnac_token)[0]

    log_sync_info = ''
    if dc_sync_status == 202:
        log_sync_info = '\n\nDNA Center started the DC Router resync'
    if remote_sync_status == 202:
        log_sync_info += '\n\nDNA Center started the Remote Router resync'

    print(log_sync_info)

    # Webex Teams notification

    webex_teams_apis.post_space_message(
        ROOM_NAME, 'Access to this device: IPD has been terminated')
    webex_teams_apis.post_space_message(
        ROOM_NAME, '----------------------------------------------')

    # update the database with script execution

    access_log_file = open('access_logs.csv', 'a')
    data_to_append = str('\n\n' + date_time) + ','
    access_log_file.write(data_to_append)
    data_to_append = last_person_email + ',' + log_ipd_info + ',' + approver_email
    data_to_append += ',' + log_dc_info + ',' + log_remote_info + ',' + log_templ_depl_info + ','
    data_to_append += log_path_trace + ',' + log_asav_info + ',\n' + snow_incident
    data_to_append_nolines = data_to_append.replace('\n\n', '\n')
    access_log_file.write(data_to_append_nolines)
    access_log_file.close()

    print('\nRecords database updated, file saved')

    comments = log_remove_info + log_asav_remove_info + log_ucsd_remove_info + log_sync_info
    service_now_apis.update_incident(snow_incident, comments, snow_user)

    # restore the stdout to initial value
    sys.stdout = initial_sys

    # the local date and time when the code will end execution

    date_time = str(datetime.datetime.now().replace(microsecond=0))
    print('\n\nEnd of application "ERNA.py" run at this time ', date_time)
Esempio n. 7
0
def main():

    # post message to the new space
    webex_teams_apis.post_space_message('Class Space SRW', 'test message')
    input(
        'Check the space for the new message posted, hit any key to continue ')