Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- """
- System Monitoring Statistics via Ubidots
- This script sends CPU, Memory, and Disk Usage statistics to Ubidots for
- visualization and insights. This script is cross platform and will work on
- Windows, Linux, and OS X.
- The data source in Ubidots is named after the system"s hostname, and will
- be created if it does not exist. The disk usage statistic corresponds to
- the first mounted physical partiton and the CPU usage statistics is
- the average over all CPU's.
- """
- __author__ = "Daniel da Silva"
- from socket import gethostname
- from sys import argv
- import psutil
- import ubidots
- def get_var_by_name(var_name, ds):
- """Search for a variable in a datasource. If found, returns the variable.
- If not found, returns None."""
- for var in ds.get_variables():
- if var.name == var_name:
- return var
- return None
- def main():
- """Main routine for the script."""
- if len(argv) != 2:
- print "Usage: %s API_KEY" % argv[0]
- return
- api = ubidots.ApiClient(argv[1])
- # Search for a data source with name matching this the desired
- # name of our datasource. If it doesn"t exist, create it.
- hostname = gethostname() + " Monitor"
- ds = None
- for cur_ds in api.get_datasources():
- if cur_ds.name == hostname:
- ds = cur_ds
- break
- if ds is None:
- ds = api.create_datasource({"name": hostname})
- # Search for variables in the data source with names matching
- # the ones we will update. If they don"t exist, create them.
- var_cpu = get_var_by_name("cpu_percent", ds)
- var_mem = get_var_by_name("mem_percent", ds)
- var_disk = get_var_by_name("disk_percent", ds)
- if var_cpu is None:
- var_cpu = ds.create_variable({"name": "cpu_percent", "unit": "%"})
- if var_mem is None:
- var_mem = ds.create_variable({"name": "mem_percent", "unit": "%"})
- if var_disk is None:
- var_disk = ds.create_variable({"name": "disk_percent", "unit": "%"})
- # Utilize the psutil module to send values to Ubidots.
- var_cpu.save_value({"value": psutil.cpu_percent(interval=1)})
- var_mem.save_value({"value": psutil.virtual_memory().percent})
- var_disk.save_value({"value": psutil.disk_usage(psutil.disk_partitions(all=False)[0].mountpoint).percent})
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement