Sunday, January 19, 2020

Bulk download attachments ServiceNow


Below Script can be used to bulk download attachments from ServiceNow.

import requests
import os
import concurrent.futures
import json

tasks =[]

def make_folder(folder):
folder = f"data/{folder}"
if not os.path.exists(folder):
os.makedirs(folder)

uri = "https://instance.service-now.com"
api = "/api/now/table/"
header = {'Content-Type': 'application/json'}


def write_to_file(file_name, r):
with open(file_name, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
f.flush()
os.fsync(f.fileno())

def process_attachment(obj):
attachment = obj['attachment']
attachment_sys_id = attachment['sys_id']
attachment_file_api = f"{uri}/api/now/attachment/{attachment_sys_id}/file"
binary_response = requests.get(attachment_file_api, **options)
write_to_file(f"data/{obj['number']}/{attachment['file_name']}",
binary_response)


def process_tasks(tasks):
jobs = []
with concurrent.futures.ThreadPoolExecutor(max_workers=40) as executor:
for task in tasks:
jobs.append(executor.submit(process_attachment, task))

for job in concurrent.futures.as_completed(jobs):
print(job.result())

def prepare_options():
user_name = "username"
password = "pwd"
options = {
'headers': {'Content-Type': 'application/json',
},
'auth': (user_name, password),
'timeout' : 50
}
return options
tables = ['incident']
options = prepare_options()
for table in tables:
url = f"{uri}/{api}/{table}"
response = requests.get(url, **options)
response = response.json()
response = response['result']
for record in response:
sys_id = record['sys_id']
numbr = record['number']
attachment_meta_api = f"{uri}/api/now/attachment?sysparm_query={table}
^table_sys_id={sys_id}"
a_response = requests.get(attachment_meta_api, **options)
a_response = a_response.json()
attachments = a_response['result']
if len(attachments):
make_folder(record['number'])

for attachment in attachments:
obj = {
'attachment': attachment,
'number': numbr,
'options': options
}
tasks.append(obj)

process_tasks(tasks)






The above python 3 script downloads attachments into local machine  stores them into data folder.

Inputs:


  1.  Tables  = List of task related tables that you want to download attachments from.
  2.  URI =  Instance URI
  3. userName = userName to access the instance.
  4. password = pwd to access the instance
Ensure provided user has read access to the task table. 







No comments:

Post a Comment

Most common interview questions and answers

 1. Tell me about yourself? This is [Your name] ,   I am a  specialist/expert in [your area] with [no of years]  experience and the [so and...