def get_item(self, beanstr, key, port): """ java -jar cmdline-jmxclient-0.10.3.jar - localhost:12345 java.lang:type=Memory NonHeapMemoryUsage 参数: """ pre_key = key sub_key = None if "." in key: pos = str(key).rfind(".") pre_key = key[0:pos] sub_key = key[pos+1:] lst_beanstr = self._parse_beanstr(beanstr) cmdstr = "%s -jar %s - localhost:%s '%s' '%s'" % (self._java_path, self._cmdclient_jar, port, lst_beanstr, pre_key) c2 = cmds(cmdstr, timeout=3) stdo = c2.stdo() stde = c2.stde() retcode = c2.code() (stdo_list, stde_list) = (re.split("\n", stdo), re.split("\n", stde)) logdict = { "beanstr": beanstr, "lst_beanstr": lst_beanstr, "key": key, "cmdstr": cmdstr, "stdo": stdo, "stde": stde, "retcode": retcode, "orders": ["beanstr", "lst_beanstr", "key", "cmdstr", "stdo", "stde", "retcode"], } if retcode !=0: self._logger.dictlog(width=8, level="error", **logdict) return else: self._logger.dictlog(width=8, level="info", **logdict) if stde_list: stdo_list.extend(stde_list) ## without sub attr if not sub_key and stdo_list: line = stdo_list[-1] ln_ary = re.split(" ", line) if ln_ary and len(ln_ary) >= 2: if pre_key in ln_ary[-2]: return ln_ary[-1] #print stdo_list,"###" ## with sub attr for line in stdo_list: line = str(line).strip() ln_ary = re.split(":", line) if ln_ary and len(ln_ary) != 2:continue dst_key = str(ln_ary[0]).strip() dst_val = str(ln_ary[1]).strip() if sub_key == dst_key: return dst_val return None
def get_mysql_cmd_output(self, cmdstr, hostname=None, username=None, password=None, port=None): try: hostname = hostname if hostname else self._iphost username = username if username else self._username passwd = password if password else self._password port = port if port else self._port bp = which("mysql") binpaths = [ bp, "/data0/mysql/product/bin/mysql", ] mysql_bp = None for p in binpaths: if os.path.isfile(p): mysql_path = p break if not mysql_path: return sql_cmdstr = '%s -h%s -P%s -u%s -p%s -e "%s"' % ( mysql_path, hostname, port, username, passwd, cmdstr) c2 = cmds(sql_cmdstr, timeout=2) stdo = c2.stdo() stde = c2.stde() retcode = c2.code() logdict = { #"cmdstr": cmdstr, "cmdstr": sql_cmdstr, "stdo": stdo, "stde": stde, "retcode": retcode, "orders": ["cmdstr", "stdo", "stde", "retcode"], } if retcode != 0: self._logger.dictlog(width=8, level="error", **logdict) return None else: self._logger.dictlog(width=8, level="info", **logdict) output_list = re.split("[\n]+", str(stdo).strip()) content = dict() for line in output_list: line = str(line).strip().replace(" ", "").strip("|").lower() line_ary = re.split(r"[\s]+", line) if len(line_ary) < 2: continue if content.has_key(line_ary[0]): pass content[line_ary[0]] = line_ary[1] return content except Exception as expt: import traceback tb = traceback.format_exc() self._logger.error(tb)
def _get_jmx_port_list(self): cmdstr = "ps -ef | grep 'jmxremote.port='| grep -v grep 2>/dev/null" plst = [] c2 = cmds(cmdstr, timeout=3) stdo = c2.stdo() stde = c2.stde() retcode = c2.code() (stdo_list, stde_list) = (re.split("\n", stdo), re.split("\n", stde)) logdict = { "cmdstr": cmdstr, "stdo": stdo, "stde": stde, "retcode": retcode, "orders": ["cmdstr", "stdo", "stde", "retcode"], } if retcode !=0: self._logger.dictlog(width=8, level="error", **logdict) return else: self._logger.dictlog(width=8, level="info", **logdict) data = list() for line in stdo_list: if not line or str(line).strip() == "": continue line = str(line).strip() ln_ary = re.split("[\s]+", line) runuser=ln_ary[0] pid = ln_ary[1] gcs = [] jmxport = None pattern=r'\-XX\:\+Use(\w+)GC' for field in ln_ary: if "jmxremote.port=" in field: jmxport = str(field).split("jmxremote.port=")[1] m = re.match(pattern, field) if m: gcs.append(m.group(1)) if not gcs: confitem = { "{#PID}": int(pid), "{#RUNUSER}": runuser, } if jmxport:confitem["{#JVMPORT}"] = int(jmxport) confitem["{#GC}"] = "Parallel" data.append(confitem) else: for gc in gcs: confitem = { "{#PID}": int(pid), "{#RUNUSER}": runuser, } if jmxport:confitem["{#JVMPORT}"] = int(jmxport) confitem["{#GC}"] = gc or "Parallel" data.append(confitem) return data
def _get_result(self, iphost=None, port=None, username=None, password=None): try: hostname = iphost if iphost else self._iphost port = port if port else self._port username = username if username else self._username password = password if password else self._password resobj = None binpt = which("mongo") pbinpaths = [ binpt, "/usr/local/mongodb/bin/mongo", "/home/albert/mongodb/mongodb-3.0.0/bin/mongo", ] cmdstr = None for bp in pbinpaths: if not bp: continue if not os.path.exists(bp): continue cmdstr = "echo 'db.serverStatus()' | %s admin --host '%s' --port %s --quiet" % ( bp, hostname, port) if username and password: cmdstr = "echo 'db.serverStatus()' | %s admin --host '%s' --port %s -u '%s' -p '%s' --quiet" % ( bp, hostname, port, username, password) break if not cmdstr: return None c2 = cmds(cmdstr, timeout=3) stdo = c2.stdo() stde = c2.stde() retcode = c2.code() logdict = { "cmdstr": cmdstr, "stdo": stdo, "stde": stde, "retcode": retcode, "orders": ["cmdstr", "stdo", "stde", "retcode"], } if retcode != 0: self._logger.dictlog(width=8, level="error", **logdict) return else: self._logger.dictlog(width=8, level="info", **logdict) stdo_str = stdo stdo_str = stdo_str.replace("NumberLong(", "").replace( ")", "").replace("ISODate(", "").replace("ObjectId(", "") #print stdo_str resobj = json.loads(stdo_str) return resobj except Exception as expt: import traceback tb = traceback.format_exc() self._logger.error(tb)
def get_port_list(self): # sudo权限,必须授予 # [root@localhost ~]# tail -n 2 /etc/sudoers # Defaults:zabbix !requiretty # zabbix ALL=(root) NOPASSWD:/bin/netstat binname = "mongod" cmdstr = "sudo netstat -nlpt | grep '%s' | awk '{print $4}' | awk -F: '{print $2}'" % (binname) c2 = cmds(cmdstr, timeout=3) stdo = c2.stdo() stde = c2.stde() retcode = c2.code() (stdo_list, stde_list) = (re.split("\n", stdo), re.split("\n", stde)) logdict = { "cmdstr": cmdstr, "stdo": stdo, "stde": stde, "retcode": retcode, "orders": ["cmdstr", "stdo", "stde", "retcode"], } if retcode !=0: self._logger.dictlog(width=8, level="error", **logdict) return else: self._logger.dictlog(width=8, level="info", **logdict) data = list() for port in stdo_list: port = int(str(port).strip()) data.append({"{#MONGODB_PORT}": port}) import json return json.dumps({'data': data}, sort_keys=True, indent=7, separators=(",",":"))
def get_pd_detail(slot, drive, parameter): cmdstr = "sudo /usr/sbin/hpssacli controller slot={} physicaldrive all show detail|grep -i -A 21 'physicaldrive {}'|grep -i '{}'".format(slot, drive, parameter) c2 = cmds(cmdstr, timeout=5) stdo = c2.stdo() stde = c2.stde() (stdo_list, stde_list) = (re.split("\n", stdo), re.split("\n", stde)) return stdo_list[0].split(':')[-1].strip()
def get_mysql_cmd_output(self, hostname=None, username=None, password=None, port=None): try: hostname = hostname if hostname else self._iphost username = username if username else self._username passwd = password if password else self._password port = port if port else self._port sys_binpath = which("mysqladmin") ## 适配编译安装,这里设置常用的路径 binpaths = [ sys_binpath, "/usr/bin/mysqladmin", "/data/mysql/product/bin/mysqladmin" ] cmdstr = None command = "extended-status" for p in binpaths: if not p or os.path.exists(p) == False: continue cmdstr = "%s -h%s -P%s -u'%s' -p'%s' %s" % ( p, hostname, port, username, passwd, command) if not cmdstr: return None c2 = cmds(cmdstr, timeout=3) stdo = c2.stdo() stde = c2.stde() retcode = c2.code() logdict = { "cmdstr": cmdstr, "stdo": stdo, "stde": stde, "retcode": retcode, "orders": ["cmdstr", "stdo", "stde", "retcode"], } if retcode != 0: self._logger.dictlog(width=8, level="error", **logdict) return None else: self._logger.dictlog(width=8, level="info", **logdict) output_list = re.split("[\n]+", str(stdo).strip()) content = dict() for line in output_list: line = str(line).strip().replace(" ", "").lower().strip("|") line_ary = re.split("\|", line) if len(line_ary) < 2: continue content[line_ary[0]] = line_ary[1] return content except Exception as expt: import traceback tb = traceback.format_exc() self._logger.error(tb)
def get_mysql_cmd_output(self, cmdstr, hostname=None, username=None, password=None, port=None): try: hostname = hostname if hostname else self._iphost username = username if username else self._username passwd = password if password else self._password port = port if port else self._port bp = which("mysql") mysql_path = bp if bp else "/usr/local/bin/mysql" # 自编译mysql请修改此路径或自行添加PATH变量 if not (os.path.isfile(mysql_path) and os.access(mysql_path, os.X_OK)): exit("No mysql client found.") sql_cmdstr = '%s -h%s -P%s -u"%s" -p"%s" -e "%s"' % ( mysql_path, hostname, port, username, passwd, cmdstr) c2 = cmds(sql_cmdstr, timeout=2) stdo = c2.stdo() stde = c2.stde() retcode = c2.code() logdict = { # "cmdstr": cmdstr, "cmdstr": sql_cmdstr, "stdo": stdo, "stde": stde, "retcode": retcode, "orders": ["cmdstr", "stdo", "stde", "retcode"], } if retcode != 0: self._logger.dictlog(width=8, level="error", **logdict) return None else: self._logger.dictlog(width=8, level="info", **logdict) output_list = re.split("[\n]+", str(stdo).strip()) content = dict() # 将命令行返回的内容解析成字典 for line in output_list: line = str(line).strip().replace(" ", "").strip("|").lower() # line_ary = re.split(r"[\s]+", line) line_ary = re.split(r"[\s|\||:|;|,]+", line) if len(line_ary) < 2: continue if line_ary[0] in content: pass content[line_ary[0]] = line_ary[1] return content except Exception as expt: import traceback tb = traceback.format_exc() self._logger.error(tb)
def get_mysql_cmd_output(self, cmdstr, hostname=None,username=None,password=None,port=None): try: hostname= hostname if hostname else self._iphost username = username if username else self._username passwd = password if password else self._password port = port if port else self._port bp = which("mysql") binpaths = [ bp, "/data0/mysql/product/bin/mysql", ] mysql_bp = None for p in binpaths: if os.path.isfile(p): mysql_path = p break if not mysql_path: return sql_cmdstr = '%s -h%s -P%s -u%s -p%s -e "%s"' % (mysql_path,hostname,port,username,passwd, cmdstr) c2 = cmds(sql_cmdstr, timeout=2) stdo = c2.stdo() stde = c2.stde() retcode = c2.code() logdict = { #"cmdstr": cmdstr, "cmdstr": sql_cmdstr, "stdo": stdo, "stde": stde, "retcode": retcode, "orders": ["cmdstr", "stdo", "stde", "retcode"], } if retcode !=0: self._logger.dictlog(width=8, level="error", **logdict) return None else: self._logger.dictlog(width=8, level="info", **logdict) output_list = re.split("[\n]+", str(stdo).strip()) content = dict() for line in output_list: line = str(line).strip().replace(" ", "").strip("|").lower() #line_ary = re.split(r"[\s]+", line) line_ary = re.split(r"[\s|\||:|;|,]+", line) if len(line_ary) < 2:continue if content.has_key(line_ary[0]): pass content[line_ary[0]] = line_ary[1] return content except Exception as expt: import traceback tb = traceback.format_exc() self._logger.error(tb)
def get_res_set(self, key, port=None, password=None): port = port if port else self._port password = password if password else self._password rds_cli_path = which("redis-cli") ## 适配编译安装,这里设置常用的路径 rds_paths_def = [ "/usr/bin/redis-cli", "/bin/redis-cli", "/usr/local/redis-server/bin/redis-cli" ] cmdstr = None if rds_cli_path: cmdstr = "%s -h 127.0.0.1 -p %s info" % (rds_cli_path, port) if password: cmdstr = "%s -h 127.0.0.1 -a %s -p %s info" % (rds_cli_path, password, port) else: for p in rds_paths_def: if os.path.exists(p) == False: continue cmdstr = "%s -h 127.0.0.1 -p %s info" % (p, port) if password: cmdstr = "%s -h 127.0.0.1 -a %s -p %s info" % (p, password, port) break c2 = cmds(cmdstr, timeout=3) stdo = c2.stdo() stde = c2.stde() retcode = c2.code() (stdo_list, stde_list) = (re.split("\n", stdo), re.split("\n", stde)) logdict = { "cmdstr": cmdstr, "stdo": stdo, "stde": stde, "retcode": retcode, "orders": ["cmdstr", "stdo", "stde", "retcode"], } if retcode != 0: self._logger.dictlog(width=8, level="error", **logdict) return else: #self._logger.dictlog(width=8, level="info", **logdict) pass resobj = {} for line in stdo_list: line = str(line).strip() ln_ary = re.split(":", line) if ln_ary and len(ln_ary) != 2: continue dst_key = str(ln_ary[0]).strip() dst_val = str(ln_ary[1]).strip() resobj[dst_key] = dst_val return resobj
def _get_result(self, iphost=None, port=None, username=None, password=None): try: hostname= iphost if iphost else self._iphost port = port if port else self._port username = username if username else self._username password = password if password else self._password resobj = None binpt = which("mongo") pbinpaths = [ binpt, "/usr/local/mongodb/bin/mongo", "/home/albert/mongodb/mongodb-3.0.0/bin/mongo", ] cmdstr = None for bp in pbinpaths: if not bp:continue if not os.path.exists(bp): continue cmdstr = "echo 'db.serverStatus()' | %s admin --host '%s' --port %s --quiet" % (bp, hostname, port) if username and password: cmdstr = "echo 'db.serverStatus()' | %s admin --host '%s' --port %s -u '%s' -p '%s' --quiet" % (bp, hostname, port, username, password) break if not cmdstr: return None c2 = cmds(cmdstr, timeout=3) stdo = c2.stdo() stde = c2.stde() retcode = c2.code() logdict = { "cmdstr": cmdstr, "stdo": stdo, "stde": stde, "retcode": retcode, "orders": ["cmdstr", "stdo", "stde", "retcode"], } if retcode !=0: self._logger.dictlog(width=8, level="error", **logdict) return else: self._logger.dictlog(width=8, level="info", **logdict) stdo_str = stdo stdo_str = stdo_str.replace("NumberLong(", "").replace(")", "").replace("ISODate(", "") #print stdo_str resobj = json.loads(stdo_str) return resobj except Exception as expt: import traceback tb = traceback.format_exc() self._logger.error(tb)
def get_port_list(self): cmdstr = "ps -ef | grep 'jmxremote.port='| grep -v grep 2>/dev/null" plst = [] c2 = cmds(cmdstr, timeout=3) stdo = c2.stdo() stde = c2.stde() retcode = c2.code() (stdo_list, stde_list) = (re.split("\n", stdo), re.split("\n", stde)) logdict = { "cmdstr": cmdstr, "stdo": stdo, "stde": stde, "retcode": retcode, "orders": ["cmdstr", "stdo", "stde", "retcode"], } if retcode != 0: self._logger.dictlog(width=8, level="error", **logdict) return else: self._logger.dictlog(width=8, level="info", **logdict) data = list() for line in stdo_list: if not line or str(line).strip() == "": continue line = str(line).strip() ln_ary = re.split("[\s]+", line) runuser = ln_ary[0] pid = ln_ary[1] jmxport = None for field in ln_ary: if "jmxremote.port=" in field: jmxport = str(field).split("jmxremote.port=")[1] confitem = { "{#PID}": int(pid), "{#RUNUSER}": runuser, } if jmxport: confitem["{#JVMPORT}"] = int(jmxport) if confitem: data.append(confitem) return json.dumps({'data': data}, sort_keys=True, indent=7, separators=(",", ":"))
def get_mysql_cmd_output(self, hostname=None, username=None, password=None, port=None): try: hostname= hostname if hostname else self._iphost username = username if username else self._username passwd = password if password else self._password port = port if port else self._port sys_binpath = which("mysqladmin") ## 适配编译安装,这里设置常用的路径 binpaths = [sys_binpath, "/usr/bin/mysqladmin", "/data/mysql/product/bin/mysqladmin"] cmdstr = None command = "extended-status" for p in binpaths: if not p or os.path.exists(p) == False: continue cmdstr = "%s -h%s -P%s -u'%s' -p'%s' %s" % (p,hostname,port,username,passwd, command) if not cmdstr:return None c2 = cmds(cmdstr, timeout=3) stdo = c2.stdo() stde = c2.stde() retcode = c2.code() logdict = { "cmdstr": cmdstr, "stdo": stdo, "stde": stde, "retcode": retcode, "orders": ["cmdstr", "stdo", "stde", "retcode"], } if retcode !=0: self._logger.dictlog(width=8, level="error", **logdict) return None else: self._logger.dictlog(width=8, level="info", **logdict) output_list = re.split("[\n]+", str(stdo).strip()) content = dict() for line in output_list: line = str(line).strip().replace(" ", "").lower().strip("|") line_ary = re.split("\|", line) if len(line_ary) < 2:continue content[line_ary[0]] = line_ary[1] return content except Exception as expt: import traceback tb = traceback.format_exc() self._logger.error(tb)
def get_res_set(self, key, port=None, password=None): port = port if port else self._port password = password if password else self._password rds_cli_path = which("redis-cli") ## 适配编译安装,这里设置常用的路径 rds_paths_def = ["/usr/bin/redis-cli", "/bin/redis-cli", "/usr/local/redis-server/bin/redis-cli"] cmdstr = None if rds_cli_path: cmdstr = "%s -h 127.0.0.1 -p %s info" % (rds_cli_path, port) if password: cmdstr = "%s -h 127.0.0.1 -a %s -p %s info" % (rds_cli_path, password, port) else: for p in rds_paths_def: if os.path.exists(p) == False: continue cmdstr = "%s -h 127.0.0.1 -p %s info" % (p, port) if password: cmdstr = "%s -h 127.0.0.1 -a %s -p %s info" % (p, password, port) break c2 = cmds(cmdstr, timeout=3) stdo = c2.stdo() stde = c2.stde() retcode = c2.code() (stdo_list, stde_list) = (re.split("\n", stdo), re.split("\n", stde)) logdict = { "cmdstr": cmdstr, "stdo": stdo, "stde": stde, "retcode": retcode, "orders": ["cmdstr", "stdo", "stde", "retcode"], } if retcode !=0: self._logger.dictlog(width=8, level="error", **logdict) return else: self._logger.dictlog(width=8, level="info", **logdict) resobj = {} for line in stdo_list: line = str(line).strip() ln_ary = re.split(":", line) if ln_ary and len(ln_ary) != 2:continue dst_key = str(ln_ary[0]).strip() dst_val = str(ln_ary[1]).strip() resobj[dst_key] = dst_val return resobj
def get_pd_list(slot): cmdstr = "sudo /usr/sbin/hpssacli controller slot={} physicaldrive all show detail|grep physicaldrive".format(slot) c2 = cmds(cmdstr, timeout=5) stdo = c2.stdo() stde = c2.stde() # retcode = c2.code() (stdo_list, stde_list) = (re.split("\n", stdo), re.split("\n", stde)) data = list() for pd in stdo_list: if not pd:continue data.append({ "{#DRIVE}": pd.split()[1], }) return json.dumps({'data': data}, sort_keys=True, indent=7, separators=(",",":"))
def get_tomcat_list(): cmdstr = "ps -ef|grep java|grep -v grep|grep \"Dcatalina.home\"|awk '{print $2 ,$(NF-3)}'|sed 's/-Dcatalina.home=//g'" c2 = cmds(cmdstr, timeout=3) stdo = c2.stdo() stde = c2.stde() # retcode = c2.code() (stdo_list, stde_list) = (re.split("\n", stdo), re.split("\n", stde)) data = list() for tomcat in stdo_list: if not tomcat: continue data.append({ "{#TOMCAT_PID}": tomcat.split()[0], "{#TOMCAT_PATH}": tomcat.split()[1], "{#TOMCAT_NAME}": tomcat.split()[1].split('/')[-1], }) return json.dumps({'data': data}, sort_keys=True, indent=7, separators=(",", ":"))
def get_redis_port_list(self): # sudo权限,必须授予,在root用户下执行如下命令 """ echo "zabbix ALL=(root) NOPASSWD:/bin/netstat" > /etc/sudoers.d/zabbix echo 'Defaults:zabbix !requiretty' >> /etc/sudoers.d/zabbix chmod 600 /etc/sudoers.d/zabbix """ cmdstr = "sudo netstat -nlpt | grep 'redis-server' | awk '{print $4}'|awk -F: '{print $2}'" c2 = cmds(cmdstr, timeout=3) stdo = c2.stdo() stde = c2.stde() retcode = c2.code() (stdo_list, stde_list) = (re.split("\n", stdo), re.split("\n", stde)) logdict = { "cmdstr": cmdstr, "stdo": stdo, "stde": stde, "retcode": retcode, "orders": ["cmdstr", "stdo", "stde", "retcode"], } if retcode != 0: self._logger.dictlog(width=8, level="error", **logdict) return else: #self._logger.dictlog(width=8, level="info", **logdict) pass data = list() for port in stdo_list: if not port: continue port = int(str(port).strip()) data.append({"{#REDIS_PORT}": port}) import json return json.dumps({'data': data}, sort_keys=True, indent=7, separators=(",", ":"))
def get_port_list(self): # sudo权限,必须授予 # [root@localhost ~]# tail -n 2 /etc/sudoers # Defaults:zabbix !requiretty # zabbix ALL=(root) NOPASSWD:/bin/netstat cmdstr = "sudo netstat -nlpt | grep 'memcached' | awk '{print $4}'|awk -F: '{print $2}'" port_conf = None c2 = cmds(cmdstr, timeout=3) stdo = c2.stdo() stde = c2.stde() retcode = c2.code() (stdo_list, stde_list) = (re.split("\n", stdo), re.split("\n", stde)) logdict = { "cmdstr": cmdstr, "stdo": stdo, "stde": stde, "retcode": retcode, "orders": ["cmdstr", "stdo", "stde", "retcode"], } if retcode != 0: self._logger.dictlog(width=8, level="error", **logdict) return port_conf else: self._logger.dictlog(width=8, level="info", **logdict) data = list() for port in stdo_list: if not port: continue port = int(str(port).strip()) data.append({"{#MEMCACHED_PORT}": port}) import json return json.dumps({'data': data}, sort_keys=True, indent=7, separators=(",", ":"))
def get_port_list(self): # sudo权限,必须授予 # [root@localhost ~]# tail -n 2 /etc/sudoers # Defaults:zabbix !requiretty # zabbix ALL=(root) NOPASSWD:/bin/netstat binname = "mongod" cmdstr = "sudo netstat -nlpt | grep '%s' | awk '{print $4}'" % (binname) c2 = cmds(cmdstr, timeout=3) stdo = c2.stdo() # print stdo stde = c2.stde() # print stde retcode = c2.code() (stdo_list, stde_list) = (re.split("\n", stdo), re.split("\n", stde)) logdict = { "cmdstr": cmdstr, "stdo": stdo, "stde": stde, "retcode": retcode, "orders": ["cmdstr", "stdo", "stde", "retcode"], } if retcode != 0: self._logger.dictlog(width=8, level="error", **logdict) return else: self._logger.dictlog(width=8, level="info", **logdict) data = list() for port in stdo_list: port = (str(port).strip()) port = port.replace(":", "-") data.append({"{#MONGODB_PORT}": port}) import json return json.dumps({'data': data}, sort_keys=True, indent=7, separators=(",", ":"))
def get_redis_port_list(self): # sudo权限,必须授予,在root用户下执行如下命令 """ echo "zabbix ALL=(root) NOPASSWD:/bin/netstat" > /etc/sudoers.d/zabbix echo 'Defaults:zabbix !requiretty' >> /etc/sudoers.d/zabbix chmod 600 /etc/sudoers.d/zabbix """ cmdstr = "sudo netstat -nlpt | grep 'redis-server' | awk '{print $4}'|awk -F: '{print $2}'" c2 = cmds(cmdstr, timeout=3) stdo = c2.stdo() stde = c2.stde() retcode = c2.code() (stdo_list, stde_list) = (re.split("\n", stdo), re.split("\n", stde)) logdict = { "cmdstr": cmdstr, "stdo": stdo, "stde": stde, "retcode": retcode, "orders": ["cmdstr", "stdo", "stde", "retcode"], } if retcode !=0: self._logger.dictlog(width=8, level="error", **logdict) return else: self._logger.dictlog(width=8, level="info", **logdict) data = list() for port in stdo_list: if not port:continue port = int(str(port).strip()) data.append({"{#REDIS_PORT}": port}) import json return json.dumps({'data': data}, sort_keys=True, indent=7, separators=(",",":"))
def get_item(self, key, port=None, password=None, force=False): """ 参数: """ # cmdstr = "redis-cli -h 127.0.0.1 -p 6379 info | grep 'used_cpu_sys' " port = port if port else self._port password = password if password else self._password if force == False: value = self._file_cache.get_val_from_json(key) logdict = { "msg": "Try To Get From Cache File: %s" % self._file_cache_path, "key": key, "value": value, "orders": ["msg", "key", "value"], } self._logger.dictlog(width=8, level="info", **logdict) if value: return value rds_cli_path = which("redis-cli") ## 适配编译安装,这里设置常用的路径 rds_paths_def = ["/usr/bin/redis-cli", "/bin/redis-cli", "/usr/local/redis-server/bin/redis-cli"] cmdstr = None if rds_cli_path: cmdstr = "%s -h 127.0.0.1 -p %s info" % (rds_cli_path, port) if password: cmdstr = "%s -h 127.0.0.1 -a %s -p %s info" % (rds_cli_path, password, port) else: for p in rds_paths_def: if os.path.exists(p) == False: continue cmdstr = "%s -h 127.0.0.1 -p %s info" % (p, port) if password: cmdstr = "%s -h 127.0.0.1 -a %s -p %s info" % (p, password, port) break c2 = cmds(cmdstr, timeout=3) stdo = c2.stdo() stde = c2.stde() retcode = c2.code() (stdo_list, stde_list) = (re.split("\n", stdo), re.split("\n", stde)) logdict = { "cmdstr": cmdstr, "stdo": stdo, "stde": stde, "retcode": retcode, "orders": ["cmdstr", "stdo", "stde", "retcode"], } if retcode !=0: self._logger.dictlog(width=8, level="error", **logdict) return else: self._logger.dictlog(width=8, level="info", **logdict) resobj = {} for line in stdo_list: line = str(line).strip() ln_ary = re.split(":", line) if ln_ary and len(ln_ary) != 2:continue dst_key = str(ln_ary[0]).strip() dst_val = str(ln_ary[1]).strip() resobj[dst_key] = dst_val self._file_cache.save_to_cache_file(resobj) return resobj.get(key, "")
def get_item(self, key, port=None, password=None, force=False): """ 参数: """ # cmdstr = "redis-cli -h 127.0.0.1 -p 6379 info | grep 'used_cpu_sys' " port = port if port else self._port password = password if password else self._password if force == False: value = self._file_cache.get_val_from_json(key) logdict = { "msg": "Try To Get From Cache File: %s" % self._file_cache_path, "key": key, "value": value, "orders": ["msg", "key", "value"], } self._logger.dictlog(width=8, level="info", **logdict) if value: return value rds_cli_path = which("redis-cli") ## 适配编译安装,这里设置常用的路径 rds_paths_def = [ "/usr/local/bin/redis-cli", "/usr/bin/redis-cli", "/bin/redis-cli", "/usr/local/redis-server/bin/redis-cli" ] cmdstr = None if rds_cli_path: cmdstr = "%s -h 127.0.0.1 -p %s info" % (rds_cli_path, port) if password: cmdstr = "%s -h 127.0.0.1 -a %s -p %s info" % (rds_cli_path, password, port) else: for p in rds_paths_def: if os.path.exists(p) == False: continue cmdstr = "%s -h 127.0.0.1 -p %s info" % (p, port) if password: cmdstr = "%s -h 127.0.0.1 -a %s -p %s info" % (p, password, port) break c2 = cmds(cmdstr, timeout=3) stdo = c2.stdo() stde = c2.stde() retcode = c2.code() (stdo_list, stde_list) = (re.split("\n", stdo), re.split("\n", stde)) logdict = { "cmdstr": cmdstr, "stdo": stdo, "stde": stde, "retcode": retcode, "orders": ["cmdstr", "stdo", "stde", "retcode"], } if retcode != 0: self._logger.dictlog(width=8, level="error", **logdict) return else: self._logger.dictlog(width=8, level="info", **logdict) resobj = {} for line in stdo_list: line = str(line).strip() ln_ary = re.split(":", line) if ln_ary and len(ln_ary) != 2: continue dst_key = str(ln_ary[0]).strip() dst_val = str(ln_ary[1]).strip() resobj[dst_key] = dst_val self._file_cache.save_to_cache_file(resobj) return resobj.get(key, "")
def get_port_list(self): cmdstr = "ps -ef | grep tomcat | grep 'jmxremote.port='| grep -v grep 2>/dev/null" plst = [] c2 = cmds(cmdstr, timeout=3) stdo = c2.stdo() stde = c2.stde() retcode = c2.code() (stdo_list, stde_list) = (re.split("\n", stdo), re.split("\n", stde)) logdict = { "cmdstr": cmdstr, "stdo": stdo, "stde": stde, "retcode": retcode, "orders": ["cmdstr", "stdo", "stde", "retcode"], } if retcode !=0: self._logger.dictlog(width=8, level="error", **logdict) return else: self._logger.dictlog(width=8, level="info", **logdict) data = list() for line in stdo_list: if not line or str(line).strip() == "": continue line = str(line).strip() ln_ary = re.split("[\s]+", line) pid = ln_ary[1] runuser = ln_ary[0] (jmxport, catalina_home, tc_dirname, buz_port) = (None, None, None, None) for field in ln_ary: if "jmxremote.port=" in field: jmxport = str(field).split("jmxremote.port=")[1] if "catalina.home=" in field: catalina_home = str(field).split("catalina.home=")[1] tc_dirname = str(catalina_home).split("/")[-1] confitem = { "{#RUNUSER}": runuser, "{#PID}": int(pid), } if jmxport: confitem["{#JVMPORT}"] = int(jmxport) if catalina_home: confitem["{#CTLN_HOME}"] = catalina_home server_xml = "%s/conf/server.xml" % (catalina_home) if os.path.exists(server_xml): parser = xml.sax.make_parser() parser.setFeature(xml.sax.handler.feature_namespaces, 0) handler = TCSerHandler() parser.setContentHandler( handler ) parser.parse(server_xml) biz_port = handler.get_biz_port() or "NotFound" if biz_port: confitem["{#BIZPORT}"] = biz_port if tc_dirname: confitem["{#DIRNAME}"] = tc_dirname if confitem: data.append(confitem) import json return json.dumps({'data': data}, sort_keys=True, indent=7, separators=(",",":"))
def get_port_list(self): cmdstr = "ps -ef | grep tomcat | grep 'jmxremote.port='| grep -v grep 2>/dev/null" plst = [] c2 = cmds(cmdstr, timeout=3) stdo = c2.stdo() stde = c2.stde() retcode = c2.code() (stdo_list, stde_list) = (re.split("\n", stdo), re.split("\n", stde)) logdict = { "cmdstr": cmdstr, "stdo": stdo, "stde": stde, "retcode": retcode, "orders": ["cmdstr", "stdo", "stde", "retcode"], } if retcode != 0: self._logger.dictlog(width=8, level="error", **logdict) return else: self._logger.dictlog(width=8, level="info", **logdict) data = list() for line in stdo_list: if not line or str(line).strip() == "": continue line = str(line).strip() ln_ary = re.split("[\s]+", line) pid = ln_ary[1] runuser = ln_ary[0] (jmxport, catalina_home, tc_dirname, buz_port) = (None, None, None, None) for field in ln_ary: if "jmxremote.port=" in field: jmxport = str(field).split("jmxremote.port=")[1] if "catalina.home=" in field: catalina_home = str(field).split("catalina.home=")[1] tc_dirname = str(catalina_home).split("/")[-1] confitem = { "{#RUNUSER}": runuser, "{#PID}": int(pid), } if jmxport: confitem["{#JVMPORT}"] = int(jmxport) if catalina_home: confitem["{#CTLN_HOME}"] = catalina_home server_xml = "%s/conf/server.xml" % (catalina_home) if os.path.exists(server_xml): parser = xml.sax.make_parser() parser.setFeature(xml.sax.handler.feature_namespaces, 0) handler = TCSerHandler() parser.setContentHandler(handler) parser.parse(server_xml) biz_port = handler.get_biz_port() if biz_port: confitem["{#BIZPORT}"] = biz_port if tc_dirname: confitem["{#DIRNAME}"] = tc_dirname if confitem: data.append(confitem) import json return json.dumps({'data': data}, sort_keys=True, indent=7, separators=(",", ":"))
def get_item(self, beanstr, key, port, iphost='localhost', auth='-'): """ java -jar cmdline-jmxclient-0.10.3.jar - localhost:12345 java.lang:type=Memory NonHeapMemoryUsage 参数: """ pre_key = key sub_key = None if "." in key: pos = str(key).rfind(".") pre_key = key[0:pos] sub_key = key[pos + 1:] if self._java_path == None: print "can not find java command, exit." return None cmdstr = "%s -jar %s %s %s:%s '%s' '%s'" % (self._java_path, self._cmdclient_jar, auth, iphost, port, beanstr, pre_key) c2 = cmds(cmdstr, timeout=3) stdo = c2.stdo() stde = c2.stde() retcode = c2.code() (stdo_list, stde_list) = (re.split("\n", stdo), re.split("\n", stde)) logdict = { "beanstr": beanstr, "key": key, "cmdstr": cmdstr, "stdo": stdo, "stde": stde, "retcode": retcode, "orders": ["beanstr", "lst_beanstr", "key", "cmdstr", "stdo", "stde", "retcode"], } if retcode !=0: self._logger.dictlog(width=8, level="error", **logdict) return else: self._logger.dictlog(width=8, level="info", **logdict) if stde_list: stdo_list.extend(stde_list) # # without sub attr if not sub_key and stdo_list: line = stdo_list[-1] ln_ary = re.split(" ", line) if ln_ary and len(ln_ary) >= 2: if pre_key in ln_ary[-2]: return ln_ary[-1] # print stdo_list,"###" # # with sub attr for line in stdo_list: line = str(line).strip() ln_ary = re.split(":", line) if ln_ary and len(ln_ary) != 2:continue dst_key = str(ln_ary[0]).strip() dst_val = str(ln_ary[1]).strip() if sub_key == dst_key: return dst_val return None
def get_item(self, beanstr, key, port, iphost='localhost', auth='-'): """ java -jar cmdline-jmxclient-0.10.3.jar - localhost:12345 java.lang:type=Memory NonHeapMemoryUsage 参数: """ pre_key = key sub_key = None if "." in key: pos = str(key).rfind(".") pre_key = key[0:pos] sub_key = key[pos + 1:] if self._java_path == None: print "can not find java command, exit." return None cmdstr = "%s -jar %s %s %s:%s '%s' '%s'" % (self._java_path, self._cmdclient_jar, auth, iphost, port, beanstr, pre_key) c2 = cmds(cmdstr, timeout=6) stdo = c2.stdo() stde = c2.stde() retcode = c2.code() (stdo_list, stde_list) = (re.split("\n", stdo), re.split("\n", stde)) logdict = { "beanstr": beanstr, "key": key, "cmdstr": cmdstr, "stdo": stdo, "stde": stde, "retcode": retcode, "orders": ["beanstr", "lst_beanstr", "key", "cmdstr", "stdo", "stde", "retcode"], } if retcode !=0: self._logger.dictlog(width=8, level="error", **logdict) return else: self._logger.dictlog(width=8, level="info", **logdict) if stde_list: stdo_list.extend(stde_list) # # without sub_key attr # # handle the output in below format: # cmd: python jvm.py -b "java.lang:type=Runtime" -k "VmVersion" -p 18080 # output: 10/26/2015 14:23:51 +0800 org.archive.jmx.Client VmVersion: 25.121-b13 if not sub_key and stdo_list: line = stdo_list[-1] ln_ary = re.split(" ", line) if ln_ary and len(ln_ary) >= 2: if pre_key in ln_ary[-2]: return ln_ary[-1] # handle the out in below format: # cmd: python jvm.py -d -b "java.lang:type=Runtime" -k "VmName" -p 18080 # output: 10/26/2015 14:28:13 +0800 org.archive.jmx.Client VmName: Java HotSpot(TM) 64-Bit Server VM for line in stdo_list: line = str(line).strip() ln_ary = re.split(":", line) if ln_ary and len(ln_ary) > 2: for key in ln_ary: if pre_key and pre_key in key: return str(ln_ary[-1]).strip() #print stdo_list,"###" #print "sub_key: " + sub_key #print "-line: " + line # handle the out in below format: # cmd: python jvm.py -d -b "java.lang:type=Memory" -k "NonHeapMemoryUsage.used" -p 18080 # output: #stde: 10/26/2015 14:38:51 +0800 org.archive.jmx.Client NonHeapMemoryUsage: #committed: 45842432 #init: 2555904 #max: -1 #used: 43731872 # # with sub_key attr for line in stdo_list: line = str(line).strip() ln_ary = re.split(":", line) if ln_ary and len(ln_ary) != 2:continue dst_key = str(ln_ary[0]).strip() dst_val = str(ln_ary[1]).strip() if sub_key == dst_key: return dst_val return None