InstanceID.py 1.1 KB

123456789101112131415161718192021222324252627282930
  1. #!/usr/bin/env python
  2. #coding=utf-8
  3. from pprint import pprint
  4. import json
  5. from config import Config
  6. from word_generater import decodestr
  7. from aliyunsdkcore.client import AcsClient
  8. from aliyunsdkcore.acs_exception.exceptions import ClientException
  9. from aliyunsdkcore.acs_exception.exceptions import ServerException
  10. from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest
  11. def privateIP2InstanceID(ip,region):
  12. d = {}
  13. client = AcsClient(decodestr(Config.accessKeyId), decodestr(Config.accessSecret), region)
  14. request = DescribeInstancesRequest()
  15. request.set_accept_format('json')
  16. request.set_PrivateIpAddresses([ip])
  17. response = client.do_action_with_exception(request)
  18. result = json.loads(str(response, encoding='utf-8'))
  19. eipinfo = result['Instances']["Instance"][0].get('EipAddress')
  20. if eipinfo:
  21. d['eipid'] = eipinfo['AllocationId']
  22. d['instanceid'] = result['Instances']["Instance"][0]["InstanceId"]
  23. return d
  24. if __name__ == "__main__":
  25. #print(privateIP2InstanceID("172.18.135.107"))
  26. print(privateIP2InstanceID("172.16.181.135","cn-hangzhou"))