Пример #1
0
def main():
    #Variable assignments
    assignmentgroup = "AutomationQ"
    user = "******"
    passwd = "tcs#1234"
    instance_name = "dev99449"

    #Creating the conneciton to Service now
    connection = connect_servicenow(user, passwd, instance_name)
    #Connection the incident instance on Service now
    incident_Connection = ServiceNow.Incident(connection)
    # Create Conneciton to Group instance
    group_conneciton = ServiceNow.Group(connection)
    # fetch the details of Group AutomationQ
    group_con = ServiceNow.Group.fetch_all(group_conneciton,
                                           {"name": "AutomationQ"})
    # Get the sys_id for AutomationQ, which is need to get the list of instance in AutomationQ
    group_sid = group_con['records'][0]['sys_id']
    fetch_incident = ServiceNow.Incident.fetch_all(incident_Connection, {
        "assignment_group": group_sid,
        "state": 1
    })
    for i in range(0, len(fetch_incident['records'])):
        if len(fetch_incident['records'][i]['description'].split(",")) > 2:
            print(fetch_incident['records'][i]['description'].split(",")[2])
Пример #2
0
def main():
    #Variable assignments
    assignmentgroup = sys.argv[1]
    user = "******"
    passwd = "tcs#1234"
    instance_name = "dev99449"
    description = sys.argv[2]
    detail = sys.argv[3]

    #Creating the conneciton to Service now
    connection = connect_servicenow(user, passwd, instance_name)
    #Connection the incident instance on Service now
    incident_Connection = ServiceNow.Incident(connection)
    group_conneciton = ServiceNow.Group(connection)
    new_incident = ServiceNow.Incident.create(incident_Connection,{"short_description":description,"description":detail,"priority":"3","u_requestor":"autoalert","u_contact_type":"Auto Monitoring","assignment_group": assignmentgroup})
    message = f'Incident # {new_incident} has been Created'
    log_service_now(message)
Пример #3
0
class TestSequenceFunctions(unittest.TestCase):
    conn = Connection.Auth(username=username,
                           password=password,
                           instance=instance,
                           api='JSONv2')
    inc = ServiceNow.Incident(conn)
    incident = {}

    def test_00_insert(self):
        global incident
        createdinc = self.inc.create({
            'short_description': 'automated test',
            'description': 'automated test'
        })
        self.assertTrue('number' in createdinc['records'][0])
        incident = createdinc['records'][0]

    def test_02_update(self):
        global incident
        text = 'updated'
        updated = self.inc.update({'number': incident['number']},
                                  {'short_description': 'updated'})
        self.assertEqual(text, updated['records'][0]['short_description'])
        incident = updated['records'][0]

    def test_02_fetch_one(self):
        global incident
        self.assertEqual(self.inc.fetch_one({'number': incident['number']}),
                         incident)

    def test_03_fetch_all(self):
        global incident
        self.assertEqual(
            self.inc.fetch_all({'number': incident['number']})['records'][0],
            incident)

    def test_04_delete(self):
        global incident
        deleted = self.inc.delete(incident['sys_id'])
        self.assertEqual(incident, deleted['records'][0])
Пример #4
0
#               rubrik_cdm module (pip install rubrik_cdm)
#               servicenow module (pip install servicenow)
#               Rubrik CDM 5.0.2+
#               Environment variables for RUBRIK_IP (IP of Rubrik node), RUBRIK_USER (Rubrik username), RUBRIK_PASS (Rubrik password)

from servicenow import ServiceNow
from servicenow import Connection
import rubrik_cdm

conn = Connection.Auth(username='******',
                       password='******',
                       instance='dev99999',
                       api='JSONv2')

rubrik = rubrik_cdm.Connect()
inc = ServiceNow.Incident(conn)

table_payload = {
    "dataSource": "FrequentDataSource",
    "reportTableRequest": {
        "sortBy": "ObjectName",
        "sortOrder": "asc",
        "requestFilters": {
            "compliance24HourStatus": "NonCompliance"
        },
        "limit": 1000
    }
}

events = rubrik.post('internal', '/report/data_source/table', table_payload)
Пример #5
0
def main():

    # Process Command Line Parameters
    parser = argparse.ArgumentParser(
             description='Create a CMDB Server Record in ServiceNow. ',
             epilog='')
    parser.add_argument("-l", "--sn_location", dest="sn_location", default='ALL', required=False)
    parser.add_argument("-u", "--sn_user", dest="sn_user", required=True)
    parser.add_argument("-p", "--sn_pass", dest="sn_pass", required=True)
    parser.add_argument("-i", "--sn_instance", dest="sn_instance", required=True)
    parser.add_argument("-k", "--cmdb_key", dest="cmdb_key", required=True)
    # cmdb record is variable and passed on the command line as a json string
    parser.add_argument("-r", "--cmdb_record", dest="cmdb_record", type=json.loads, required=False)
    # -c to add -d to delete
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('-c', '--create', default=False, action='store_true')
    group.add_argument('-d', '--delete', default=False, action='store_true')

    args = parser.parse_args()

    sn_instance = args.sn_instance
    sn_user = args.sn_user
    sn_pass = args.sn_pass
    sn_location = args.sn_location

    # Get connection object
    cmdb_conn = get_connection(sn_location, sn_instance, sn_user, sn_pass)

    #Get Server Object
    cmdb_server = ServiceNow.Server(cmdb_conn)

    #if not cmdb_server.list({'name': args.cmdb_key}):
    #  sys.stderr.write('cmdb_server: Error Connecting to CMDB.')
    #  exit(1)

    # Process Request
    if args.create:

        cmdb_record = args.cmdb_record
        cmdb_key = args.cmdb_key

        print 'Create CMDB Server Record....'
        print 'SN Instance: ' + args.sn_instance
        print 'SN User: '******'SN Pass: '******'*****'
        print 'CMDB Record Key: ' + cmdb_key
        print 'CMDB Record'

        cmdb_record = args.cmdb_record
        for key in cmdb_record:
            print '    ' + key + ': ' + cmdb_record[key]

        response = create_cmdb(cmdb_server, cmdb_key, cmdb_record)

    elif args.delete:

        cmdb_key = args.cmdb_key

        print 'Delete CMDB Server Record....'
        print 'SN Instance: ' + args.sn_instance
        print 'SN User: '******'SN Pass: '******'*****'
        print 'CMDB Record Key: ' + cmdb_key

        response = delete_cmdb(cmdb_server, cmdb_key)

    if response:
        exit(0)
    else:
        exit(1)
