def _construct_client(self): # If instance is not defined in the config, host is required. If both are defined, instance # takes precedence. with self._session as _session: _session.auth = requests.auth.HTTPBasicAuth( self._username, self._password) return (pysnow.Client(instance=self._instance, session=_session) if self._instance else pysnow.Client(host=self._host, session=_session))
def snow_get(key, instance=None, username=None, password=None, table=None, lookup_field=None, result_fields=None): if not HAS_PYSNOW: raise AnsibleError("Service-Now lookup requires pysnow to be installed") value = [] if instance is None: raise AnsibleError("Service-Now: No instance specified") if username is None: raise AnsibleError("Service-Now: No username specified") if password is None: raise AnsibleError("Service-Now: No password specified") if table is None: raise AnsibleError("Service-Now: No table specified") if lookup_field is None: raise AnsibleError("Service-Now: No lookup_field specified") try: conn = pysnow.Client(instance=instance, user=username, password=password) except Exception as detail: raise AnsibleError("Could not connect to ServiceNow: {0}".format(str(detail))) try: record = conn.query(table=table, query={lookup_field: key}) for res in record.get_multiple(fields=result_fields): if len(result_fields) == 1: # we have single field results, make a simpler list value.append(res[result_fields[0]]) else: value.append(res) except pysnow.exceptions.NoResults: return ['ENOENT'] except Exception as detail: raise AnsibleError("Unknown failure in query record: {0}".format(str(detail))) return value
def login(self): result = dict( changed=False ) if self.params['client_id'] is not None: try: self.conn = pysnow.OAuthClient(client_id=self.client_id, client_secret=self.client_secret, token_updater=self.updater, instance=self.instance) except Exception as detail: self.module.fail_json(msg='Could not connect to ServiceNow: {0}'.format(str(detail)), **result) if not self.session['token']: # No previous token exists, Generate new. try: self.session['token'] = self.conn.generate_token(self.username, self.password) except pysnow.exceptions.TokenCreateError as detail: self.module.fail_json(msg='Unable to generate a new token: {0}'.format(str(detail)), **result) self.conn.set_token(self.session['token']) elif self.username is not None: try: self.conn = pysnow.Client(instance=self.instance, user=self.username, password=self.password) except Exception as detail: self.module.fail_json(msg='Could not connect to ServiceNow: {0}'.format(str(detail)), **result) else: snow_error = "Must specify username/password. Also client_id/client_secret if using OAuth." self.module.fail_json(msg=snow_error, **result)
def set_ServiceNow_Connection(self): try: self.connection = pysnow.Client(user=self.username, password=self.passwd, instance=self.instance_name) except: print("Issue in Conneciting Servicenow")
def setUp(self): # Mock client configuration self.mock_connection = { 'instance': 'mock_instance', 'user': '******', 'pass': '******', 'raise_on_empty': False } self.mock_connection[ 'fqdn'] = "%s.service-now.com" % self.mock_connection['instance'] # Mock incident attributes self.mock_incident = { 'path': 'api/now/table/incident', 'number': 'INC01234', 'sys_id': '98ace1a537ea2a00cf5c9c9953990e19', 'link_arg': '?page=2' } self.client = pysnow.Client( instance=self.mock_connection['instance'], user=self.mock_connection['user'], password=self.mock_connection['pass'], raise_on_empty=self.mock_connection['raise_on_empty']) logging.basicConfig(level=logging.DEBUG) self.log = logging.getLogger('debug')
def googleCreateList(userName): # Create client object c = pysnow.Client(instance='dev34640', user='******', password='******') # Define a resource, here we'll use the incident table API incident = c.resource(api_path='/table/incident') result = incident.get( query={'caller_id': '6033415bdb021300ea6e5c00cf961963'}) print('User name for ' + str(result)) allUserInc = None count = 0 for record in result.all(): incNumber = record['number'] shortDescription = record['short_description'] incState = record['state'] print(incNumber) print(incState) while count != 5: print(incNumber) print(incState) if (allUserInc != None): allUserInc += ',' + googleResList(incNumber) elif (allUserInc == None): allUserInc = googleResList(incNumber) print(count) count += 1 print("All user inc/s are " + str(allUserInc)) lser = JsonService('googlelist', str(allUserInc)) print('iNSIDE' + str(lser)) print('iNSIDE1' + str(lser.jsonRestStr)) print('iNSIDE2' + str(lser.jsonRichResMsg)) return lser
def CommentsUpdation(InstanceName, SnowUserName, SnowPassWord, SnowSysId, CommentsOutput, AlertStatus): try: SnowAuthenication = pysnow.Client(instance=InstanceName, user=SnowUserName, password=SnowPassWord) IncidentList = SnowAuthenication.resource(api_path='/table/incident') response = IncidentList.get(query={'sys_id': SnowSysId}) response.update({'comments': CommentsOutput}) response.update({'assignment_group': 'DES Windows Operations'}) response.update({'assigned_to': 'Autobots'}) if AlertStatus: response.update({'incident_state': 'Resolved'}) response.update({'u_sub_state': 'With Workaround'}) response.update({'close_code': 'Positive Alarm (Action taken)'}) response.update( {'u_close_code_subcategory': 'Infrastructure Issue'}) response.update({'close_notes': 'Resolved by Auobots'}) logger.info( "\n" + "Message : Script Execution is Successful.Incident State is Resolved..!" ) else: response.update({'incident_state': 'Awaiting Assignment'}) response.update({'assigned_to': ''}) logger.info( "\n" + "Message : Script Execution is Successful.Incident State is Awaiting Assignment..!" ) except Exception as e: print "Message : " + str(e)
def needits(): """Return all needits.""" data = request.form text = data['text'] s = pysnow.Client(instance=SN_INSTANCE_URL, user=SN_USERNAME, password=SN_PASSWORD) needits = s.resource(api_path='/table/x_58872_needit_needit') needit = needits.get(query={'number': text}).one_or_none() msg = { "blocks": [{ "type": "section", "text": { "type": "mrkdwn", "text": ('*Incident Found.*' if needit else '*No records found.*') } }, { "type": "actions", "elements": [{ "type": "button", "text": { "type": "plain_text", "text": "Create Ticket", "emoji": False } }] }] } return jsonify(msg), 200
def setUp(self): # Mock client configuration self.mock_connection = { 'instance': 'mock_instance', 'user': '******', 'pass': '******', 'raise_on_empty': False } self.mock_connection[ 'fqdn'] = "%s.service-now.com" % self.mock_connection['instance'] # Mock incident attributes self.mock_incident = { 'path': 'api/now/table/incident', 'number': 'INC01234', 'sys_id': '98ace1a537ea2a00cf5c9c9953990e19', 'link_arg': '?page=2' } # Mock attachment attributes self.mock_attachment = { 'path': 'api/now/attachment/upload', 'sys_id': 'b39fb9c1db0032000062f34ebf96198b', 'file_name': 'example.txt', } self.client = pysnow.Client( instance=self.mock_connection['instance'], user=self.mock_connection['user'], password=self.mock_connection['pass'], raise_on_empty=self.mock_connection['raise_on_empty']) # Use `nosetests -l debug` to enable this logger logging.basicConfig(level=logging.DEBUG) self.log = logging.getLogger('debug')
def NonR2ServerCommentsUpdation(InstanceName, SnowUserName, SnowPassWord, SnowSysId): try: CommentsOutput = '''Autobots unable to connect to JEA (ADSK_Autobot) end point. This may be due to: 1) Target Server runs Windows Server 2008/2003. (JEA feature is not available on these OS) 2) If Server OS is Windows Server 2008 R2 onwards, run the following command to check if the JEA endpoint exists. Get-PSSessionConfigurtion -Name ADSK_Autobot''' SnowAuthenication = pysnow.Client(instance=InstanceName, user=SnowUserName, password=SnowPassWord) IncidentList = SnowAuthenication.resource(api_path='/table/incident') response = IncidentList.get(query={'sys_id': SnowSysId}) Payload = { 'comments': CommentsOutput, 'assignment_group': 'DES Windows Operations', 'assigned_to': 'Autobots', 'incident_state': 'New', 'assigned_to': '' } response.update(Payload) logging.warning("Message : JEA is not configured.") except Exception as e: print "Message : " + str(e)
def check_servicenow_connection(self, connection_string, user_name, password): try: pysnow.Client(instance=connection_string, user=user_name, password=password) except Exception as ex: return False return True
def createTicket(userId, assignedToId, reason, username, passwd): # Create client object c = pysnow.Client(instance=config.servicenow['instance'], user=username, password=passwd) # Define a resource, here we'll use the incident table API incident = c.resource(api_path='/table/incident') # Set the payload new_record = { 'caller_id': '%s' % userId, 'assignment_group': config.assignment_group['assign_id'], 'assigned_to': '%s' % assignedToId, 'short_description': '%s' % reason, 'contact_type': 'Walk-in', 'u_internal': 'true', 'category': 'Inquiry / Help', 'impact': '2', 'urgency': '2', 'u_preferred_language': 'en', 'u_business_service': config.u_business_service['bus_id'], 'location': config.location['loc_id'] } # Create a new incident record result = incident.create(payload=new_record) return result
def test_client_request_params(self): httpretty.register_uri( httpretty.GET, "http://%s/%s" % (self.mock_connection['host'], self.mock_incident['path']), body=json.dumps({'result': ''}), status=200, content_type="application/json") client = pysnow.Client( instance=self.mock_connection['instance'], user=self.mock_connection['user'], password=self.mock_connection['pass'], raise_on_empty=self.mock_connection['raise_on_empty'], use_ssl=False, request_params={ 'foo1': 'bar1', 'foo2': 'bar2' }) r = client.query(table='incident', query={}) r.get_one() # Parse QS and make sure `request_params` actually ended up in the request qs_str = r.last_response.url.split("?")[1] qs = dict( (x[0], x[1]) for x in [x.split("=") for x in qs_str.split("&")]) self.assertEqual(qs['foo1'], 'bar1') self.assertEqual(qs['foo2'], 'bar2')
def get_sn_client(current_user: AuthInfo): sn_config = get_sn_config(current_user) sn_client = pysnow.Client(user=sn_config.user, password=sn_config.password, host=sn_config.host) return sn_client
def _get_client(self, default_payload=None): instance_name = self.config['instance_name'] username = self.config['username'] password = self.config['password'] if not default_payload and 'default_payload' in self.config: default_payload = self.config['default_payload'] return sn.Client(instance_name, username, password, default_payload=default_payload)
def setUp(self): self.client = pysnow.Client(instance="test", user="******", password="******") r = self.resource = self.client.resource(api_path=mock_api_path) a = self.attachment_base_url = r._base_url + r._base_path + "/attachment" self.attachment_url_binary = a + "/file" self.attachment_url_multipart = a + "/upload" self.attachment_url_sys_id = a + "/" + mock_sys_id
def setUp(self): self.client = pysnow.Client(instance='test', user='******', password='******') r = self.resource = self.client.resource(api_path=mock_api_path) a = self.attachment_base_url = r._base_url + r._base_path + '/attachment' self.attachment_url_binary = a + '/file' self.attachment_url_multipart = a + '/upload' self.attachment_url_sys_id = a + '/' + mock_sys_id
def work(self): '''Main application logic''' # 11 fields short_description = self._module.params['short_description'] assignment_group = self._module.params['assignment_group'] remediation = self._module.params['remediation'] serviceName = self._module.params['serviceName'] server = self._module.params['server'] host = self._module.params['host'] user = self._module.params['user'] password = self._module.params['password'] requestor = self._module.params['requestor'] assigned_to = self._module.params['assigned_to'] escalation_group = self._module.params['escalation_group'] # Create client object # 3 inputs used c = pysnow.Client(host=host, user=user, password=password) c.parameters.display_value = True c.parameters.exclude_reference_link = True incident = c.resource(api_path='/table/incident') description_pieces = [] # 4 composite fields description_pieces.append("Server=" + server) description_pieces.append("Remediation=" + remediation) description_pieces.append("ServiceName=" + serviceName) description_pieces.append("EscalationGroup=" + escalation_group) description = "~".join(description_pieces) # "requestor in GUI, caller_id in data model caller_id = requestor # Set the payload # 4 individual fields # 1 composite field of 4 inputs # 3 individual fields used to create the connection (above) # 11 fields total new_record = { 'caller_id': caller_id, #'assigned_to': assigned_to, 'short_description': short_description, 'description': description, 'assignment_group': assignment_group } result = None try: result = incident.create(payload=new_record) except Exception as e: self._module.fail_json(msg="Query failure: ({0})".format(e)) return json.dumps(result.one(), indent=2)
def _auth_basic(self): try: self.connection = pysnow.Client(instance=self.instance, host=self.host, user=self.username, password=self.password, raise_on_empty=self.raise_on_empty) except Exception as detail: self.fail( msg='Could not connect to ServiceNow: {0}'.format(str(detail)))
def servicenow(computer_hostname, computer_ip, computer_domain, computer_workgroup, computer_os): ''' Function is checking if there is already ticket for device if now create new one. If ticket is resolve it will reopen it if device is still vulnerable ''' pysnow_c = pysnow.Client(instance=SN_INSTANCES, user=SN_USERNAME, password=SN_PASSWORD) # First checking if there is already ticket for that hostname incident = pysnow_c.resource(api_path='/table/incident') query_pysnow = 'problem_id='+CONFIG['nmap']['problem_id']+'^short_descriptionLIKE '+computer_hostname+' ^ORdescriptionLIKE '+computer_hostname+' ' response = incident.get(query=query_pysnow) short_describtion = "Vulnerability for WannaCry for IP: "+computer_ip+" , Computer Name: "+computer_hostname +" , Domain or workgoup: "+computer_domain+computer_workgroup+" , OS :"+computer_os describtion = "Computer is vulnerable. " new_record = { 'short_description': short_describtion, 'description': describtion, 'assignment_group':CONFIG['nmap']['assignment_group'], 'caller_id': CONFIG['nmap']['caller_id'], 'category': CONFIG['nmap']['category'], 'priority':'3 - Moderate', 'problem_id': CONFIG['nmap']['problem_nb']} flag_closed = False flag_reopen = False flag_active = False # Create new one or reopen old one if response.all(): for respons in response.all(): if respons['state'] == "6": flag_reopen = True reopen_ticket = respons['number'] elif respons['state'] == "7": flag_closed = True else: flag_active = True ticket_number = respons['number'] print(respons['state']+" "+respons['number']) if not flag_active and flag_reopen: pysnow_query = pysnow_c.query(table='incident', query={'number': reopen_ticket}) ticket_number = reopen_ticket result = pysnow_query.update({'work_notes': 'Host still vulnerable please patch again and clean', 'close_code': '', 'state': '2'}) print("Ticket "+result['number']+" state was successfully changed to "+result['state']) elif not flag_active and flag_closed: result = incident.create(payload=new_record) print("Ticket already closed new ticket createt "+result['number']) ticket_number = result['number'] else: result = incident.create(payload=new_record) print("New ticket createt "+result['number']) ticket_number = result['number'] return ticket_number
def _get_client(self): instance_name = self.config['instance_name'] username = self.config['username'] password = self.config['password'] client = sn.Client(instance=instance_name, user=username, password=password) if 'custom_params' in self.config and isinstance(self.config['custom_params'], dict): client.parameters.add_custom(self.config['custom_params']) return client
def _auth_token(self): try: s = requests.Session() s.auth = HTTPBearerAuth(self.token) self.connection = pysnow.Client(instance=self.instance, host=self.host, session=s, raise_on_empty=self.raise_on_empty) except Exception as detail: self.fail( msg='Could not connect to ServiceNow: {0}'.format(str(detail)))
def run_module(): # define the available arguments/parameters that a user can pass to # the module module_args = dict(instance=dict(default=None, type='str', required=True), username=dict(default=None, type='str', required=True, no_log=True), password=dict(default=None, type='str', required=True, no_log=True), table=dict(type='str', required=False, default='incident'), number=dict(default=None, type='str', required=True), return_fields=dict(default=None, type='list', required=False)) module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) # check for pysnow if not HAS_PYSNOW: module.fail_json(msg='pysnow module required') result = dict( changed=False, instance=module.params['instance'], table=module.params['table'], number=module.params['number'], ) # do the lookup try: conn = pysnow.Client(instance=module.params['instance'], user=module.params['username'], password=module.params['password']) except: module.fail_json(msg='Could not connect to ServiceNow', **result) try: record = conn.query(table=module.params['table'], query={'number': module.params['number']}) if module.params['return_fields'] is None: res = record.get_one() else: res = record.get_one(module.params['return_fields']) result['record'] = res except: module.fail_json(msg='Failed to find record', **result) module.exit_json(**result)
def conecta_bd(sistema): import psycopg2 import cx_Oracle import pyodbc import pysnow #Fazer as conexões com o Postgress if sistema == 'X': # Connect to an existing database database_f = 'data_base_nome' user_f = 'seu user' password_f = 'sua senha' host_f = 'seu host' port_f = '5432' #Connect ORACLE SERVER elif sistema == 'Y': conexao = 'user/senha@host:1521/database' elif sistema == 'Z': # Connect to servicenow API user_f = 'user' password_f = 'senha' host_f = 'instancia' elif sistema == 'W': #Connect Microsoft SQL Server conexao = ('DRIVER=' + '{SQL Server}' + ';PORT=1433;SERVER=' + 'xxxx.xxxxxx.database.windows.net' + ';PORT=1443;DATABASE=' + 'Instancia' + ';UID=' + 'user' + ';PWD=' + 'senha') else: print('input de sistema errado') if sistema in ['X']: conn = psycopg2.connect(database=database_f, user=user_f, password=password_f, host=host_f, port=port_f) if sistema in ['Z']: conn = pysnow.Client(user=user_f, password=password_f, instance=host_f) if sistema in ['W']: conn = pyodbc.connect(conexao) else: conn = cx_Oracle.connect(conexao) return (conn)
def getactivecitasks(ci): c = pysnow.Client(instance=theconfig['snowinstance'], user=theconfig['snowusername'], password=theconfig['snowpassword']) changetasks = c.resource(api_path='/table/task_ci') qb = ( pysnow.QueryBuilder() .field('ci_item.sys_id').equals(ci) .AND() .field('task.sys_class_name').equals('change_request') .AND() .field('task.state').equals('4') ) response = changetasks.get(query=qb, fields=['sys_id','task.number', 'ci_item']) return response.all()
def authenticate_snow(): is_snow_authenticate = False try: logger.info("Authenticating user credentials to access ServiceNow") authenticate_snow.snowUserPassword = base64.b64decode(snowUserPassword).decode('utf-8') global snow_incident snow_connection = pysnow.Client(instance=snowInstance, user=snowUserName, password=authenticate_snow.snowUserPassword) # Define a resource, here we'll use the incident table API snow_incident = snow_connection.resource(api_path='/table/incident') is_snow_authenticate = True except Exception as ex: logger.error("Exception occurred while authenticating ServiceNow " + str(ex)) return is_snow_authenticate
def test_invalid_default_payload(self): """ Make sure passing an invalid payload doesn't work """ try: pysnow.Client( instance=self.mock_connection['instance'], user=self.mock_connection['user'], password=self.mock_connection['pass'], raise_on_empty=self.mock_connection['raise_on_empty'], default_payload='invalid payload') except pysnow.InvalidUsage: pass
def connect(): """ Connect to ServiceNow with credentials from the configuration file. Returns the pysnow client object directly. """ global snow snow = pysnow.Client(instance=config['servicenow']['instance'], user=config['servicenow']['username'], password=config['servicenow']['password']) print("connected to instance: " + snow.instance) return snow
def getAllIncidentsOlderThan(username, passwd, daysago): today = datetime.today() days_ago_time = today - timedelta(days=int(daysago)) # Create client object c = pysnow.Client(instance=config.servicenow['instance'], user=username, password=passwd, use_ssl=False) # Define a resource, here we'll use the incident table API incident = c.resource(api_path='/table/incident') qb = pysnow.QueryBuilder().field('assignment_group').equals('').OR().field( 'assignment_group').equals('6230ba480f872500d7f84b9ce1050ec7').AND( ).field('assigned_to').is_empty().AND().field('active').equals( 'true').AND().field('state').not_equals('6').AND().field( 'sys_created_on').less_than(days_ago_time) # Query for incidents with state 1 response = incident.get(query=qb, limit=50, stream=True, fields=[ 'sys_id', 'opened_at', 'assignment_group', 'number', 'state', 'assigned_to', 'short_description', 'caller_id', 'contact_type', 'priority', 'subcategory', 'u_kick_back_counter' ]) x = PrettyTable() x.field_names = [ 'Number', 'Caller', 'Description', 'Category', 'Assignment Group', 'Opened At' ] # Iterate over the result and print out `sys_id` of the matching records. for record in response.all(): x.add_row([ record['number'], getUser(c, record), record['short_description'], record['subcategory'], getGroup(c, record), record['opened_at'] ]) x.sortby = "Opened At" x.reversesort = True return x
def run(self): '''Main logic routine''' host = self.url user = self.username pwd = self.password api = self.api_path # Create ServiceNow client object c = pysnow.Client(host=host, user=user, password=pwd) c.parameters.display_value = True c.parameters.exclude_reference_link = True cmdb = c.resource(api_path=api) # Query qb = ( pysnow.QueryBuilder() .field('subcategory').contains('Windows Server') .AND() .field('u_status').equals('Deployed') .AND() .field('host_name').order_ascending() ) try: response = cmdb.get(query=qb) except pysnow.exceptions.ResponseError as e: sys.stderr.write(str(e)) sys.exit(EXIT_FAILURE) # Map SNOW record to something more convenient results = [ ] for record_raw in response.all(): record_refined = { "u_ci_id":record_raw['u_ci_id'], "classification":record_raw['classification'], "sys_class_name":record_raw['sys_class_name'], "u_technicalinfraapproval":record_raw['u_technicalinfraapproval'], "u_ccbapprover":record_raw['u_ccbapprover'], "host_name":record_raw['host_name'], "sys_domain":record_raw['sys_domain'], "category":record_raw['category'], "sys_class_name":record_raw['sys_class_name'], "fqdn":record_raw['fqdn'], "ip_address":record_raw['ip_address'], "os":record_raw['os'], "name":record_raw['name'], "company":record_raw['company'] } self.all_records = results