-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathget_instance_info
executable file
·146 lines (116 loc) · 4.46 KB
/
get_instance_info
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Import system libs
import os
import re
import sys
import argparse
import logging
import urllib2
from logging.handlers import RotatingFileHandler
try:
import simplejson as json
except ImportError:
import json
# PY3?
is_py3 = sys.version_info >= (3, 3)
script = os.path.basename(sys.argv[0])
scriptname = os.path.splitext(script)[0]
DEFAULT_LOG = "/var/log/" + scriptname
LOG = logging.getLogger(scriptname)
API_URL = "http://xxxxxxx.xxxx/info.php"
RET_OK = 0
RET_FAILED = 1
RET_INVALID_ARGS = 2
IP_PATTERN = re.compile(r"""
\b((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}
(2[0-4]\d|25[0-5]|[01]?\d\d?)\b""", re.VERBOSE)
def error_exit(msg, status=1):
LOG.error('%s\n' % msg)
sys.exit(status)
def setup_logging(logfile=DEFAULT_LOG, max_bytes=None, backup_count=None):
"""Sets up logging and associated handlers."""
LOG.setLevel(logging.INFO)
if backup_count is not None and max_bytes is not None:
assert backup_count > 0
assert max_bytes > 0
ch = RotatingFileHandler(logfile, 'a', max_bytes, backup_count)
else: # Setup stream handler.
ch = logging.StreamHandler(sys.stdout)
ch.setFormatter(logging.Formatter('%(asctime)s %(name)s[%(process)d] '
'%(levelname)s: %(message)s'))
LOG.addHandler(ch)
def parse_argument():
parser = argparse.ArgumentParser()
parser.add_argument('-v', '--version', action = 'version',
version = '%(prog)s 1.0'
)
parser.add_argument('--max-bytes', action = 'store', dest = 'max_bytes',
type = int, default = 64 * 1024 * 1024,
help = 'Maximum bytes per a logfile.')
parser.add_argument('--backup-count', action = 'store',
dest = 'backup_count', type = int, default = 0,
help='Maximum number of logfiles to backup.')
parser.add_argument('--logfile', action = 'store', dest='logfile',
type = str, default = DEFAULT_LOG,
help = 'Filename where logs are written to.')
parser.add_argument('name_or_ip', nargs = 1,
help='''host name or ip for query, ip for exact match.''')
#nargs: ? for 0 or one. + for 1 or more. * 0 for or more.
parser.add_argument('--host', action = 'store_false', default = True,
dest = 'host', help = 'Set display hostname to false.' )
options = parser.parse_args()
return parser, options
def get_info_name(hostname, display):
url = API_URL + "?hostname=" + hostname
if display:
url = url + "?display=true"
LOG.debug("get data from url: %s" % url)
try:
data = urllib2.urlopen(url).read()
LOG.debug("get data is: %s" % data)
jstr = json.loads(data)
if jstr["success"]:
print json.dumps(jstr, sort_keys=True, indent=4, separators=(',', ': '),\
ensure_ascii=False, encoding='utf-8').encode("gb2312")
else:
print jstr["message"]
except Exception, e:
LOG.error("Have a problem %s", str(e))
print "Query infomation failed use hostname: %s." % hostname
def get_info_ip(ip):
url = API_URL + "?ip=" + ip
LOG.debug("get data from url: %s" % url)
try:
data = urllib2.urlopen(url).read()
LOG.debug("get data is: %s" % data)
jstr = json.loads(data)
if jstr["success"]:
print json.dumps(jstr, sort_keys=True, indent=4, separators=(',', ': '),\
ensure_ascii=False, encoding='utf-8').encode("gb2312")
else:
print jstr["message"]
except Exception, e:
LOG.error("Have a problem %s", str(e))
print "Query infomation failed use ip: %s." % ip
################# main route ######################
if __name__ == '__main__':
parser, options = parse_argument()
setup_logging(options.logfile, options.max_bytes or None,
options.backup_count or None)
#LOG.setLevel(logging.DEBUG)
name_or_ip = vars(options)["name_or_ip"]
name_or_ip = name_or_ip[0].strip()
LOG.debug("name_or_ip value is:" + str(vars(options)))
if name_or_ip.strip() == "":
parser.print_help()
sys.exit(RET_INVALID_ARGS)
try:
m = IP_PATTERN.match(name_or_ip)
if m:
get_info_ip(name_or_ip)
else:
get_info_name(name_or_ip, options.host)
except TypeError:
get_info_name(name_or_ip)