awins.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. import boto3
  2. from time import sleep
  3. import subprocess
  4. client = boto3.client('ec2', region_name='ap-south-1')
  5. import os
  6. current_path = os.path.dirname(os.path.dirname(__file__))
  7. def get_instance_id():
  8. if not os.path.exists(os.path.join(current_path,'instance_file.txt')):
  9. with open(os.path.join(current_path,'instance_file.txt'),'w') as f:
  10. instance_info = input('Enter Instance Name/Number : ')
  11. f.write(instance_info)
  12. else:
  13. with open(os.path.join(current_path,'instance_file.txt'),'r') as f:
  14. instance_info = f.readline()
  15. instance_info = instance_info.strip()
  16. return instance_info
  17. def get_public_ip(instance_id = None):
  18. if instance_id is None:
  19. l_instance_id= []
  20. input_instance_id = get_instance_id()
  21. l_instance_id.append(input_instance_id)
  22. else:
  23. l_instance_id= []
  24. l_instance_id.append(instance_id)
  25. response = client.describe_instances(InstanceIds=l_instance_id)
  26. res_data = response['Reservations'][0]
  27. instances = res_data['Instances']
  28. status_name = instances[0]['State']['Name']
  29. status_code = instances[0]['State']['Code']
  30. if status_code == 16:
  31. public_ip = instances[0]['PublicIpAddress']
  32. else:
  33. public_ip = 'notfound'
  34. return public_ip
  35. def start_instance(instance_id = None):
  36. if instance_id is None:
  37. l_instance_id= []
  38. input_instance_id = get_instance_id()
  39. l_instance_id.append(input_instance_id)
  40. else:
  41. l_instance_id= []
  42. l_instance_id.append(instance_id)
  43. ins_state = get_instance_status(instance_id=instance_id)
  44. if (ins_state == 'RUNNING'):
  45. public_ip = get_public_ip()
  46. #logging.debug(f'Instance running at : {public_ip}')
  47. return public_ip
  48. elif(ins_state == 'INITIALIZING'):
  49. while (not ins_state == 'RUNNING') or (not ins_state == 'RUNNING') :
  50. # logging.debug("System Already Initialized , waiting to close or start")
  51. if(ins_state == 'RUNNING'):
  52. public_ip = get_public_ip()
  53. # logging.debug(f'Instance running at : {public_ip}')
  54. return public_ip
  55. try:
  56. client.start_instances(InstanceIds=l_instance_id)
  57. except Exception:
  58. #logging.debug('could not start instance, try again')
  59. return 'could not start instance, try again'
  60. ins_state = get_instance_status(instance_id=instance_id)
  61. while not (ins_state == 'RUNNING'):
  62. ins_state = get_instance_status(instance_id=instance_id)
  63. sleep(20)
  64. return get_public_ip()
  65. def stop_instance(instance_id = None):
  66. if instance_id is None:
  67. l_instance_id= []
  68. input_instance_id = get_instance_id()
  69. l_instance_id.append(input_instance_id)
  70. else:
  71. l_instance_id= []
  72. l_instance_id.append(instance_id)
  73. client.stop_instances(InstanceIds=l_instance_id)
  74. ins_state = get_instance_status(instance_id=instance_id)
  75. while not (ins_state == 'STOPPED'):
  76. ins_state = get_instance_status(instance_id=instance_id)
  77. sleep(10)
  78. return 'STOPPED'
  79. def get_instance_status(instance_id = None):
  80. if instance_id is None:
  81. l_instance_id = []
  82. input_instance_id = get_instance_id()
  83. l_instance_id.append(input_instance_id)
  84. else:
  85. l_instance_id= []
  86. l_instance_id.append(instance_id)
  87. InstanceState = None
  88. tanceStatus_reachability = None
  89. tanceStatus_status = None
  90. SystemStatus_reachablity = None
  91. SystemStatus_status = None
  92. dict_resp = client.describe_instance_status(InstanceIds=l_instance_id)
  93. try:
  94. all_status = dict_resp['InstanceStatuses'][0]
  95. InstanceState = all_status['InstanceState']['Name'] #should be running
  96. tanceStatus_reachability = all_status['InstanceStatus']['Details'][0]['Status'] #should be passed
  97. tanceStatus_status = all_status['InstanceStatus']['Status'] #should be ok
  98. SystemStatus_reachablity = all_status['SystemStatus']['Details'][0]['Status'] #should be passed
  99. SystemStatus_status = all_status['SystemStatus']['Status'] #should be ok
  100. print(f'Instance State :{InstanceState}')
  101. print(f'Instance Reachiblity :{tanceStatus_reachability}')
  102. print(f'Instance Status :{tanceStatus_status}')
  103. print(f'System Status :{SystemStatus_status}')
  104. print(f'System Reachiblity :{SystemStatus_status}')
  105. if (InstanceState == 'running' and
  106. tanceStatus_reachability == 'passed' and
  107. tanceStatus_status == 'ok'and
  108. SystemStatus_reachablity == 'passed' and
  109. SystemStatus_status=='ok') :
  110. return 'RUNNING'
  111. else:
  112. return 'INITIALIZING'
  113. except Exception:
  114. tanceStatus_reachability = 'not found' #should be passed
  115. tanceStatus_status = 'not found' #should be ok
  116. SystemStatus_reachablity = 'not found' #should be passed
  117. SystemStatus_status = 'not found' #should be ok
  118. print(f'Instance State :{InstanceState}')
  119. print(f'Instance Reachiblity :{tanceStatus_reachability}')
  120. print(f'Instance Status :{tanceStatus_status}')
  121. print(f'System Status :{SystemStatus_status}')
  122. print(f'System Reachiblity :{SystemStatus_status}')
  123. return 'STOPPED'
  124. def connect_rdp():
  125. public_ip = start_instance()
  126. if public_ip == 'notfound':
  127. print("Something Wrong, can't get public IP")
  128. else:
  129. aws_ip = f'/v:{public_ip}'
  130. subprocess.run(['mstsc',aws_ip])
  131. print("launched rdp")
  132. if __name__ == "__main__":
  133. #print(stop_instance())
  134. #print(start_instance())
  135. #print(get_instance_id())
  136. get_instance_status()
  137. #get_public_ip()
  138. #connect_rdp()