Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

In this worked example, we will produce the same CSV file output as in the first PowerShell worked example

...

The requests module handles the HTTP details for us.

Code Block
languagepy
titleConnect to host
import requests

r = requests.get('http://vm-mike-2012b/api/v1/devices',auth=('admin','password'))
max = r.headers['X-fetch-count']
data = r.json()
count = len(data)

By default the REST API "/api/v1/devices" page will return 200 devices at a time. We can increase or decrease this using the "fetch_size" parameter. The variable max contains the total number of devices. If this is more than 200 we would need to fetch a second batch - see other worked examples in this series for more details on that. In this example we will print at most 200. data holds the RestAPI data converted into a Python data structure, count is the number of devices returned.

Step Two - print out Hostname, RAM and CPU details for each device

Code Block
languagepy
titleFind the hostname
i = 0
print ('Host,RAM,CPU Type')
while (i < count):
  row = data[i]
  if ( 'host_name' in row ):
    hostname = row['host_name']
  else:
    hostname = '(no hostname)'
	

...

For each device, we get the host_name (which can be empty) and the self (which is always set) values.  'self' contains a URL pointing to detailed information on the device which we then fetch to get the RAM and CPU information.

Code Block
languagepy
titleFind the rest of the details
  url2 = row['self']
  r2 = requests.get(url2,auth=('admin','password'))
  device = r2.json()
  if ('total_memory_mb' in device):
    ram = device['total_memory_mb']
  else:
    ram = '(unknown ram)'

  if ('cpu' in device):
    
    cpu = device['cpu'][0]['cpu_model']
  else:
    cpu = '(unknown cpu)'

  # remove commas from the cpu string
  cpu = cpu.replace(',','')
  print (hostname,',',ram,',',cpu,sep='')
  i+=1

...

 Completed Code

Code Block
languagepy
titleCompleted Script
collapsetrue
#
# RestAPI duplicate the PowerShell example in Python
#
import requests
# Set this to your own host name/login/password)
r = requests.get('http://vm-mike-2012b/api/v1/devices',auth=('admin','password'))
max = r.headers['X-fetch-count']
data = r.json()
count = len(data)
i = 0
print ('Host,RAM,CPU Type')
while (i < count):
  row = data[i]
  if ( 'host_name' in row ):
    hostname = row['host_name']
  else:
    hostname = '(no hostname)'
	
  url2 = row['self']
  r2 = requests.get(url2,auth=('admin','password'))
  device = r2.json()
  if ('total_memory_mb' in device):
    ram = device['total_memory_mb']
  else:
    ram = '(unknown ram)'

  if ('cpu' in device):
    
    cpu = device['cpu'][0]['cpu_model']
  else:
    cpu = '(unknown cpu)'

  # remove commas from the cpu string
  cpu = cpu.replace(',','')
  print (hostname,',',ram,',',cpu,sep='')
  i+=1

...