gns3api - Simple python module to access the GNS3 API

start_nodes 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #!/usr/bin/env python3
  2. #
  3. # start_nodes - start all nodes of a project
  4. #
  5. # Usage: start_nodes project
  6. #
  7. import sys
  8. import time
  9. import gns3api
  10. def die(*msg_list):
  11. """ abort program with error message """
  12. error_msg = ' '.join(str(x) for x in msg_list)
  13. sys.exit(error_msg.rstrip("\n\r"))
  14. # get command line parameter
  15. if len(sys.argv) == 2:
  16. proj_name = sys.argv[1]
  17. else:
  18. die("Usage: start_nodes project")
  19. # connect to GNS3 controller
  20. try:
  21. api = gns3api.GNS3Api()
  22. except (IOError, OSError, gns3api.GNS3BaseException) as err:
  23. die("Can't connect to GNS3 controller:", err)
  24. # search for the project
  25. project = None
  26. for project in api.request('GET', '/v2/projects'):
  27. if project['name'] == proj_name:
  28. break
  29. else:
  30. die("Project '{}' not found".format(proj_name))
  31. if project['status'] != 'opened':
  32. api.request("POST", ("/v2/projects", project['project_id'], 'open'))
  33. # start nodes
  34. all_nodes = api.request('GET', ('/v2/projects', project['project_id'], 'nodes'))
  35. for node in sorted(all_nodes, key=lambda k: k['name'].lower()):
  36. if node['status'] == 'started':
  37. continue
  38. time.sleep(3)
  39. while True:
  40. compute = api.request('GET', ('/v2/computes', node['compute_id']))
  41. if compute['cpu_usage_percent'] < 60.0:
  42. break
  43. time.sleep(10)
  44. print("Starting '{}'".format(node['name']))
  45. try:
  46. api.request("POST", ("/v2/projects", project['project_id'], 'nodes', node['node_id'], 'start'))
  47. except (IOError, OSError) as err:
  48. die(err)