Пример #6
0
 def _out(conn):
     custom = ServiceNow.Base(conn)
     custom.__table__ = custom_table
     return custom
Пример #7
0
def main():

    parser = argparse.ArgumentParser(
        description='Python utility to test ServiceNow API')
    parser.add_argument('--servicenow_hostname',
                        help='DNS resolvable hostname or IP address')
    parser.add_argument('--servicenow_username', help='ServiceNow username')
    parser.add_argument('--servicenow_password', help='ServiceNow password')
    args = parser.parse_args()

    if args.servicenow_hostname == None:
        print(
            "No hostname was specified. Use --servicenow_hostname argument to provide a hostname. Exiting ..."
        )
    if args.servicenow_username == None:
        print(
            "No username was specified. Use --servicenow_username argument to provide a username. Exiting ..."
        )

    servicenow_password = args.servicenow_password
    if servicenow_password == None or servicenow_password == "":
        servicenow_password = getpass.getpass

    print("ServiceNow")
    try:
        servicenow = ServiceNow(args.servicenow_hostname,
                                args.servicenow_username,
                                args.servicenow_password)
    except:
        raise

    #print("Getting a list of tables from ServiceNow")
    #tables = servicenow._get_from_table('sys_db_object')
    #for table in tables[:10]:
    #	if 'name' in table:
    #		print(table['name'])

    print("Getting all CIs from ServiceNow")
    parameters = []
    parameters.append({'name': 'sysparm_display_value', 'value': 'all'})

    cis = servicenow.get_configuration_items(parameters=parameters)
    ci_count = len(cis)
    print(f"There are {ci_count} CIs in ServiceNow.")

    include_filters = [{'name': 'category', 'value': 'Hardware'}]
    exclude_filters = []
    filtered_cis = filter_cis(cis, include_filters=include_filters)

    first_data_list = []
    for filtered_ci in filtered_cis:
        data = {}
        data['name'] = filtered_ci['name']
        data['sys_class_name'] = filtered_ci['sys_class_name']
        data['location'] = filtered_ci['location']
        data['ip_address'] = filtered_ci['ip_address']
        data['sys_id'] = filtered_ci['sys_id']
        data['operational_status'] = filtered_ci['operational_status']
        data['vendor'] = filtered_ci['vendor']
        data['model_id'] = filtered_ci['model_id']
        data['monitor'] = filtered_ci['monitor']
        first_data_list.append(data)
    print(first_data_list)

    #second_data_list = []
    #for filtered_ci in filtered_cis:
    #	# Get a series of information about the CI
    #	fields = []
    #	# Name
    #	fields.append('name')
    #	# Class
    #	fields.append('sys_class_name')
    #	# Location
    #	fields.append('location')
    #	# IP Address
    #	fields.append('ip_address')
    #	# CI ID
    #	fields.append('sys_id')
    #	# CI Status
    #	fields.append('operational_status')
    #	# Manufacturer
    #	fields.append('vendor')
    #	# Model
    #	fields.append('model_id')
    #	# Monitor
    #	fields.append('monitor')
    #	# Monitored Type
    #	fields.append('type')
    #
    #	sys_id = filtered_ci['sys_id']
    #	if 'value' in sys_id:
    #		sys_id = sys_id['value']
    #	#data = servicenow.get_configuration_item_data(sys_id, fields, display_value=True)
    #
    #	second_data_list.append(data)
    #print(second_data_list)

    locations = servicenow.get_locations()
    if locations != None:
        location_count = len(locations)
        print(
            f"There are {location_count} locations in the ServiceNow instance."
        )

    return
from servicenow import ServiceNow as sn


# EXAMPLE USE OF SERVICENOW TAGS SYNC
# Set the request parameters
# This script is limiting the search to one host. This is for a demo.
instance = "---"
url = 'https://{}.service-now.com'.format(instance)

# Set proper headers
headers = {"Content-Type":"application/json","Accept":"application/json"}

# Eg. User name="username", Password="******" for this code sample.
user = '******'
pwd = '---'

# Datadog API & APP Keys
api_key = '---'
app_key = '---'

# Hostname that is shared between a servicenow registered server & Datadog
hostname = "lnux100"

sn.updateTags(hostname,sn.attributes(sn.findSysId(url, user, pwd, headers)), api_key, app_key)