gns3api - Simple python module to access the GNS3 API

get_console 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #!/usr/bin/env python3
  2. #
  3. # get_console - get console port of GNS3 node
  4. #
  5. # Usage: get_console [project] node
  6. #
  7. import sys
  8. import gns3api
  9. def die(*msg_list):
  10. """ abort program with error message """
  11. error_msg = ' '.join(str(x) for x in msg_list)
  12. sys.exit(error_msg.rstrip("\n\r"))
  13. # get command line parameter
  14. if len(sys.argv) == 2:
  15. proj_name = None
  16. node_name = sys.argv[1]
  17. elif len(sys.argv) == 3:
  18. proj_name = sys.argv[1]
  19. node_name = sys.argv[2]
  20. else:
  21. die("Usage: get_console [project] node")
  22. # connect to GNS3 controller
  23. try:
  24. api = gns3api.GNS3Api()
  25. except (IOError, OSError) as err:
  26. die("Can't connect to GNS3 controller:", err)
  27. # search for the project
  28. project = None
  29. if proj_name is None: # search for the only open project
  30. for proj in api.request('GET', '/v2/projects'):
  31. if proj['status'] == 'opened':
  32. if project is None:
  33. project = proj
  34. else:
  35. die("Multiple projects active, set project as first param")
  36. if project is None:
  37. die("No project is open")
  38. else: # search for proj_name
  39. for proj in api.request('GET', '/v2/projects'):
  40. if proj['name'] == proj_name:
  41. if proj['status'] != 'opened':
  42. die("Project '{}' not open".format(proj_name))
  43. project = proj
  44. break
  45. if project is None:
  46. die("Project '{}' not found".format(proj_name))
  47. # search for node_name
  48. node = None
  49. for node in api.request('GET', ('/v2/projects', project['project_id'], 'nodes')):
  50. if node['name'] == node_name:
  51. break
  52. else:
  53. die("Node '{}' not found in project '{}'".format(node_name, project['name']))
  54. if node['status'] != 'started':
  55. die("Node '{}' is {}".format(node_name, node['status']))
  56. # print console host and port
  57. console_port = node['console']
  58. if console_port is None:
  59. die("Node '{}' doesn't use the console".format(node_name))
  60. console_host = node['console_host']
  61. if console_host == '0.0.0.0' or console_host == '::':
  62. compute = api.request('GET', ('/v2/computes', node['compute_id']))
  63. console_host = compute['host']
  64. print("{} {}".format(console_host, console_port))