├── ZabbixTool ├── py_tool │ ├── __init__.py │ ├── my_lib │ │ ├── __init__.py │ │ ├── date.py │ │ └── pyMail.py │ └── config │ │ └── zabbix_tool.ini ├── lib_zabbix │ ├── w_lib │ │ ├── __init__.py │ │ ├── mylib │ │ │ ├── __init__.py │ │ │ └── xlwt │ │ │ │ ├── BIFFRecords.py │ │ │ │ ├── UnicodeUtils.py │ │ │ │ ├── __init__.py │ │ │ │ ├── compat.py │ │ │ │ ├── ExcelFormula.py │ │ │ │ ├── Column.py │ │ │ │ ├── CreateLearningSheet.py │ │ │ │ ├── ExcelFormulaLexer.py │ │ │ │ ├── GenerateAFFont.py │ │ │ │ ├── Utils.py │ │ │ │ ├── Cell.py │ │ │ │ ├── Formatting.py │ │ │ │ ├── CompoundDoc.py │ │ │ │ └── Bitmap.py │ │ ├── terminaltables │ │ │ ├── __init__.py │ │ │ ├── terminal_io.py │ │ │ ├── width_and_alignment.py │ │ │ ├── tables.py │ │ │ └── base_table.py │ │ ├── colorclass │ │ │ ├── toggles.py │ │ │ ├── __main__.py │ │ │ ├── __init__.py │ │ │ ├── search.py │ │ │ ├── parse.py │ │ │ ├── color.py │ │ │ └── codes.py │ │ ├── my_compare.py │ │ ├── my_sort.py │ │ ├── BLog.py │ │ ├── XLSWriter.py │ │ └── backup │ │ │ ├── zabbix_api_lib.py_1.2.7 │ │ │ └── zabbix_api_lib.py_1.3.04 │ ├── logo.bmp │ ├── itemkey.example │ ├── etc │ │ ├── zabbix_setting.ini │ │ └── zabbix_config.ini │ ├── switch │ ├── __doc │ │ ├── time.sh │ │ ├── mylog.py │ │ ├── my_compare.py │ │ ├── zabbix_re.py │ │ ├── test.py │ │ └── zabbix-time.py │ └── config.py ├── .shell_menu_configured ├── README.md ├── sh_menu │ ├── Config │ │ ├── host.menu │ │ ├── item.menu │ │ ├── template.menu │ │ ├── hostgroup.menu │ │ └── TOOL.menu │ └── Function │ │ ├── issues.sh │ │ ├── host │ │ └── host_get.sh │ │ ├── template │ │ └── template_get.sh │ │ ├── hostgroup │ │ └── hostgroup_get.sh │ │ └── item │ │ └── item_list.sh ├── scripts │ ├── template │ │ ├── template_import.sh │ │ └── ceshi_templates.xml │ └── init │ │ └── init.sh ├── main.py └── main.sh ├── images ├── 5.jpg ├── report_xls.jpg ├── report_table.jpg ├── usergroup_add.jpg ├── report_available_xls.jpg ├── wiki │ ├── zabbix_community.png │ └── zabbix_structure.jpg ├── report_available_table.jpg ├── report_available_table2.jpg └── report_available_table3.jpg ├── tools └── telnet-0.17-47.el6.x86_64.rpm ├── .gitignore ├── start.sh ├── README.md └── LICENSE /ZabbixTool/py_tool/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ZabbixTool/py_tool/my_lib/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/w_lib/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/w_lib/mylib/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /images/5.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/meetbill/zabbix_manager/HEAD/images/5.jpg -------------------------------------------------------------------------------- /images/report_xls.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/meetbill/zabbix_manager/HEAD/images/report_xls.jpg -------------------------------------------------------------------------------- /ZabbixTool/.shell_menu_configured: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | TOOL_PATH_FLAG=/root/github/zabbix_manager/ZabbixTool 3 | -------------------------------------------------------------------------------- /images/report_table.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/meetbill/zabbix_manager/HEAD/images/report_table.jpg -------------------------------------------------------------------------------- /images/usergroup_add.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/meetbill/zabbix_manager/HEAD/images/usergroup_add.jpg -------------------------------------------------------------------------------- /ZabbixTool/README.md: -------------------------------------------------------------------------------- 1 | # ManagerTool 2 | 3 | [使用手册](https://github.com/BillWang139967/zabbix_manager/wiki) 4 | -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/logo.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/meetbill/zabbix_manager/HEAD/ZabbixTool/lib_zabbix/logo.bmp -------------------------------------------------------------------------------- /images/report_available_xls.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/meetbill/zabbix_manager/HEAD/images/report_available_xls.jpg -------------------------------------------------------------------------------- /images/wiki/zabbix_community.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/meetbill/zabbix_manager/HEAD/images/wiki/zabbix_community.png -------------------------------------------------------------------------------- /images/wiki/zabbix_structure.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/meetbill/zabbix_manager/HEAD/images/wiki/zabbix_structure.jpg -------------------------------------------------------------------------------- /ZabbixTool/sh_menu/Config/host.menu: -------------------------------------------------------------------------------- 1 | host_get.sh%/root/github/zabbix_manager/ZabbixTool/sh_menu/Function/host/host_get.sh 2 | -------------------------------------------------------------------------------- /ZabbixTool/sh_menu/Config/item.menu: -------------------------------------------------------------------------------- 1 | item_list.sh%/root/github/zabbix_manager/ZabbixTool/sh_menu/Function/item/item_list.sh 2 | -------------------------------------------------------------------------------- /images/report_available_table.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/meetbill/zabbix_manager/HEAD/images/report_available_table.jpg -------------------------------------------------------------------------------- /images/report_available_table2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/meetbill/zabbix_manager/HEAD/images/report_available_table2.jpg -------------------------------------------------------------------------------- /images/report_available_table3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/meetbill/zabbix_manager/HEAD/images/report_available_table3.jpg -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/itemkey.example: -------------------------------------------------------------------------------- 1 | size[available] 2 | agent.ping 3 | vfs.fs.size[/,pfree] 4 | system.cpu.load[percpu,avg1] 5 | -------------------------------------------------------------------------------- /tools/telnet-0.17-47.el6.x86_64.rpm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/meetbill/zabbix_manager/HEAD/tools/telnet-0.17-47.el6.x86_64.rpm -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/etc/zabbix_setting.ini: -------------------------------------------------------------------------------- 1 | [web] 2 | # lnmp(False),lamp(True) 3 | apache = False 4 | [report] 5 | logo_show = True 6 | -------------------------------------------------------------------------------- /ZabbixTool/sh_menu/Config/template.menu: -------------------------------------------------------------------------------- 1 | template_get.sh%/root/github/zabbix_manager/ZabbixTool/sh_menu/Function/template/template_get.sh 2 | -------------------------------------------------------------------------------- /ZabbixTool/sh_menu/Config/hostgroup.menu: -------------------------------------------------------------------------------- 1 | hostgroup_get.sh%/root/github/zabbix_manager/ZabbixTool/sh_menu/Function/hostgroup/hostgroup_get.sh 2 | -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/switch: -------------------------------------------------------------------------------- 1 | # 注释 2 | # description===hostid===ethernet port===default_speed 3 | 描述===10084===Ethernet0/0===AUTO 4 | 描述===10084===Ethernet0/0===1000 5 | -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/w_lib/mylib/xlwt/BIFFRecords.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/meetbill/zabbix_manager/HEAD/ZabbixTool/lib_zabbix/w_lib/mylib/xlwt/BIFFRecords.py -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/w_lib/mylib/xlwt/UnicodeUtils.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/meetbill/zabbix_manager/HEAD/ZabbixTool/lib_zabbix/w_lib/mylib/xlwt/UnicodeUtils.py -------------------------------------------------------------------------------- /ZabbixTool/sh_menu/Config/TOOL.menu: -------------------------------------------------------------------------------- 1 | hostgroup%hostgroup.menu 2 | host%host.menu 3 | issues.sh%/root/github/zabbix_manager/ZabbixTool/sh_menu/Function/issues.sh 4 | item%item.menu 5 | template%template.menu 6 | -------------------------------------------------------------------------------- /ZabbixTool/py_tool/config/zabbix_tool.ini: -------------------------------------------------------------------------------- 1 | [create_file] 2 | # 应用名称,使用","进行分割 3 | applitions=s3,Zabbix agent 4 | # 忽略的 key 列表 5 | ignore_key=agent.hostname,agent.version 6 | # 导出的文件位置 7 | monit_config=/etc/monit_config.py 8 | -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/etc/zabbix_config.ini: -------------------------------------------------------------------------------- 1 | [zabbixserver] 2 | server = 127.0.0.1 3 | port = 80 4 | user = admin 5 | password = zabbix 6 | #[bendi] 7 | #server = 192.168.199.128 8 | #port = 80 9 | #user = admin 10 | #password = zabbix 11 | -------------------------------------------------------------------------------- /ZabbixTool/sh_menu/Function/issues.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | ######################################################################### 3 | # File Name: issues.sh 4 | # Author: meetbill 5 | # mail: meetbill@163.com 6 | # Created Time: 2017-06-10 08:34:45 7 | ######################################################################### 8 | zabbix_api issues --table 9 | 10 | -------------------------------------------------------------------------------- /ZabbixTool/sh_menu/Function/host/host_get.sh: -------------------------------------------------------------------------------- 1 | ######################################################################### 2 | # File Name: host_get.sh 3 | # Author: 遇见王斌 4 | # mail: meetbill@163.com 5 | # Created Time: 2016-11-27 16:48:01 6 | ######################################################################### 7 | #!/bin/bash 8 | zabbix_api host_get --table 9 | 10 | -------------------------------------------------------------------------------- /ZabbixTool/sh_menu/Function/template/template_get.sh: -------------------------------------------------------------------------------- 1 | ######################################################################### 2 | # File Name: template_get.sh 3 | # Author: 遇见王斌 4 | # mail: meetbill@163.com 5 | # Created Time: 2016-11-27 16:55:30 6 | ######################################################################### 7 | #!/bin/bash 8 | zabbix_api template_get 9 | 10 | -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/w_lib/mylib/xlwt/__init__.py: -------------------------------------------------------------------------------- 1 | __VERSION__ = '1.0.0' 2 | 3 | from .Workbook import Workbook 4 | from .Worksheet import Worksheet 5 | from .Row import Row 6 | from .Column import Column 7 | from .Formatting import Font, Alignment, Borders, Pattern, Protection 8 | from .Style import XFStyle, easyxf, easyfont, add_palette_colour 9 | from .ExcelFormula import * 10 | -------------------------------------------------------------------------------- /ZabbixTool/sh_menu/Function/hostgroup/hostgroup_get.sh: -------------------------------------------------------------------------------- 1 | ######################################################################### 2 | # File Name: hostgroup_get.sh 3 | # Author: 遇见王斌 4 | # mail: meetbill@163.com 5 | # Created Time: 2016-11-27 16:53:17 6 | ######################################################################### 7 | #!/bin/bash 8 | zabbix_api hostgroup_get --table 9 | 10 | -------------------------------------------------------------------------------- /ZabbixTool/scripts/template/template_import.sh: -------------------------------------------------------------------------------- 1 | ######################################################################### 2 | # File Name: template_import.sh 3 | # Author: Bill 4 | # mail: XXXXXXX@qq.com 5 | # Created Time: 2016-06-22 16:30:11 6 | ######################################################################### 7 | #!/bin/bash 8 | python ./lib_zabbix/zabbix_api.py --template_import ./scripts/template/ceshi_templates.xml 9 | -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/__doc/time.sh: -------------------------------------------------------------------------------- 1 | ######################################################################### 2 | # File Name: test_history_get.sh 3 | # Author: Bill 4 | # mail: XXXXXXX@qq.com 5 | # Created Time: 2016-06-10 12:11:48 6 | ######################################################################### 7 | #!/bin/bash 8 | ##报告的初始时间和结束时间(前一天的0点到24点) 9 | from=`date "+%Y-%m-%d 00:00:00" -d"-2day"` 10 | now=`date "+%Y-%m-%d 00:00:00"` 11 | 12 | from=`date -d "$from" '+%s'` 13 | now=`date -d "$now" '+%s'` 14 | 15 | echo $from 16 | echo $now 17 | -------------------------------------------------------------------------------- /ZabbixTool/sh_menu/Function/item/item_list.sh: -------------------------------------------------------------------------------- 1 | ######################################################################### 2 | # File Name: item_list.sh 3 | # Author: 遇见王斌 4 | # mail: meetbill@qq.com 5 | # Created Time: 2016-06-07 12:35:08 6 | ######################################################################### 7 | #!/bin/bash 8 | err_echo(){ 9 | echo -e "\033[41;37m[Error]: $1 \033[0m" 10 | } 11 | read -p "please host id:" g_HOST_ID 12 | if [[ -z ${g_HOST_ID} ]] 13 | then 14 | err_echo "host_id is null" 15 | fi 16 | zabbix_api item_get $g_HOST_ID 17 | 18 | -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/__doc/mylog.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding=utf8 3 | """ 4 | Author: Bill 5 | Created Time : 2015年11月23日 星期一 16时20分07秒 6 | File Name: mylog.py 7 | Description: 8 | """ 9 | import logging 10 | logging.basicConfig(level=logging.DEBUG, 11 | format='%(asctime)s%(filename)s[line:%(lineno)d] %(levelname)s%(message)s', 12 | datefmt='%a,%d %b %Y %H:%M:%S', 13 | filename='/tmp/test.log', 14 | filemode='a') 15 | 16 | 17 | logging.debug('debug message') 18 | logging.info('info message') 19 | logging.warning('warning message') 20 | logging.error('error message') 21 | logging.critical('critical message') 22 | 23 | -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/w_lib/terminaltables/__init__.py: -------------------------------------------------------------------------------- 1 | """Generate simple tables in terminals from a nested list of strings. 2 | 3 | Use SingleTable or DoubleTable instead of AsciiTable for box-drawing characters. 4 | 5 | https://github.com/Robpol86/terminaltables 6 | https://pypi.python.org/pypi/terminaltables 7 | """ 8 | 9 | from terminaltables.tables import AsciiTable # noqa 10 | from terminaltables.tables import DoubleTable # noqa 11 | from terminaltables.tables import GithubFlavoredMarkdownTable # noqa 12 | from terminaltables.tables import SingleTable # noqa 13 | 14 | __author__ = '@Robpol86' 15 | __license__ = 'MIT' 16 | __version__ = '2.1.0' 17 | -------------------------------------------------------------------------------- /ZabbixTool/scripts/init/init.sh: -------------------------------------------------------------------------------- 1 | ######################################################################### 2 | # File Name: alert.sh 3 | # Author: Bill 4 | # mail: XXXXXXX@qq.com 5 | # Created Time: 2016-06-20 11:58:11 6 | ######################################################################### 7 | #!/bin/bash 8 | 9 | # agent 自动注册 10 | zabbix_api action_autoreg_create "ceshi_action" "Linux" "Linux servers" 11 | #zabbix_api mediatype_create alerts alerts.py 12 | #zabbix_api usergroup_create "op_group" "Linux servers" 13 | #zabbix_api user_create op 123456 "op_group" alerts "ceshi@qq.com" 14 | #zabbix_api action_trigger_create "trigger_action" "op_group" "alerts" 15 | -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/w_lib/mylib/xlwt/compat.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | PY3 = sys.version_info[0] >= 3 4 | 5 | if PY3: 6 | unicode = bytes.decode 7 | unicode_type = str 8 | basestring = str 9 | xrange = range 10 | int_types = (int,) 11 | long = int 12 | 13 | def iteritems(d): 14 | return iter(d.items()) 15 | def itervalues(d): 16 | return iter(d.values()) 17 | else: 18 | # Python 2 19 | unicode = unicode_type = unicode 20 | basestring = basestring 21 | xrange = xrange 22 | int_types = (int, long) 23 | long = long 24 | 25 | def iteritems(d): 26 | return d.iteritems() 27 | def itervalues(d): 28 | return d.itervalues() 29 | -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/config.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding:utf8 3 | import os 4 | import sys 5 | import re 6 | def read_config(hosts_file): 7 | host=[] 8 | host_file=open(hosts_file) 9 | # 判断第一行是否有主机组 10 | for line in host_file: 11 | if re.search("^#",line) or re.search("^ *$",line): 12 | continue 13 | host_info=line.strip().split("===") 14 | if len(host_info) < 4: 15 | print "the config file is err" 16 | sys.exit() 17 | host.append((host_info[0],host_info[1],host_info[2],host_info[3])) 18 | return host 19 | 20 | if __name__ == "__main__": 21 | hosts_file="./switch" 22 | host_info = read_config(hosts_file) 23 | print host_info 24 | -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/__doc/my_compare.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding=utf8 3 | """ 4 | # Author: Bill 5 | # Created Time : 2016-06-11 14:43:35 6 | 7 | # File Name: my_compare.py 8 | # Description: 9 | 10 | """ 11 | import re 12 | def my_compare(str_all,str_sub): 13 | str_sub_list=re.split(r' ', str_sub) 14 | for sub in str_sub_list: 15 | if sub in str_all: 16 | continue 17 | else: 18 | return 0 19 | return 1 20 | 21 | 22 | if __name__ == "__main__": 23 | str_sub="to world" 24 | str1="I want to say hello world" 25 | str2="I want say hello world" 26 | info=my_compare(str1,str_sub) 27 | print "ceshi:1",info 28 | info=my_compare(str2,str_sub) 29 | print "ceshi:0",info 30 | -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/__doc/zabbix_re.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding=utf8 3 | """ 4 | # Author: meetbill 5 | # Created Time : 2017-08-30 20:54:25 6 | 7 | # File Name: zabbix_re.py 8 | # Description: 9 | 10 | """ 11 | import re 12 | # vfs.fs.size[/,pfree] 13 | #subject="vfs.[]" 14 | #regex="vfs.\[\]$" 15 | subject_list=["vfs.fs.size[/,pfree]","vfs.fs.size[/home,pfree]"] 16 | regex="vfs.fs.size\[.*,pfree\]$" 17 | regex1="vfs.fs.size\[.,pfree\]$" 18 | 19 | 20 | print "regex:-------------------------",regex 21 | for subject in subject_list: 22 | if re.match(regex, subject): 23 | print subject,"OK" 24 | else: 25 | print subject,"ERR" 26 | 27 | print "regex:-------------------------",regex1 28 | for subject in subject_list: 29 | if re.match(regex1, subject): 30 | print subject,"OK" 31 | else: 32 | print subject,"ERR" 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | 55 | # Sphinx documentation 56 | docs/_build/ 57 | 58 | # PyBuilder 59 | target/ 60 | 61 | #Ipython Notebook 62 | .ipynb_checkpoints 63 | -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/w_lib/colorclass/toggles.py: -------------------------------------------------------------------------------- 1 | """Convenience functions to enable/disable features.""" 2 | 3 | from colorclass.codes import ANSICodeMapping 4 | 5 | 6 | def disable_all_colors(): 7 | """Disable all colors. Strip any color tags or codes.""" 8 | ANSICodeMapping.disable_all_colors() 9 | 10 | 11 | def enable_all_colors(): 12 | """Enable colors.""" 13 | ANSICodeMapping.enable_all_colors() 14 | 15 | 16 | def is_enabled(): 17 | """Are colors enabled.""" 18 | return not ANSICodeMapping.DISABLE_COLORS 19 | 20 | 21 | def set_light_background(): 22 | """Choose dark colors for all 'auto'-prefixed codes for readability on light backgrounds.""" 23 | ANSICodeMapping.set_light_background() 24 | 25 | 26 | def set_dark_background(): 27 | """Choose dark colors for all 'auto'-prefixed codes for readability on light backgrounds.""" 28 | ANSICodeMapping.set_dark_background() 29 | 30 | 31 | def is_light(): 32 | """Are background colors for light backgrounds.""" 33 | return ANSICodeMapping.LIGHT_BACKGROUND 34 | -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/w_lib/colorclass/__main__.py: -------------------------------------------------------------------------------- 1 | """Called by "python -m". Allows package to be used as a script. 2 | 3 | Example usage: 4 | echo "{red}Red{/red}" |python -m colorclass 5 | """ 6 | 7 | from __future__ import print_function 8 | 9 | import fileinput 10 | import os 11 | 12 | from colorclass.color import Color 13 | from colorclass.toggles import disable_all_colors 14 | from colorclass.toggles import enable_all_colors 15 | from colorclass.toggles import set_dark_background 16 | from colorclass.toggles import set_light_background 17 | from colorclass.windows import Windows 18 | 19 | TRUTHY = ('true', '1', 'yes', 'on') 20 | 21 | 22 | if __name__ == '__main__': 23 | if os.environ.get('COLOR_ENABLE', '').lower() in TRUTHY: 24 | enable_all_colors() 25 | elif os.environ.get('COLOR_DISABLE', '').lower() in TRUTHY: 26 | disable_all_colors() 27 | if os.environ.get('COLOR_LIGHT', '').lower() in TRUTHY: 28 | set_light_background() 29 | elif os.environ.get('COLOR_DARK', '').lower() in TRUTHY: 30 | set_dark_background() 31 | Windows.enable() 32 | for LINE in fileinput.input(): 33 | print(Color(LINE)) 34 | -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/__doc/test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding=utf8 3 | """ 4 | # Author: Bill 5 | # Created Time : Wed 02 Dec 2015 10:17:28 AM CST 6 | 7 | # File Name: wb_zabbix.py 8 | # Description: 9 | 10 | """ 11 | import os 12 | import sys 13 | root_path = os.path.dirname(__file__) 14 | print root_path 15 | sys.path.insert(0, os.path.join(root_path)) 16 | sys.path.insert(0, os.path.join(root_path, 'mylib')) 17 | from zabbix_api import zabbix_api 18 | #新增帮助信息,可直接执行脚本 19 | zabbix=zabbix_api() 20 | #获取所有主机列表 21 | zabbix.host_get() 22 | #查询单个主机列表 23 | #zabbix.host_get('WP227') 24 | #获取所有主机组列表 25 | #zabbix.hostgroup_get() 26 | #查询单个主机组列表 27 | #zabbix.hostgroup_get('test01') 28 | #获取所有模板列表 29 | #zabbix.template_get() 30 | #查询单个模板信息 31 | # zabbix.template_get('Template OS Linux') 32 | #添加一个主机组 33 | #zabbix.hostgroup_create('test01') 34 | #添加一个主机,支持将主机添加进多个组,多个模板,多个组、模板之间用逗号隔开,如果添加的组不存在,新创建组 35 | #zabbix.host_create('192.168.199.137', 'ceshi3','Qywp', 'Template OS Linux') 36 | #zabbix.host_create('192.168.2.1', 'Linux servers,test01 ', 'Template OS Linux,Template App MySQL') 37 | #禁用一个主机 38 | # zabbix.host_disable('192.168.2.1') 39 | #删除host,支持删除多个,之间用逗号 40 | #zabbix.host_delete('192.168.2.1,192.168.2.2') 41 | #zabbix.alert_get() 42 | -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/w_lib/colorclass/__init__.py: -------------------------------------------------------------------------------- 1 | """Colorful worry-free console applications for Linux, Mac OS X, and Windows. 2 | 3 | Supported natively on Linux and Mac OSX (Just Works), and on Windows it works the same if Windows.enable() is called. 4 | 5 | Gives you expected and sane results from methods like len() and .capitalize(). 6 | 7 | https://github.com/Robpol86/colorclass 8 | https://pypi.python.org/pypi/colorclass 9 | """ 10 | 11 | from colorclass.codes import list_tags # noqa 12 | from colorclass.color import Color # noqa 13 | from colorclass.toggles import disable_all_colors # noqa 14 | from colorclass.toggles import enable_all_colors # noqa 15 | from colorclass.toggles import is_enabled # noqa 16 | from colorclass.toggles import is_light # noqa 17 | from colorclass.toggles import set_dark_background # noqa 18 | from colorclass.toggles import set_light_background # noqa 19 | from colorclass.windows import Windows # noqa 20 | 21 | 22 | __all__ = ( 23 | 'Color', 24 | 'disable_all_colors', 25 | 'enable_all_colors', 26 | 'is_enabled', 27 | 'is_light', 28 | 'list_tags', 29 | 'set_dark_background', 30 | 'set_light_background', 31 | 'Windows', 32 | ) 33 | 34 | 35 | __author__ = '@Robpol86' 36 | __license__ = 'MIT' 37 | __version__ = '2.1.0' 38 | -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/__doc/zabbix-time.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | import sys 4 | import time 5 | import datetime 6 | import calendar 7 | import os 8 | import os.path 9 | 10 | #当天日期 11 | today = datetime.date.today() 12 | 13 | def custom_report(startTime,endTime): 14 | sheetName = time.strftime('%m%d_%H%M',startTime) + "_TO_" +time.strftime('%m%d_%H%M',endTime) 15 | print sheetName 16 | customStart = int(time.mktime(startTime)) 17 | print customStart 18 | customEnd = int(time.mktime(endTime)) 19 | print customEnd 20 | 21 | def main(): 22 | #最好加上时间类型检查 23 | argvCount = len(sys.argv) #参数个数,用于判断是生成自定义报表还是周期性报表 24 | dateFormat = "%Y-%m-%d %H:%M:%S" 25 | dateFormat = "%Y-%m-%d" 26 | today = datetime.date.today() 27 | if(argvCount == 3): 28 | #传入两个参数,生成自定义报表为:以第一参数为起始时间,第二参数为结束时间的区别报表 29 | startTime = time.strptime(sys.argv[1],dateFormat) 30 | endTime = time.strptime(sys.argv[2],dateFormat) 31 | print "startTime:",startTime 32 | print "startTime:",endTime 33 | custom_report(startTime,endTime) 34 | else: 35 | #参数个数大于2为非法情况,打印异常信息,退出报表生成 36 | usage() 37 | def usage(): 38 | print """注意时间格式强制要求: zabbix-report.py ['2012-09-01 01:12:00'] ['2012-09-01 01:12:00']""" 39 | 40 | #运行程序 41 | main() 42 | -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/w_lib/my_compare.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding=utf8 3 | """ 4 | # Author: Bill 5 | # Created Time : 2016-06-11 14:43:35 6 | 7 | # File Name: my_compare.py 8 | # Description: 9 | 10 | """ 11 | __version__ = "1.0.2" 12 | import re 13 | def my_compare(str_all,str_sub,sep_sign=None): 14 | if not sep_sign: 15 | sep_sign = ' ' 16 | str_sub_list=re.split(sep_sign, str_sub) 17 | #str_sub_list=re.split(r' ', str_sub) 18 | str_all=sep_sign+str_all+sep_sign 19 | for sub in str_sub_list: 20 | sub =sep_sign+sub+sep_sign 21 | if sub in str_all: 22 | continue 23 | else: 24 | return 0 25 | return 1 26 | 27 | 28 | if __name__ == "__main__": 29 | str_sub="to world" 30 | str1="I want to say hello world" 31 | str2="I want say hello world" 32 | str3="I want say hello wor" 33 | info=my_compare(str1,str_sub) 34 | print "ceshi:1",info 35 | info=my_compare(str2,str_sub) 36 | print "ceshi:0",info 37 | info=my_compare(str3,str_sub) 38 | print "ceshi:0",info 39 | 40 | str_sub="to_world" 41 | str1="I_want_to_say_hello_world" 42 | str2="I_want_say_hello_world" 43 | str3="I_want_say_hello_wor" 44 | info=my_compare(str1,str_sub,sep_sign='_') 45 | print "ceshi:1",info 46 | info=my_compare(str2,str_sub,sep_sign='_') 47 | print "ceshi:0",info 48 | info=my_compare(str3,str_sub,sep_sign='_') 49 | print "ceshi:0",info 50 | -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/w_lib/mylib/xlwt/ExcelFormula.py: -------------------------------------------------------------------------------- 1 | # -*- coding: windows-1252 -*- 2 | 3 | from . import ExcelFormulaParser, ExcelFormulaLexer 4 | import struct 5 | from .antlr import ANTLRException 6 | 7 | 8 | class Formula(object): 9 | __slots__ = ["__s", "__parser", "__sheet_refs", "__xcall_refs"] 10 | 11 | 12 | def __init__(self, s): 13 | try: 14 | self.__s = s 15 | lexer = ExcelFormulaLexer.Lexer(s) 16 | self.__parser = ExcelFormulaParser.Parser(lexer) 17 | self.__parser.formula() 18 | self.__sheet_refs = self.__parser.sheet_references 19 | self.__xcall_refs = self.__parser.xcall_references 20 | except ANTLRException as e: 21 | # print e 22 | raise ExcelFormulaParser.FormulaParseException("can't parse formula " + s) 23 | 24 | def get_references(self): 25 | return self.__sheet_refs, self.__xcall_refs 26 | 27 | def patch_references(self, patches): 28 | for offset, idx in patches: 29 | self.__parser.rpn = self.__parser.rpn[:offset] + struct.pack('= 100): 57 | sys.stderr.write('ERROR: percentile must be < 100. you supplied: %s\n'% percentile) 58 | value = None 59 | else: 60 | element_idx = int(len(self.sequence) * (percentile / 100.0)) 61 | self.sequence.sort() 62 | value = self.sequence[element_idx] 63 | return value 64 | 65 | if __name__ == "__main__": 66 | sequence=[2.3,4,6,10] 67 | wang = Stats(sequence) 68 | print wang.min() 69 | print wang.max() 70 | print wang.avg() 71 | -------------------------------------------------------------------------------- /ZabbixTool/scripts/template/ceshi_templates.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 3.0 4 | 2016-06-22T08:23:37Z 5 | 6 | 7 | store 8 | 9 | 10 | 11 | 67 | 68 | 69 | 70 | {ceshi_template:ceshi_status.last(#3)}<>1 71 | ceshi_status 72 | 73 | 0 74 | 4 75 | 76 | 0 77 | 78 | 79 | 80 | 81 | -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/w_lib/terminaltables/width_and_alignment.py: -------------------------------------------------------------------------------- 1 | """Functions that handle alignment, padding, widths, etc.""" 2 | 3 | import unicodedata 4 | 5 | 6 | def string_width(string): 7 | """Get the visible width of a unicode string. 8 | 9 | Some CJK unicode characters are more than one byte unlike ASCII and latin unicode characters. 10 | 11 | From: https://github.com/Robpol86/terminaltables/pull/9 12 | 13 | :param str string: String to measure. 14 | 15 | :return: String's width. 16 | :rtype: int 17 | """ 18 | # Colorclass instance. 19 | if hasattr(string, 'value_no_colors'): 20 | string = string.value_no_colors 21 | 22 | # Convert to unicode. 23 | try: 24 | decoded = string.decode('u8') 25 | except (AttributeError, UnicodeEncodeError): 26 | decoded = string 27 | 28 | width = 0 29 | for char in decoded: 30 | if unicodedata.east_asian_width(char) in ('F', 'W'): 31 | width += 2 32 | else: 33 | width += 1 34 | 35 | return width 36 | 37 | 38 | def align_and_pad_cell(string, align, size_dims): 39 | """Align a string with center/rjust/ljust and adds additional padding. 40 | 41 | :param str string: Input string to operate on. 42 | :param str align: 'left', 'right', or 'center'. 43 | :param iter size_dims: Size and dimensions. A 4-item tuple of integers representing width, height, lpad, and rpad. 44 | 45 | :return: Modified string. 46 | :rtype: str 47 | """ 48 | width, height, lpad, rpad = size_dims 49 | 50 | # Handle trailing newlines or empty strings, str.splitlines() does not satisfy. 51 | lines = string.splitlines() or [''] 52 | if string.endswith('\n'): 53 | lines.append('') 54 | 55 | # Align. 56 | if align == 'center': 57 | method = 'center' 58 | elif align == 'right': 59 | method = 'rjust' 60 | else: 61 | method = 'ljust' 62 | aligned = '\n'.join(getattr(l, method)(width + len(l) - string_width(l)) for l in lines) 63 | 64 | # Pad. 65 | padded = '\n'.join((' ' * lpad) + l + (' ' * rpad) for l in aligned.splitlines() or ['']) 66 | 67 | # Increase height. 68 | additional_padding = height - 1 - padded.count('\n') 69 | if additional_padding > 0: 70 | padded += ('\n{0}'.format(' ' * (width + lpad + rpad))) * additional_padding 71 | 72 | return padded 73 | 74 | 75 | def column_widths(table_data): 76 | """Get maximum widths of each column in the table. 77 | 78 | :param iter table_data: List of list of strings. The unpadded table data. 79 | 80 | :return: Column widths. 81 | :rtype: list 82 | """ 83 | if not table_data: 84 | return list() 85 | 86 | number_of_columns = max(len(r) for r in table_data) 87 | widths = [0] * number_of_columns 88 | 89 | for row in table_data: 90 | for i in range(len(row)): 91 | if not row[i]: 92 | continue 93 | widths[i] = max(widths[i], string_width(max(row[i].splitlines(), key=len))) 94 | 95 | return widths 96 | -------------------------------------------------------------------------------- /start.sh: -------------------------------------------------------------------------------- 1 | ######################################################################### 2 | # File Name: start.sh 3 | # Author: meetbill 4 | # mail: meetbill@163.com 5 | # Created Time: 2016-12-30 14:49:49 6 | ######################################################################### 7 | #!/bin/bash 8 | 9 | CUR_DIR=$(cd `dirname $0`; pwd) 10 | cd ${CUR_DIR} 11 | 12 | # Check if user is root 13 | if [ $(id -u) != "0" ]; then 14 | echo "Error: You must be root to run this script, please use root to install" 15 | exit 1 16 | fi 17 | 18 | ##########################################################process 19 | x='' 20 | NUM=3 21 | function ProcessBar() 22 | { 23 | x=##########$x 24 | printf "install-ZabbixTool:[%-${NUM}0s]\r" $x 25 | sleep 0.1 26 | } 27 | ##########################################################process_end 28 | g_BACKUP_DIR=/opt/ZabbixTool_oldbackup 29 | function check_dir() 30 | { 31 | if [[ -d /opt/ZabbixTool ]] 32 | then 33 | if [ ! -d ${g_BACKUP_DIR} ] 34 | then 35 | mkdir -p ${g_BACKUP_DIR} 36 | else 37 | rm -rf ${g_BACKUP_DIR} 38 | mkdir -p ${g_BACKUP_DIR} 39 | fi 40 | mv /opt/ZabbixTool ${g_BACKUP_DIR}/ 41 | cp -rf ./ZabbixTool /opt/ 42 | else 43 | cp -rf ./ZabbixTool /opt/ 44 | fi 45 | ProcessBar 46 | } 47 | function check_config() 48 | { 49 | if [[ ! -f /etc/zabbix_tool/zabbix_config.ini ]] 50 | then 51 | mkdir -p /etc/zabbix_tool 52 | cp ./ZabbixTool/lib_zabbix/etc/zabbix_config.ini /etc/zabbix_tool/ 53 | fi 54 | if [[ ! -f /etc/zabbix_tool/zabbix_setting.ini ]] 55 | then 56 | mkdir -p /etc/zabbix_tool 57 | cp ./ZabbixTool/lib_zabbix/etc/zabbix_setting.ini /etc/zabbix_tool/ 58 | fi 59 | if [[ ! -f /etc/zabbix_tool/zabbix_tool.ini ]] 60 | then 61 | mkdir -p /etc/zabbix_tool 62 | cp ./ZabbixTool/py_tool/config/zabbix_tool.ini /etc/zabbix_tool/ 63 | fi 64 | ProcessBar 65 | } 66 | function check_command() 67 | { 68 | # zabbix_api 69 | if [[ -f /usr/bin/zabbix_api ]] 70 | then 71 | unlink /usr/bin/zabbix_api 72 | ln -s /opt/ZabbixTool/lib_zabbix/zabbix_api.py /usr/bin/zabbix_api 73 | else 74 | ln -s /opt/ZabbixTool/lib_zabbix/zabbix_api.py /usr/bin/zabbix_api 75 | fi 76 | chmod +x /usr/bin/zabbix_api 77 | 78 | # zabbix_menu 79 | if [[ -f /usr/bin/zabbix_menu ]] 80 | then 81 | unlink /usr/bin/zabbix_menu 82 | ln -s /opt/ZabbixTool/main.sh /usr/bin/zabbix_menu 83 | else 84 | ln -s /opt/ZabbixTool/main.sh /usr/bin/zabbix_menu 85 | fi 86 | chmod +x /usr/bin/zabbix_menu 87 | 88 | # zabbix_tool 89 | if [[ -f /usr/bin/zabbix_tool ]] 90 | then 91 | unlink /usr/bin/zabbix_tool 92 | ln -s /opt/ZabbixTool/main.py /usr/bin/zabbix_tool 93 | else 94 | ln -s /opt/ZabbixTool/main.py /usr/bin/zabbix_tool 95 | fi 96 | chmod +x /usr/bin/zabbix_tool 97 | ProcessBar 98 | } 99 | check_dir 100 | check_config 101 | check_command 102 | echo 103 | 104 | -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/w_lib/mylib/xlwt/CreateLearningSheet.py: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------------- 2 | # Name: CreateLearningSheet 3 | # Purpose: Creates an Excel sheet of sample data. This is then "Autofitted" using the real Excel function 4 | # and then read back in and processed to work out the character mappings to be used later. 5 | # 6 | # Author: Warwick Prince Mushroom Systems International Pty. Ltd. 7 | # 8 | # Created: 3/02/12 11:56 AM 9 | #------------------------------------------------------------------------------- 10 | #!/usr/bin/env python 11 | 12 | import xlwt 13 | import sys 14 | 15 | def ExportSampleSheet(): 16 | """ 17 | Create a sample sheet format and save it to the file supplied. The user then must select all the sheets and using Excel, 18 | Autofit them and save the workbook. Then, use GenerateAFFont to read the Excel formatted sheet back in and learn from it. 19 | """ 20 | 21 | if len(sys.argv) != 2: 22 | print 'Usage: CreateLearningSheet [SampleSheet.xls]' 23 | sys.exit() 24 | 25 | # Get the workbook file name from the command line 26 | fileName = sys.argv[1] 27 | 28 | if not fileName.lower().endswith('.xls'): 29 | fileName = '%s.xls' % fileName 30 | 31 | xlWorkbook = xlwt.Workbook() 32 | 33 | s1 = xlWorkbook.add_sheet('Normal Sample UPPER') 34 | s2 = xlWorkbook.add_sheet('Normal Sample Lower') 35 | s3 = xlWorkbook.add_sheet('Normal Sample Other') 36 | s4 = xlWorkbook.add_sheet('Bold Sample UPPER') 37 | s5 = xlWorkbook.add_sheet('Bold Sample Lower') 38 | s6 = xlWorkbook.add_sheet('Bold Sample Other') 39 | 40 | # Normal UPPER 41 | for row in xrange(0, 2): 42 | letterValue = 65 43 | for col in range(0, 51, 2): 44 | letter = chr(letterValue) 45 | s1.write(row, col, letter*10) 46 | s1.write(row, col+1, letter*100) 47 | letterValue += 1 48 | 49 | # Normal lower 50 | for row in xrange(0, 2): 51 | letterValue = 97 52 | for col in range(0, 51, 2): 53 | letter = chr(letterValue) 54 | s2.write(row, col, letter*10) 55 | s2.write(row, col+1, letter*100) 56 | letterValue += 1 57 | 58 | # Normal Other 59 | for row in xrange(0, 2): 60 | letterValue = 32 61 | for col in range(0, 66, 2): 62 | letter = chr(letterValue) 63 | s3.write(row, col, letter*10) 64 | s3.write(row, col+1, letter*100) 65 | letterValue += 1 66 | 67 | style = xlwt.Style.XFStyle() 68 | style.font.bold = True 69 | 70 | # Bold UPPER 71 | for row in xrange(0, 2): 72 | letterValue = 65 73 | for col in range(0, 51, 2): 74 | letter = chr(letterValue) 75 | s4.write(row, col, letter*10, style) 76 | s4.write(row, col+1, letter*100, style) 77 | letterValue += 1 78 | 79 | # Bold lower 80 | for row in xrange(0, 2): 81 | letterValue = 97 82 | for col in range(0, 51, 2): 83 | letter = chr(letterValue) 84 | s5.write(row, col, letter*10, style) 85 | s5.write(row, col+1, letter*100, style) 86 | letterValue += 1 87 | 88 | # Bold Other 89 | for row in xrange(0, 2): 90 | letterValue = 32 91 | for col in range(0, 66, 2): 92 | letter = chr(letterValue) 93 | s6.write(row, col, letter*10, style) 94 | s6.write(row, col+1, letter*100, style) 95 | letterValue += 1 96 | 97 | try: 98 | xlWorkbook.save(fileName) 99 | except IOError: 100 | print 'Failed to save filename "%s"' % fileName 101 | 102 | if __name__ == '__main__': 103 | ExportSampleSheet() 104 | -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/w_lib/colorclass/parse.py: -------------------------------------------------------------------------------- 1 | """Parse color markup tags into ANSI escape sequences.""" 2 | 3 | import re 4 | 5 | from colorclass.codes import ANSICodeMapping, BASE_CODES 6 | 7 | CODE_GROUPS = ( 8 | tuple(set(str(i) for i in BASE_CODES.values() if i and (40 <= i <= 49 or 100 <= i <= 109))), # bg colors 9 | tuple(set(str(i) for i in BASE_CODES.values() if i and (30 <= i <= 39 or 90 <= i <= 99))), # fg colors 10 | ('1', '22'), ('2', '22'), ('3', '23'), ('4', '24'), ('5', '25'), ('6', '26'), ('7', '27'), ('8', '28'), ('9', '29'), 11 | ) 12 | RE_ANSI = re.compile(r'(\033\[([\d;]+)m)') 13 | RE_COMBINE = re.compile(r'\033\[([\d;]+)m\033\[([\d;]+)m') 14 | RE_SPLIT = re.compile(r'(\033\[[\d;]+m)') 15 | 16 | 17 | def prune_overridden(ansi_string): 18 | """Remove color codes that are rendered ineffective by subsequent codes in one escape sequence then sort codes. 19 | 20 | :param str ansi_string: Incoming ansi_string with ANSI color codes. 21 | 22 | :return: Color string with pruned color sequences. 23 | :rtype: str 24 | """ 25 | multi_seqs = set(p for p in RE_ANSI.findall(ansi_string) if ';' in p[1]) # Sequences with multiple color codes. 26 | 27 | for escape, codes in multi_seqs: 28 | r_codes = list(reversed(codes.split(';'))) 29 | 30 | # Nuke everything before {/all}. 31 | try: 32 | r_codes = r_codes[:r_codes.index('0') + 1] 33 | except ValueError: 34 | pass 35 | 36 | # Thin out groups. 37 | for group in CODE_GROUPS: 38 | for pos in reversed([i for i, n in enumerate(r_codes) if n in group][1:]): 39 | r_codes.pop(pos) 40 | 41 | # Done. 42 | reduced_codes = ';'.join(sorted(r_codes, key=int)) 43 | if codes != reduced_codes: 44 | ansi_string = ansi_string.replace(escape, '\033[' + reduced_codes + 'm') 45 | 46 | return ansi_string 47 | 48 | 49 | def parse_input(tagged_string, disable_colors, keep_tags): 50 | """Perform the actual conversion of tags to ANSI escaped codes. 51 | 52 | Provides a version of the input without any colors for len() and other methods. 53 | 54 | :param str tagged_string: The input unicode value. 55 | :param bool disable_colors: Strip all colors in both outputs. 56 | :param bool keep_tags: Skip parsing curly bracket tags into ANSI escape sequences. 57 | 58 | :return: 2-item tuple. First item is the parsed output. Second item is a version of the input without any colors. 59 | :rtype: tuple 60 | """ 61 | codes = ANSICodeMapping(tagged_string) 62 | output_colors = getattr(tagged_string, 'value_colors', tagged_string) 63 | 64 | # Convert: '{b}{red}' -> '\033[1m\033[31m' 65 | if not keep_tags: 66 | for tag, replacement in (('{' + k + '}', '' if v is None else '\033[%dm' % v) for k, v in codes.items()): 67 | output_colors = output_colors.replace(tag, replacement) 68 | 69 | # Strip colors. 70 | output_no_colors = RE_ANSI.sub('', output_colors) 71 | if disable_colors: 72 | return output_no_colors, output_no_colors 73 | 74 | # Combine: '\033[1m\033[31m' -> '\033[1;31m' 75 | while True: 76 | simplified = RE_COMBINE.sub(r'\033[\1;\2m', output_colors) 77 | if simplified == output_colors: 78 | break 79 | output_colors = simplified 80 | 81 | # Prune: '\033[31;32;33;34;35m' -> '\033[35m' 82 | output_colors = prune_overridden(output_colors) 83 | 84 | # Deduplicate: '\033[1;mT\033[1;mE\033[1;mS\033[1;mT' -> '\033[1;mTEST' 85 | previous_escape = None 86 | segments = list() 87 | for item in (i for i in RE_SPLIT.split(output_colors) if i): 88 | if RE_SPLIT.match(item): 89 | if item != previous_escape: 90 | segments.append(item) 91 | previous_escape = item 92 | else: 93 | segments.append(item) 94 | output_colors = ''.join(segments) 95 | 96 | return output_colors, output_no_colors 97 | -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/w_lib/mylib/xlwt/ExcelFormulaLexer.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | # -*- coding: windows-1252 -*- 3 | 4 | from .antlr import EOF, CommonToken as Tok, TokenStream, TokenStreamException 5 | from . import ExcelFormulaParser 6 | from re import compile as recompile, LOCALE, IGNORECASE, VERBOSE 7 | 8 | 9 | int_const_pattern = r"\d+\b" 10 | flt_const_pattern = r""" 11 | (?: 12 | (?: \d* \. \d+ ) # .1 .12 .123 etc 9.1 etc 98.1 etc 13 | | 14 | (?: \d+ \. ) # 1. 12. 123. etc 15 | ) 16 | # followed by optional exponent part 17 | (?: [Ee] [+-]? \d+ ) ? 18 | """ 19 | str_const_pattern = r'"(?:[^"]|"")*"' 20 | #range2d_pattern = recompile(r"\$?[A-I]?[A-Z]\$?\d+:\$?[A-I]?[A-Z]\$?\d+" 21 | ref2d_r1c1_pattern = r"[Rr]0*[1-9][0-9]*[Cc]0*[1-9][0-9]*" 22 | ref2d_pattern = r"\$?[A-I]?[A-Z]\$?0*[1-9][0-9]*" 23 | true_pattern = r"TRUE\b" 24 | false_pattern = r"FALSE\b" 25 | if_pattern = r"IF\b" 26 | choose_pattern = r"CHOOSE\b" 27 | name_pattern = r"\w[\.\w]*" 28 | quotename_pattern = r"'(?:[^']|'')*'" #### It's essential that this bracket be non-grouping. 29 | ne_pattern = r"<>" 30 | ge_pattern = r">=" 31 | le_pattern = r"<=" 32 | 33 | pattern_type_tuples = ( 34 | (flt_const_pattern, ExcelFormulaParser.NUM_CONST), 35 | (int_const_pattern, ExcelFormulaParser.INT_CONST), 36 | (str_const_pattern, ExcelFormulaParser.STR_CONST), 37 | # (range2d_pattern , ExcelFormulaParser.RANGE2D), 38 | (ref2d_r1c1_pattern, ExcelFormulaParser.REF2D_R1C1), 39 | (ref2d_pattern , ExcelFormulaParser.REF2D), 40 | (true_pattern , ExcelFormulaParser.TRUE_CONST), 41 | (false_pattern , ExcelFormulaParser.FALSE_CONST), 42 | (if_pattern , ExcelFormulaParser.FUNC_IF), 43 | (choose_pattern , ExcelFormulaParser.FUNC_CHOOSE), 44 | (name_pattern , ExcelFormulaParser.NAME), 45 | (quotename_pattern, ExcelFormulaParser.QUOTENAME), 46 | (ne_pattern, ExcelFormulaParser.NE), 47 | (ge_pattern, ExcelFormulaParser.GE), 48 | (le_pattern, ExcelFormulaParser.LE), 49 | ) 50 | 51 | _re = recompile( 52 | '(' + ')|('.join([i[0] for i in pattern_type_tuples]) + ')', 53 | VERBOSE+LOCALE+IGNORECASE) 54 | 55 | _toktype = [None] + [i[1] for i in pattern_type_tuples] 56 | # need dummy at start because re.MatchObject.lastindex counts from 1 57 | 58 | single_char_lookup = { 59 | '=': ExcelFormulaParser.EQ, 60 | '<': ExcelFormulaParser.LT, 61 | '>': ExcelFormulaParser.GT, 62 | '+': ExcelFormulaParser.ADD, 63 | '-': ExcelFormulaParser.SUB, 64 | '*': ExcelFormulaParser.MUL, 65 | '/': ExcelFormulaParser.DIV, 66 | ':': ExcelFormulaParser.COLON, 67 | ';': ExcelFormulaParser.SEMICOLON, 68 | ',': ExcelFormulaParser.COMMA, 69 | '(': ExcelFormulaParser.LP, 70 | ')': ExcelFormulaParser.RP, 71 | '&': ExcelFormulaParser.CONCAT, 72 | '%': ExcelFormulaParser.PERCENT, 73 | '^': ExcelFormulaParser.POWER, 74 | '!': ExcelFormulaParser.BANG, 75 | } 76 | 77 | class Lexer(TokenStream): 78 | def __init__(self, text): 79 | self._text = text[:] 80 | self._pos = 0 81 | self._line = 0 82 | 83 | def isEOF(self): 84 | return len(self._text) <= self._pos 85 | 86 | def curr_ch(self): 87 | return self._text[self._pos] 88 | 89 | def next_ch(self, n = 1): 90 | self._pos += n 91 | 92 | def is_whitespace(self): 93 | return self.curr_ch() in " \t\n\r\f\v" 94 | 95 | def match_pattern(self): 96 | m = _re.match(self._text, self._pos) 97 | if not m: 98 | return None 99 | self._pos = m.end(0) 100 | return Tok(type = _toktype[m.lastindex], text = m.group(0), col = m.start(0) + 1) 101 | 102 | def nextToken(self): 103 | # skip whitespace 104 | while not self.isEOF() and self.is_whitespace(): 105 | self.next_ch() 106 | if self.isEOF(): 107 | return Tok(type = EOF) 108 | # first, try to match token with 2 or more chars 109 | t = self.match_pattern() 110 | if t: 111 | return t 112 | # second, we want 1-char tokens 113 | te = self.curr_ch() 114 | try: 115 | ty = single_char_lookup[te] 116 | except KeyError: 117 | raise TokenStreamException( 118 | "Unexpected char %r in column %u." % (self.curr_ch(), self._pos)) 119 | self.next_ch() 120 | return Tok(type=ty, text=te, col=self._pos) 121 | 122 | if __name__ == '__main__': 123 | try: 124 | for t in Lexer(""" 1.23 456 "abcd" R2C2 a1 iv65536 true false if choose a_name 'qname' <> >= <= """): 125 | print(t) 126 | except TokenStreamException as e: 127 | print("error:", e) 128 | -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/w_lib/mylib/xlwt/GenerateAFFont.py: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------------- 2 | # Name: GenerateAFFont 3 | # Purpose: Opens the learning sheet, processes it and returns a dict to cut and paste into 4 | # a new AFFont class for your font 5 | # 6 | # Author: Warwick Prince 7 | # 8 | # Created: 3/02/12 2:22 PM 9 | # Copyright: (c) 2012 Mushroom Systems International Pty. Ltd. 10 | # Licence: You are free to use this code in any way you see fit - but you must retain this license message 11 | #------------------------------------------------------------------------------- 12 | #!/usr/bin/env python 13 | 14 | import xlrd 15 | import sys 16 | from pprint import pprint 17 | 18 | def GenerateAFFont(): 19 | """ 20 | Open up the sampler sheet supplied, read in the sizes and determine the factors from there.. 21 | """ 22 | if len(sys.argv) != 2: 23 | print 'Usage: GenerateAFFont [SampleSheet.xls]' 24 | sys.exit() 25 | 26 | # Get the workbook file name from the command line 27 | fileName = sys.argv[1] 28 | 29 | if not fileName.lower().endswith('.xls'): 30 | fileName = '%s.xls' % fileName 31 | 32 | try: 33 | sampleBook = xlrd.open_workbook(fileName, formatting_info=True) 34 | except IOError: 35 | print 'Failed to open Excel sample sheet %s' % fileName 36 | sys.exit() 37 | 38 | if sampleBook._all_sheets_count is not 6: 39 | print 'Invalid Sample Workbook format - must be generated by CreateLearningSheet and contain 6 Sheets' 40 | sys.exit() 41 | 42 | # Read it in and process it 43 | charMapping = {} 44 | gutter = 190 45 | creepDivisor = 50.00 46 | 47 | # Normal UPPER 48 | sheet = sampleBook.sheet_by_index(0) 49 | letterValue = 65 50 | for col in range(0, 51, 2): 51 | width10 = (sheet.colinfo_map[col].width - gutter) / 10.00 52 | width100 = (sheet.colinfo_map[col+1].width - gutter) / 100.00 53 | creepFactor = round((width10 - width100) / creepDivisor, 4) 54 | letter = chr(letterValue) 55 | charMapping[letter] = [(round(width10, 4), creepFactor)] 56 | letterValue += 1 57 | 58 | # Normal lower 59 | sheet = sampleBook.sheet_by_index(1) 60 | letterValue = 97 61 | for col in range(0, 51, 2): 62 | width10 = (sheet.colinfo_map[col].width - gutter) / 10.00 63 | width100 = (sheet.colinfo_map[col+1].width - gutter) / 100.00 64 | creepFactor = round((width10 - width100) / creepDivisor, 4) 65 | letter = chr(letterValue) 66 | charMapping[letter] = [(round(width10, 4), creepFactor)] 67 | letterValue += 1 68 | 69 | # Normal Other 70 | sheet = sampleBook.sheet_by_index(2) 71 | letterValue = 32 72 | for col in range(0, 66, 2): 73 | width10 = (sheet.colinfo_map[col].width - gutter) / 10.00 74 | width100 = (sheet.colinfo_map[col+1].width - gutter) / 100.00 75 | creepFactor = round((width10 - width100) / creepDivisor, 4) 76 | letter = chr(letterValue) 77 | charMapping[letter] = [(round(width10, 4), creepFactor)] 78 | letterValue += 1 79 | 80 | # Bold UPPER 81 | sheet = sampleBook.sheet_by_index(3) 82 | letterValue = 65 83 | for col in range(0, 51, 2): 84 | width10 = (sheet.colinfo_map[col].width - gutter) / 10.00 85 | width100 = (sheet.colinfo_map[col+1].width - gutter) / 100.00 86 | creepFactor = round((width10 - width100) / creepDivisor, 4) 87 | letter = chr(letterValue) 88 | charMapping[letter].append((round(width10, 4), creepFactor)) 89 | letterValue += 1 90 | 91 | # Normal lower 92 | sheet = sampleBook.sheet_by_index(4) 93 | letterValue = 97 94 | for col in range(0, 51, 2): 95 | width10 = (sheet.colinfo_map[col].width - gutter) / 10.00 96 | width100 = (sheet.colinfo_map[col+1].width - gutter) / 100.00 97 | creepFactor = round((width10 - width100) / creepDivisor, 4) 98 | letter = chr(letterValue) 99 | charMapping[letter].append((round(width10, 4), creepFactor)) 100 | letterValue += 1 101 | 102 | # Normal Other 103 | sheet = sampleBook.sheet_by_index(5) 104 | letterValue = 32 105 | for col in range(0, 66, 2): 106 | width10 = (sheet.colinfo_map[col].width - gutter) / 10.00 107 | width100 = (sheet.colinfo_map[col+1].width - gutter) / 100.00 108 | creepFactor = round((width10 - width100) / creepDivisor, 4) 109 | letter = chr(letterValue) 110 | charMapping[letter].append((round(width10, 4), creepFactor)) 111 | letterValue += 1 112 | 113 | print 114 | print '=' * 40 115 | pprint(charMapping) 116 | print '=' * 40 117 | print 118 | print 'CUT the ^above^ dict and paste it into your new AFFont class code where indicated' 119 | 120 | if __name__ == '__main__': 121 | GenerateAFFont() 122 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Zabbix_manager(server) 2 | 3 | > * [Zabbix 管理工具手册 (GitHub)(推荐)](https://github.com/BillWang139967/zabbix_manager/wiki)------------------- 优先更新 4 | > * [Zabbix 管理工具手册 (W3cschool)](http://www.w3cschool.cn/zabbix_manager/) 5 | 6 | ## Supported versions 7 | 8 | > * 版本高于 Zabbix 3.0 9 | 10 | ## 功能 11 | 12 | **Monitor** 13 | 14 | When we plan to monitor, we must first create a host group, and then import some template, and finally add some hosts, zabbix_manager is a better choice 15 | 16 | **Alarm** 17 | 18 | When we plan to use zabbix alarm . 19 | > * first, we need to add the alarm mode. 20 | > * the second, we need to create user groups and users. 21 | > * the third, the user configuration of alarms. 22 | > * fourth, create action 23 | 24 | **Report** 25 | 26 | Daily we need to export the report, use zabbix manager can export xls file using zabbix_manager will greatly save us time 27 | 28 | ## Zabbix_api version 29 | 30 | * V1.4 31 | * v1.4.04,2017-11-27 [更新] 更新可用性报表计算方法 [详细](https://github.com/BillWang139967/zabbix_manager/wiki/app_report_available) 32 | * v1.4.03,2017-10-20 [更新] 添加 dev_hosts_info 判断返回值个数 33 | * v1.4.02,2017-10-20 [修复] 修复 Zabbix 日常使用报表因添加数据单位导致排序无法正常运行问题 34 | * v1.4.01,2017-09-23 [更新] 更新 Zabbix_api_lib 35 | * V1.3[Release 下载](https://codeload.github.com/BillWang139967/zabbix_manager/tar.gz/v1.3) 36 | * v1.3.04,2017-09-22 [更新] 添加 `dev_hosts_device` 输出每台机器的指定挂载目录的使用信息 37 | * v1.3.03,2017-09-21 [更新] 添加 `dev_hosts_info` 输出常用监控项信息(可以自己定制), 优化部分程序 38 | * v1.3.02,2017-09-16 [更新] 更新程序调用时 `issues` 返回值 39 | * v1.3.01,2017-09-15 [更新] 增加 `item_list`方法,`issues` 方法输出添加`item key`信息 40 | * V1.2 41 | * v1.2.16,2017-09-13 [更新] `host_get` 输出项中,模板由之前获取的 `host(Template name)` 修改为 `name(Visible name)` 42 | * v1.2.15,2017-09-11 [更新] `--hostid/--hostgroupid` 参数可以通过直接输入`主机名 / 主机组名`进行获取主机列表,检查配置文件不存在时会使用本目录下`etc`下的配置文件 43 | * v1.2.13,2017-09-09 [更新] agent 自动注册功能修改参数,增加 hostmeta 参数 44 | * v1.2.12,2017-08-30 [更新] 报表 [report_key](https://github.com/BillWang139967/zabbix_manager/wiki/app_report_key) 修改为使用 key 的正则表达式进行搜索 45 | * v1.2.11,2017-08-29 [更新] item_get 只输出已启用的监控项 [增加] 增加 [report_key](https://github.com/BillWang139967/zabbix_manager/wiki/app_report_key) 46 | * v1.2.10,2017-08-26 [修复] 导出报表时设置 --table `SingleTable` 没有定义的错误 47 | * v1.2.9,2017-08-01 [更新] 增加 application_get 获取 application 列表功能 [增加] 增加 [report_app](https://github.com/BillWang139967/zabbix_manager/wiki/app_report_app) 48 | * v1.2.8,2017-07-28 [更新] 增加 3 次重试机制 49 | * v1.2.7,2017-07-25 [更新] 导出报表时,只计算 item_type 为 0(浮点数) 或者 3(整数) 的数据,其他 item 返回"-1" (2) 执行命令时会输出 zabbix server 的版本号 50 | * v1.2.6,2017-07-21 [更新] 1 [XLSWriter](https://github.com/BillWang139967/XLSWriter) 使之可控制是否显示 logo (2) 可通过配置以适应 apache 搭建的 zabbix server 51 | * v1.2.4,2017-06-15 [增加] 输出日常使用报表时会在值后面加上单位 (K/M/G 也会自动进行换算) 52 | * v1.2.3,2017-04-04 [增加] -sign 参数(设置搜索分割符) 53 | * v1.2.1,2016-12-25 [增加] 对主机批量 link 、clear 模板操作 54 | * v1.2.0,2016-11-27 [修改] `zabbix_api` 调用方式(报表类函数不变) 55 | * V1.1 56 | * v1.1.7,2016-11-25 优化程序 57 | * v1.1.6,2016-11-08 Add 通过 profile 参数选择配置文件中不同的 `section` 58 | * v1.1.5,2016-10-24 Add `report_available2` 可以对特定 item 进行输出,除报表项外,其他函数统一输出函数 59 | * v1.1.4,2016-10-24 Add `issues`获取最近问题 60 | * v1.1.3,2016-09-09 Add report_available2, 可设置排序 61 | * v1.1.2,2016-09-05 Add zabbix_manager gui 62 | * v1.1.1,2016-08-22 Add mysql_quota 63 | * v1.1.0,2016-07-14 Release 1.1.0 64 | * V1.0 65 | * v1.0.8,2016-07-13 Add report 66 | * v1.0.6,2016-06-23 Add rule and discovery manage 67 | * v1.0.5,2016-06-19 Add mediatype manage 68 | * v1.0.4,2016-06-18 Add usergroup manage 69 | * v1.0.3,2016-06-11 Add history_report 70 | * v1.0.2,2016-06-03 Modify the command line in interactive mode 71 | * v1.0.1,2016-04-16 First edit 72 | 73 | ## 参加步骤 74 | 75 | * 在 GitHub 上 `fork` 到自己的仓库,然后 `clone` 到本地,并设置用户信息。 76 | ``` 77 | $ git clone https://github.com/BillWang139967/zabbix_manager.git 78 | $ cd zabbix_manager 79 | $ git config user.name "yourname" 80 | $ git config user.email "your email" 81 | ``` 82 | * 修改代码后提交,并推送到自己的仓库。 83 | ``` 84 | $ #do some change on the content 85 | $ git commit -am "Fix issue #1: change helo to hello" 86 | $ git push 87 | ``` 88 | * 在 GitHub 网站上提交 pull request。 89 | * 定期使用项目仓库内容更新自己仓库内容。 90 | ``` 91 | $ git remote add upstream https://github.com/BillWang139967/zabbix_manager.git 92 | $ git fetch upstream 93 | $ git checkout master 94 | $ git rebase upstream/master 95 | $ git push -f origin master 96 | ``` 97 | ## 相关链接 98 | 99 | > * zabbix 安装 -------------------------------------------------[zabbix_install](https://github.com/BillWang139967/zabbix_install) 100 | > * zabbix 报警工具 ---------------------------------------------[zabbix_alert](https://github.com/BillWang139967/zabbix_alert) 101 | > * zabbix 常用模板 ---------------------------------------------[zabbix_templates](https://github.com/BillWang139967/zabbix_templates) 102 | > * 导出报表工具 -----------------------------------------------[XLSWriter](https://github.com/BillWang139967/XLSWriter) 103 | > * linux 终端表格 ----------------------------------------------[linux_terminal](https://github.com/BillWang139967/linux_terminal) 104 | > * shell 菜单工具 ----------------------------------------------[shell_menu](https://github.com/BillWang139967/shell_menu) 105 | 106 | ## 小额捐款 107 | 108 | 如果觉得 `zabbix_manager` 对您有帮助,可以请笔者喝杯咖啡 109 | 110 | ![Screenshot](images/5.jpg) 111 | 112 | ## 致谢 113 | 114 | 1. 感谢南非蜘蛛的指导 115 | -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/w_lib/BLog.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding=utf8 3 | """ 4 | # Author: Bill 5 | # Created Time : 2016-08-01 10:59:26 6 | 7 | # File Name: w.py 8 | # Description: 9 | 10 | """ 11 | import sys 12 | import logging 13 | from logging.handlers import RotatingFileHandler 14 | import os 15 | 16 | #{{{class ColoredFormatter 17 | class ColoredFormatter(logging.Formatter): 18 | '''A colorful formatter.''' 19 | 20 | def __init__(self, fmt = None, datefmt = None): 21 | logging.Formatter.__init__(self, fmt, datefmt) 22 | # Color escape string 23 | COLOR_RED='\033[1;31m' 24 | COLOR_GREEN='\033[1;32m' 25 | COLOR_YELLOW='\033[1;33m' 26 | COLOR_BLUE='\033[1;34m' 27 | COLOR_PURPLE='\033[1;35m' 28 | COLOR_CYAN='\033[1;36m' 29 | COLOR_GRAY='\033[1;37m' 30 | COLOR_WHITE='\033[1;38m' 31 | COLOR_RESET='\033[1;0m' 32 | 33 | # Define log color 34 | self.LOG_COLORS = { 35 | 'DEBUG': '%s', 36 | 'INFO': COLOR_GREEN + '%s' + COLOR_RESET, 37 | 'WARNING': COLOR_YELLOW + '%s' + COLOR_RESET, 38 | 'ERROR': COLOR_RED + '%s' + COLOR_RESET, 39 | 'CRITICAL': COLOR_RED + '%s' + COLOR_RESET, 40 | 'EXCEPTION': COLOR_RED + '%s' + COLOR_RESET, 41 | } 42 | 43 | def format(self, record): 44 | level_name = record.levelname 45 | msg = logging.Formatter.format(self, record) 46 | 47 | return self.LOG_COLORS.get(level_name, '%s') % msg 48 | #}}} 49 | #{{{class Log 50 | class Log(object): 51 | 52 | ''' 53 | log 54 | ''' 55 | def __init__(self, filename, level="debug", logid="qiueer", mbs=20, count=10, is_console=True): 56 | ''' 57 | mbs: how many MB 58 | count: the count of remain 59 | ''' 60 | try: 61 | self._level = level 62 | #print "init,level:",level,"\t","get_map_level:",self._level 63 | self._filename = filename 64 | self._logid = logid 65 | 66 | self._logger = logging.getLogger(self._logid) 67 | 68 | 69 | if not len(self._logger.handlers): 70 | self._logger.setLevel(self.get_map_level(self._level)) 71 | 72 | fmt = '[%(asctime)s] %(levelname)s\n%(message)s' 73 | datefmt = '%Y-%m-%d %H:%M:%S' 74 | formatter = logging.Formatter(fmt, datefmt) 75 | 76 | maxBytes = int(mbs) * 1024 * 1024 77 | file_handler = RotatingFileHandler(self._filename, mode='a',maxBytes=maxBytes,backupCount=count) 78 | self._logger.setLevel(self.get_map_level(self._level)) 79 | file_handler.setFormatter(formatter) 80 | self._logger.addHandler(file_handler) 81 | 82 | if is_console == True: 83 | stream_handler = logging.StreamHandler(sys.stderr) 84 | console_formatter = ColoredFormatter(fmt, datefmt) 85 | stream_handler.setFormatter(console_formatter) 86 | self._logger.addHandler(stream_handler) 87 | 88 | except Exception as expt: 89 | print expt 90 | 91 | def tolog(self, msg, level=None): 92 | try: 93 | level = level if level else self._level 94 | level = str(level).lower() 95 | level = self.get_map_level(level) 96 | if level == logging.DEBUG: 97 | self._logger.debug(msg) 98 | if level == logging.INFO: 99 | self._logger.info(msg) 100 | if level == logging.WARN: 101 | self._logger.warn(msg) 102 | if level == logging.ERROR: 103 | self._logger.error(msg) 104 | if level == logging.CRITICAL: 105 | self._logger.critical(msg) 106 | except Exception as expt: 107 | print expt 108 | 109 | def debug(self,msg): 110 | self.tolog(msg, level="debug") 111 | 112 | def info(self,msg): 113 | self.tolog(msg, level="info") 114 | 115 | def warn(self,msg): 116 | self.tolog(msg, level="warn") 117 | 118 | def error(self,msg): 119 | self.tolog(msg, level="error") 120 | 121 | def critical(self,msg): 122 | self.tolog(msg, level="critical") 123 | 124 | def get_map_level(self,level="debug"): 125 | level = str(level).lower() 126 | #print "get_map_level:",level 127 | if level == "debug": 128 | return logging.DEBUG 129 | if level == "info": 130 | return logging.INFO 131 | if level == "warn": 132 | return logging.WARN 133 | if level == "error": 134 | return logging.ERROR 135 | if level == "critical": 136 | return logging.CRITICAL 137 | #}}} 138 | if __name__ == "__main__": 139 | from BLog import Log 140 | debug=False 141 | logpath = "/tmp/test.log" 142 | logger = Log(logpath,level="debug",is_console=debug, mbs=5, count=5) 143 | 144 | 145 | logstr="helloworld" 146 | logger.error(logstr) 147 | logger.info(logstr) 148 | logger.warn(logstr) 149 | -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/w_lib/mylib/xlwt/Utils.py: -------------------------------------------------------------------------------- 1 | # see the xlwt.license module for details of licensing. 2 | 3 | # Utilities for work with reference to cells and with sheetnames 4 | 5 | import re 6 | from .ExcelMagic import MAX_ROW, MAX_COL 7 | from .compat import xrange 8 | 9 | _re_cell_ex = re.compile(r"(\$?)([A-I]?[A-Z])(\$?)(\d+)", re.IGNORECASE) 10 | _re_row_range = re.compile(r"\$?(\d+):\$?(\d+)") 11 | _re_col_range = re.compile(r"\$?([A-I]?[A-Z]):\$?([A-I]?[A-Z])", re.IGNORECASE) 12 | _re_cell_range = re.compile(r"\$?([A-I]?[A-Z]\$?\d+):\$?([A-I]?[A-Z]\$?\d+)", re.IGNORECASE) 13 | _re_cell_ref = re.compile(r"\$?([A-I]?[A-Z]\$?\d+)", re.IGNORECASE) 14 | 15 | 16 | def col_by_name(colname): 17 | """'A' -> 0, 'Z' -> 25, 'AA' -> 26, etc 18 | """ 19 | col = 0 20 | power = 1 21 | for i in xrange(len(colname)-1, -1, -1): 22 | ch = colname[i] 23 | col += (ord(ch) - ord('A') + 1) * power 24 | power *= 26 25 | return col - 1 26 | 27 | 28 | def cell_to_rowcol(cell): 29 | """Convert an Excel cell reference string in A1 notation 30 | to numeric row/col notation. 31 | 32 | Returns: row, col, row_abs, col_abs 33 | 34 | """ 35 | m = _re_cell_ex.match(cell) 36 | if not m: 37 | raise Exception("Ill-formed single_cell reference: %s" % cell) 38 | col_abs, col, row_abs, row = m.groups() 39 | row_abs = bool(row_abs) 40 | col_abs = bool(col_abs) 41 | row = int(row) - 1 42 | col = col_by_name(col.upper()) 43 | return row, col, row_abs, col_abs 44 | 45 | 46 | def cell_to_rowcol2(cell): 47 | """Convert an Excel cell reference string in A1 notation 48 | to numeric row/col notation. 49 | 50 | Returns: row, col 51 | 52 | """ 53 | m = _re_cell_ex.match(cell) 54 | if not m: 55 | raise Exception("Error in cell format") 56 | col_abs, col, row_abs, row = m.groups() 57 | # Convert base26 column string to number 58 | # All your Base are belong to us. 59 | row = int(row) - 1 60 | col = col_by_name(col.upper()) 61 | return row, col 62 | 63 | 64 | def rowcol_to_cell(row, col, row_abs=False, col_abs=False): 65 | """Convert numeric row/col notation to an Excel cell reference string in 66 | A1 notation. 67 | 68 | """ 69 | assert 0 <= row < MAX_ROW # MAX_ROW counts from 1 70 | assert 0 <= col < MAX_COL # MAX_COL counts from 1 71 | d = col // 26 72 | m = col % 26 73 | chr1 = "" # Most significant character in AA1 74 | if row_abs: 75 | row_abs = '$' 76 | else: 77 | row_abs = '' 78 | if col_abs: 79 | col_abs = '$' 80 | else: 81 | col_abs = '' 82 | if d > 0: 83 | chr1 = chr(ord('A') + d - 1) 84 | chr2 = chr(ord('A') + m) 85 | # Zero index to 1-index 86 | return col_abs + chr1 + chr2 + row_abs + str(row + 1) 87 | 88 | def rowcol_pair_to_cellrange(row1, col1, row2, col2, 89 | row1_abs=False, col1_abs=False, row2_abs=False, col2_abs=False): 90 | """Convert two (row,column) pairs 91 | into a cell range string in A1:B2 notation. 92 | 93 | Returns: cell range string 94 | """ 95 | assert row1 <= row2 96 | assert col1 <= col2 97 | return ( 98 | rowcol_to_cell(row1, col1, row1_abs, col1_abs) 99 | + ":" 100 | + rowcol_to_cell(row2, col2, row2_abs, col2_abs) 101 | ) 102 | 103 | def cellrange_to_rowcol_pair(cellrange): 104 | """Convert cell range string in A1 notation to numeric row/col 105 | pair. 106 | 107 | Returns: row1, col1, row2, col2 108 | 109 | """ 110 | cellrange = cellrange.upper() 111 | # Convert a row range: '1:3' 112 | res = _re_row_range.match(cellrange) 113 | if res: 114 | row1 = int(res.group(1)) - 1 115 | col1 = 0 116 | row2 = int(res.group(2)) - 1 117 | col2 = -1 118 | return row1, col1, row2, col2 119 | # Convert a column range: 'A:A' or 'B:G'. 120 | # A range such as A:A is equivalent to A1:A16384, so add rows as required 121 | res = _re_col_range.match(cellrange) 122 | if res: 123 | col1 = col_by_name(res.group(1).upper()) 124 | row1 = 0 125 | col2 = col_by_name(res.group(2).upper()) 126 | row2 = -1 127 | return row1, col1, row2, col2 128 | # Convert a cell range: 'A1:B7' 129 | res = _re_cell_range.match(cellrange) 130 | if res: 131 | row1, col1 = cell_to_rowcol2(res.group(1)) 132 | row2, col2 = cell_to_rowcol2(res.group(2)) 133 | return row1, col1, row2, col2 134 | # Convert a cell reference: 'A1' or 'AD2000' 135 | res = _re_cell_ref.match(cellrange) 136 | if res: 137 | row1, col1 = cell_to_rowcol2(res.group(1)) 138 | return row1, col1, row1, col1 139 | raise Exception("Unknown cell reference %s" % (cellrange)) 140 | 141 | 142 | def cell_to_packed_rowcol(cell): 143 | """ pack row and column into the required 4 byte format """ 144 | row, col, row_abs, col_abs = cell_to_rowcol(cell) 145 | if col >= MAX_COL: 146 | raise Exception("Column %s greater than IV in formula" % cell) 147 | if row >= MAX_ROW: # this for BIFF8. for BIFF7 available 2^14 148 | raise Exception("Row %s greater than %d in formula" % (cell, MAX_ROW)) 149 | col |= int(not row_abs) << 15 150 | col |= int(not col_abs) << 14 151 | return row, col 152 | 153 | # === sheetname functions === 154 | 155 | def valid_sheet_name(sheet_name): 156 | if sheet_name == u"" or sheet_name[0] == u"'" or len(sheet_name) > 31: 157 | return False 158 | for c in sheet_name: 159 | if c in u"[]:\\?/*\x00": 160 | return False 161 | return True 162 | 163 | def quote_sheet_name(unquoted_sheet_name): 164 | if not valid_sheet_name(unquoted_sheet_name): 165 | raise Exception( 166 | 'attempt to quote an invalid worksheet name %r' % unquoted_sheet_name) 167 | return u"'" + unquoted_sheet_name.replace(u"'", u"''") + u"'" 168 | -------------------------------------------------------------------------------- /ZabbixTool/main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding=utf8 3 | """ 4 | # Author: Bill 5 | # Created Time : 2016-10-25 10:01:13 6 | # Update Time : 2018-02-13 18:18:23 7 | 8 | # File Name: main.py 9 | # Description: 10 | 11 | """ 12 | __version__ = "1.0.3" 13 | import sys 14 | import os 15 | root_path = os.path.split(os.path.realpath(__file__))[0] 16 | os.chdir(root_path) 17 | sys.path.insert(0, os.path.join(root_path, 'lib_zabbix')) 18 | sys.path.insert(0, os.path.join(root_path, 'py_tool/my_lib')) 19 | 20 | from zabbix_api import zabbix_api 21 | import json 22 | zabbix_tool="/etc/zabbix_tool/zabbix_tool.ini" 23 | 24 | def week_report(): 25 | import date 26 | import datetime 27 | import pyMail 28 | weekreport_name = "/opt/weekreport.xls" 29 | d = datetime.datetime.now() 30 | date_from,date_to = date.week_get(d) 31 | print date_from,date_to 32 | terminal_table = False 33 | zabbix=zabbix_api(terminal_table) 34 | itemkey_list=['vm.memory.size[available]', 'agent.ping', 'vfs.fs.size[/,pfree]', 'system.cpu.load[percpu,avg1]'] 35 | export_xls = {"xls":"ON", 36 | "xls_name":weekreport_name, 37 | "title":"ON", 38 | "title_name":u"周报" 39 | } 40 | select_condition = {"hostgroupID":"", 41 | "hostID":"" 42 | } 43 | zabbix.report_available2(str(date_from),str(date_to),export_xls,select_condition,itemkey_list=itemkey_list) 44 | 45 | # 1 初始化发送邮件类 46 | # 25 端口时,usettls = False 47 | # 465 端口时,usettls = True 48 | usettls = False 49 | sml = pyMail.SendMailDealer('mail_address','mail_pwd','smtp.gmail.com','25',usettls = usettls) 50 | # 2 设置邮件信息 51 | # 参数包括("收件人","标题","正文","格式html/plain","附件路径1","附件路径2") 52 | sml.setMailInfo('paramiao@gmail.com','测试','正文','plain',weekreport_name) 53 | # 3 发送邮件 54 | sml.sendMail() 55 | def create_config(): 56 | import ConfigParser 57 | config = ConfigParser.ConfigParser() 58 | config.read(zabbix_tool) 59 | applitions = config.get("create_file", "applitions") 60 | monit_config = config.get("create_file","monit_config") 61 | ignore_key_list = config.get("create_file","ignore_key").split(",") 62 | 63 | zabbix=zabbix_api(output=False) 64 | 65 | # 主机名和 IP 字典 66 | hostname_ip={} 67 | 68 | # 主机名和 监控项字典 69 | hostname_key={} 70 | 71 | # key_和监控项字典 72 | service_key={} 73 | 74 | host_list=zabbix.host_list() 75 | for host in host_list: 76 | # host[0]---hostid ,host[1]---hostname,host[2]---hostip 77 | hostid=host[0] 78 | hostname=host[1] 79 | hostip=host[2] 80 | hostname_ip[hostname]=hostip 81 | 82 | items = zabbix.item_list(hostid,applitions) 83 | if not items: 84 | items = [] 85 | else: 86 | for ignore_key_item in ignore_key_list: 87 | if ignore_key_item in items: 88 | items.remove(ignore_key_item) 89 | for key_item in items: 90 | service_key[key_item]="" 91 | hostname_key[hostname]=items 92 | 93 | 94 | for key_item in service_key: 95 | service_name = key_item.replace(".","_").replace(",","").replace("[","").replace("]","") 96 | service_key[key_item]=service_name 97 | 98 | hostname_ip=json.dumps(hostname_ip,indent=4) 99 | #print hostname_ip 100 | hostname_key=json.dumps(hostname_key,indent=4) 101 | #print hostname_key 102 | service_key=json.dumps(service_key,indent=4) 103 | #print service_key 104 | 105 | # 生成配置文件 106 | config_file = "#!/usr/bin/python\n#coding=utf8\n" 107 | config_file = config_file + "hostname_ip="+hostname_ip+"\n" 108 | config_file = config_file + "hostname_key="+hostname_key+"\n" 109 | config_file = config_file + "service_key="+service_key+"\n" 110 | 111 | # 写入配置文件 112 | fo = open(monit_config, "wb") 113 | fo.write(config_file) 114 | fo.close() 115 | def status(): 116 | zabbix=zabbix_api(output=False) 117 | host_ip={} 118 | host_list=zabbix.host_list() 119 | #print host_list 120 | for host in host_list: 121 | host_ip[host[1]]=host[2] 122 | # print host_ip 123 | # for host in host_list: 124 | issues_dict = zabbix.issues() 125 | exception_host=[] 126 | 127 | ## 异常主机 128 | if isinstance(issues_dict,dict): 129 | for issues in issues_dict: 130 | exception_host.append(issues) 131 | exception_host = list(set(exception_host)) 132 | else: 133 | exception_host = [] 134 | 135 | print "exception_host",exception_host 136 | 137 | ## 正常主机 138 | normal_host=[] 139 | for host in host_ip: 140 | if host not in exception_host: 141 | normal_host.append(host) 142 | print "normal_host",normal_host 143 | 144 | def version(): 145 | print __version__ 146 | 147 | 148 | # 函数作为模块调用 不必理会 149 | if __name__ == '__main__': 150 | import sys, inspect 151 | if len(sys.argv) < 2: 152 | print "Usage:" 153 | for k, v in sorted(globals().items(), key=lambda item: item[0]): 154 | if inspect.isfunction(v) and k[0] != "_": 155 | args, __, __, defaults = inspect.getargspec(v) 156 | if defaults: 157 | print sys.argv[0], k, str(args[:-len(defaults)])[1:-1].replace(",", ""), \ 158 | str(["%s=%s" % (a, b) for a, b in zip(args[-len(defaults):], defaults)])[1:-1].replace(",", "") 159 | else: 160 | print sys.argv[0], k, str(v.func_code.co_varnames[:v.func_code.co_argcount])[1:-1].replace(",", "") 161 | sys.exit(-1) 162 | else: 163 | func = eval(sys.argv[1]) 164 | args = sys.argv[2:] 165 | try: 166 | r = func(*args) 167 | except Exception, e: 168 | print "Usage:" 169 | print "\t", "python %s" % sys.argv[1], str(func.func_code.co_varnames[:func.func_code.co_argcount])[1:-1].replace(",", "") 170 | if func.func_doc: 171 | print "\n".join(["\t\t" + line.strip() for line in func.func_doc.strip().split("\n")]) 172 | print e 173 | r = -1 174 | import traceback 175 | traceback.print_exc() 176 | if isinstance(r, int): 177 | sys.exit(r) 178 | -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/w_lib/terminaltables/tables.py: -------------------------------------------------------------------------------- 1 | """User-facing tables defined here.""" 2 | 3 | import os 4 | 5 | from terminaltables.base_table import BaseTable, join_row 6 | 7 | 8 | class AsciiTable(BaseTable): 9 | """Draw a table using regular ASCII characters, such as `+`, `|`, and `-`.""" 10 | 11 | CHAR_CORNER_LOWER_LEFT = '+' 12 | CHAR_CORNER_LOWER_RIGHT = '+' 13 | CHAR_CORNER_UPPER_LEFT = '+' 14 | CHAR_CORNER_UPPER_RIGHT = '+' 15 | CHAR_HORIZONTAL = '-' 16 | CHAR_INTERSECT_BOTTOM = '+' 17 | CHAR_INTERSECT_CENTER = '+' 18 | CHAR_INTERSECT_LEFT = '+' 19 | CHAR_INTERSECT_RIGHT = '+' 20 | CHAR_INTERSECT_TOP = '+' 21 | CHAR_VERTICAL = '|' 22 | 23 | 24 | class UnixTable(BaseTable): 25 | """Draw a table using box-drawing characters on Unix platforms. Table borders won't have any gaps between lines. 26 | 27 | Similar to the tables shown on PC BIOS boot messages, but not double-lined. 28 | """ 29 | 30 | CHAR_CORNER_LOWER_LEFT = '\033(0\x6d\033(B' 31 | CHAR_CORNER_LOWER_RIGHT = '\033(0\x6a\033(B' 32 | CHAR_CORNER_UPPER_LEFT = '\033(0\x6c\033(B' 33 | CHAR_CORNER_UPPER_RIGHT = '\033(0\x6b\033(B' 34 | CHAR_HORIZONTAL = '\033(0\x71\033(B' 35 | CHAR_INTERSECT_BOTTOM = '\033(0\x76\033(B' 36 | CHAR_INTERSECT_CENTER = '\033(0\x6e\033(B' 37 | CHAR_INTERSECT_LEFT = '\033(0\x74\033(B' 38 | CHAR_INTERSECT_RIGHT = '\033(0\x75\033(B' 39 | CHAR_INTERSECT_TOP = '\033(0\x77\033(B' 40 | CHAR_VERTICAL = '\033(0\x78\033(B' 41 | 42 | @property 43 | def table(self): 44 | """Return a large string of the entire table ready to be printed to the terminal.""" 45 | ascii_table = super(UnixTable, self).table 46 | optimized = ascii_table.replace('\033(B\033(0', '') 47 | return optimized 48 | 49 | 50 | class WindowsTable(BaseTable): 51 | """Draw a table using box-drawing characters on Windows platforms. This uses Code Page 437. Single-line borders. 52 | 53 | From: http://en.wikipedia.org/wiki/Code_page_437#Characters 54 | """ 55 | 56 | CHAR_CORNER_LOWER_LEFT = b'\xc0'.decode('ibm437') 57 | CHAR_CORNER_LOWER_RIGHT = b'\xd9'.decode('ibm437') 58 | CHAR_CORNER_UPPER_LEFT = b'\xda'.decode('ibm437') 59 | CHAR_CORNER_UPPER_RIGHT = b'\xbf'.decode('ibm437') 60 | CHAR_HORIZONTAL = b'\xc4'.decode('ibm437') 61 | CHAR_INTERSECT_BOTTOM = b'\xc1'.decode('ibm437') 62 | CHAR_INTERSECT_CENTER = b'\xc5'.decode('ibm437') 63 | CHAR_INTERSECT_LEFT = b'\xc3'.decode('ibm437') 64 | CHAR_INTERSECT_RIGHT = b'\xb4'.decode('ibm437') 65 | CHAR_INTERSECT_TOP = b'\xc2'.decode('ibm437') 66 | CHAR_VERTICAL = b'\xb3'.decode('ibm437') 67 | 68 | 69 | class WindowsTableDouble(BaseTable): 70 | """Draw a table using box-drawing characters on Windows platforms. This uses Code Page 437. Double-line borders.""" 71 | 72 | CHAR_CORNER_LOWER_LEFT = b'\xc8'.decode('ibm437') 73 | CHAR_CORNER_LOWER_RIGHT = b'\xbc'.decode('ibm437') 74 | CHAR_CORNER_UPPER_LEFT = b'\xc9'.decode('ibm437') 75 | CHAR_CORNER_UPPER_RIGHT = b'\xbb'.decode('ibm437') 76 | CHAR_HORIZONTAL = b'\xcd'.decode('ibm437') 77 | CHAR_INTERSECT_BOTTOM = b'\xca'.decode('ibm437') 78 | CHAR_INTERSECT_CENTER = b'\xce'.decode('ibm437') 79 | CHAR_INTERSECT_LEFT = b'\xcc'.decode('ibm437') 80 | CHAR_INTERSECT_RIGHT = b'\xb9'.decode('ibm437') 81 | CHAR_INTERSECT_TOP = b'\xcb'.decode('ibm437') 82 | CHAR_VERTICAL = b'\xba'.decode('ibm437') 83 | 84 | 85 | class SingleTable(WindowsTable if os.name == 'nt' else UnixTable): 86 | """Cross-platform table with single-line box-drawing characters.""" 87 | 88 | pass 89 | 90 | 91 | class DoubleTable(WindowsTableDouble): 92 | """Cross-platform table with box-drawing characters. On Windows it's double borders, on Linux/OSX it's unicode.""" 93 | 94 | pass 95 | 96 | 97 | class GithubFlavoredMarkdownTable(BaseTable): 98 | """Github flavored markdown table. 99 | 100 | https://help.github.com/articles/github-flavored-markdown/#tables 101 | """ 102 | 103 | CHAR_VERTICAL = '|' 104 | CHAR_HORIZONTAL = '-' 105 | 106 | def __init__(self, table_data): 107 | """Constructor. 108 | 109 | :param iter table_data: List (empty or list of lists of strings) representing the table. 110 | """ 111 | # Github flavored markdown table won't support title. 112 | super(GithubFlavoredMarkdownTable, self).__init__(table_data) 113 | 114 | @property 115 | def table(self): 116 | """Return a large string of the entire table ready to be printed to the terminal.""" 117 | padded_table_data = self.padded_table_data 118 | column_widths = [c + self.padding_left + self.padding_right for c in self.column_widths] 119 | final_table_data = list() 120 | 121 | for row_index, row_data in enumerate(padded_table_data): 122 | row = join_row( 123 | row_data, 124 | self.CHAR_VERTICAL, 125 | self.CHAR_VERTICAL, 126 | self.CHAR_VERTICAL 127 | ) 128 | final_table_data.append(row) 129 | 130 | if row_index != 0: 131 | continue 132 | 133 | # Header row separator. 134 | column_separators = [] 135 | for column_index, column_width in enumerate(column_widths): 136 | column_justify = self.justify_columns.get(column_index) 137 | if column_justify == 'left': 138 | separator = ':' + self.CHAR_HORIZONTAL * (column_width - 1) 139 | elif column_justify == 'right': 140 | separator = self.CHAR_HORIZONTAL * (column_width - 1) + ':' 141 | elif column_justify == 'center': 142 | separator = self.CHAR_HORIZONTAL * (column_width - 2) 143 | separator = ':' + separator + ':' 144 | else: 145 | separator = self.CHAR_HORIZONTAL * column_width 146 | column_separators.append(separator) 147 | row = join_row( 148 | column_separators, 149 | self.CHAR_VERTICAL, 150 | self.CHAR_VERTICAL, 151 | self.CHAR_VERTICAL 152 | ) 153 | final_table_data.append(row) 154 | 155 | return '\n'.join(final_table_data) 156 | -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/w_lib/colorclass/color.py: -------------------------------------------------------------------------------- 1 | """Color class used by library users.""" 2 | 3 | from colorclass.core import ColorStr 4 | 5 | 6 | class Color(ColorStr): 7 | """Unicode (str in Python3) subclass with ANSI terminal text color support. 8 | 9 | Example syntax: Color('{red}Sample Text{/red}') 10 | 11 | Example without parsing logic: Color('{red}Sample Text{/red}', keep_tags=True) 12 | 13 | For a list of codes, call: colorclass.list_tags() 14 | """ 15 | 16 | @classmethod 17 | def colorize(cls, color, string, auto=False): 18 | """Color-code entire string using specified color. 19 | 20 | :param str color: Color of string. 21 | :param str string: String to colorize. 22 | :param bool auto: Enable auto-color (dark/light terminal). 23 | 24 | :return: Class instance for colorized string. 25 | :rtype: Color 26 | """ 27 | tag = '{0}{1}'.format('auto' if auto else '', color) 28 | return cls('{%s}%s{/%s}' % (tag, string, tag)) 29 | 30 | @classmethod 31 | def black(cls, string, auto=False): 32 | """Color-code entire string. 33 | 34 | :param str string: String to colorize. 35 | :param bool auto: Enable auto-color (dark/light terminal). 36 | 37 | :return: Class instance for colorized string. 38 | :rtype: Color 39 | """ 40 | return cls.colorize('black', string, auto=auto) 41 | 42 | @classmethod 43 | def bgblack(cls, string, auto=False): 44 | """Color-code entire string. 45 | 46 | :param str string: String to colorize. 47 | :param bool auto: Enable auto-color (dark/light terminal). 48 | 49 | :return: Class instance for colorized string. 50 | :rtype: Color 51 | """ 52 | return cls.colorize('bgblack', string, auto=auto) 53 | 54 | @classmethod 55 | def red(cls, string, auto=False): 56 | """Color-code entire string. 57 | 58 | :param str string: String to colorize. 59 | :param bool auto: Enable auto-color (dark/light terminal). 60 | 61 | :return: Class instance for colorized string. 62 | :rtype: Color 63 | """ 64 | return cls.colorize('red', string, auto=auto) 65 | 66 | @classmethod 67 | def bgred(cls, string, auto=False): 68 | """Color-code entire string. 69 | 70 | :param str string: String to colorize. 71 | :param bool auto: Enable auto-color (dark/light terminal). 72 | 73 | :return: Class instance for colorized string. 74 | :rtype: Color 75 | """ 76 | return cls.colorize('bgred', string, auto=auto) 77 | 78 | @classmethod 79 | def green(cls, string, auto=False): 80 | """Color-code entire string. 81 | 82 | :param str string: String to colorize. 83 | :param bool auto: Enable auto-color (dark/light terminal). 84 | 85 | :return: Class instance for colorized string. 86 | :rtype: Color 87 | """ 88 | return cls.colorize('green', string, auto=auto) 89 | 90 | @classmethod 91 | def bggreen(cls, string, auto=False): 92 | """Color-code entire string. 93 | 94 | :param str string: String to colorize. 95 | :param bool auto: Enable auto-color (dark/light terminal). 96 | 97 | :return: Class instance for colorized string. 98 | :rtype: Color 99 | """ 100 | return cls.colorize('bggreen', string, auto=auto) 101 | 102 | @classmethod 103 | def yellow(cls, string, auto=False): 104 | """Color-code entire string. 105 | 106 | :param str string: String to colorize. 107 | :param bool auto: Enable auto-color (dark/light terminal). 108 | 109 | :return: Class instance for colorized string. 110 | :rtype: Color 111 | """ 112 | return cls.colorize('yellow', string, auto=auto) 113 | 114 | @classmethod 115 | def bgyellow(cls, string, auto=False): 116 | """Color-code entire string. 117 | 118 | :param str string: String to colorize. 119 | :param bool auto: Enable auto-color (dark/light terminal). 120 | 121 | :return: Class instance for colorized string. 122 | :rtype: Color 123 | """ 124 | return cls.colorize('bgyellow', string, auto=auto) 125 | 126 | @classmethod 127 | def blue(cls, string, auto=False): 128 | """Color-code entire string. 129 | 130 | :param str string: String to colorize. 131 | :param bool auto: Enable auto-color (dark/light terminal). 132 | 133 | :return: Class instance for colorized string. 134 | :rtype: Color 135 | """ 136 | return cls.colorize('blue', string, auto=auto) 137 | 138 | @classmethod 139 | def bgblue(cls, string, auto=False): 140 | """Color-code entire string. 141 | 142 | :param str string: String to colorize. 143 | :param bool auto: Enable auto-color (dark/light terminal). 144 | 145 | :return: Class instance for colorized string. 146 | :rtype: Color 147 | """ 148 | return cls.colorize('bgblue', string, auto=auto) 149 | 150 | @classmethod 151 | def magenta(cls, string, auto=False): 152 | """Color-code entire string. 153 | 154 | :param str string: String to colorize. 155 | :param bool auto: Enable auto-color (dark/light terminal). 156 | 157 | :return: Class instance for colorized string. 158 | :rtype: Color 159 | """ 160 | return cls.colorize('magenta', string, auto=auto) 161 | 162 | @classmethod 163 | def bgmagenta(cls, string, auto=False): 164 | """Color-code entire string. 165 | 166 | :param str string: String to colorize. 167 | :param bool auto: Enable auto-color (dark/light terminal). 168 | 169 | :return: Class instance for colorized string. 170 | :rtype: Color 171 | """ 172 | return cls.colorize('bgmagenta', string, auto=auto) 173 | 174 | @classmethod 175 | def cyan(cls, string, auto=False): 176 | """Color-code entire string. 177 | 178 | :param str string: String to colorize. 179 | :param bool auto: Enable auto-color (dark/light terminal). 180 | 181 | :return: Class instance for colorized string. 182 | :rtype: Color 183 | """ 184 | return cls.colorize('cyan', string, auto=auto) 185 | 186 | @classmethod 187 | def bgcyan(cls, string, auto=False): 188 | """Color-code entire string. 189 | 190 | :param str string: String to colorize. 191 | :param bool auto: Enable auto-color (dark/light terminal). 192 | 193 | :return: Class instance for colorized string. 194 | :rtype: Color 195 | """ 196 | return cls.colorize('bgcyan', string, auto=auto) 197 | 198 | @classmethod 199 | def white(cls, string, auto=False): 200 | """Color-code entire string. 201 | 202 | :param str string: String to colorize. 203 | :param bool auto: Enable auto-color (dark/light terminal). 204 | 205 | :return: Class instance for colorized string. 206 | :rtype: Color 207 | """ 208 | return cls.colorize('white', string, auto=auto) 209 | 210 | @classmethod 211 | def bgwhite(cls, string, auto=False): 212 | """Color-code entire string. 213 | 214 | :param str string: String to colorize. 215 | :param bool auto: Enable auto-color (dark/light terminal). 216 | 217 | :return: Class instance for colorized string. 218 | :rtype: Color 219 | """ 220 | return cls.colorize('bgwhite', string, auto=auto) 221 | -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/w_lib/terminaltables/base_table.py: -------------------------------------------------------------------------------- 1 | """Main table class.""" 2 | 3 | import re 4 | 5 | from terminaltables.terminal_io import terminal_size 6 | from terminaltables.width_and_alignment import align_and_pad_cell, column_widths, string_width 7 | 8 | 9 | def join_row(row, left, middle, right): 10 | """Convert a row (list of strings) into a joined string with left and right borders. Supports multi-lines. 11 | 12 | :param iter row: List of strings representing one row. 13 | :param str left: Left border. 14 | :param str middle: Column separator. 15 | :param str right: Right border. 16 | 17 | :return: String representation of a row. 18 | :rtype: str 19 | """ 20 | if not row: 21 | return left + right 22 | 23 | if not any('\n' in c for c in row): 24 | return left + middle.join(row) + right 25 | 26 | # Split cells in the row by newlines. This creates new rows. 27 | split_cells = [(c.splitlines() or ['']) + ([''] if c.endswith('\n') else []) for c in row] 28 | height = len(split_cells[0]) 29 | 30 | # Merge rows into strings. 31 | converted_rows = list() 32 | for row_number in range(height): 33 | converted_rows.append(left + middle.join([c[row_number] for c in split_cells]) + right) 34 | return '\n'.join(converted_rows) 35 | 36 | 37 | class BaseTable(object): 38 | """Base table class.""" 39 | 40 | CHAR_CORNER_LOWER_LEFT = '' 41 | CHAR_CORNER_LOWER_RIGHT = '' 42 | CHAR_CORNER_UPPER_LEFT = '' 43 | CHAR_CORNER_UPPER_RIGHT = '' 44 | CHAR_HORIZONTAL = '' 45 | CHAR_INTERSECT_BOTTOM = '' 46 | CHAR_INTERSECT_CENTER = '' 47 | CHAR_INTERSECT_LEFT = '' 48 | CHAR_INTERSECT_RIGHT = '' 49 | CHAR_INTERSECT_TOP = '' 50 | CHAR_VERTICAL = '' 51 | 52 | def __init__(self, table_data, title=None): 53 | """Constructor. 54 | 55 | :param iter table_data: List (empty or list of lists of strings) representing the table. 56 | :param str title: Optional title to show within the top border of the table. 57 | """ 58 | self.table_data = table_data 59 | self.title = title 60 | 61 | self.inner_column_border = True 62 | self.inner_heading_row_border = True 63 | self.inner_footing_row_border = False 64 | self.inner_row_border = False 65 | self.justify_columns = dict() # {0: 'right', 1: 'left', 2: 'center'} 66 | self.outer_border = True 67 | self.padding_left = 1 68 | self.padding_right = 1 69 | 70 | def column_max_width(self, column_number): 71 | """Return the maximum width of a column based on the current terminal width. 72 | 73 | :param int column_number: The column number to query. 74 | 75 | :return: The max width of the column. 76 | :rtype: int 77 | """ 78 | widths = self.column_widths 79 | borders_padding = (len(widths) * self.padding_left) + (len(widths) * self.padding_right) 80 | if self.outer_border: 81 | borders_padding += 2 82 | if self.inner_column_border and widths: 83 | borders_padding += len(widths) - 1 84 | other_column_widths = sum(widths) - widths[column_number] 85 | return terminal_size()[0] - other_column_widths - borders_padding 86 | 87 | @property 88 | def column_widths(self): 89 | """Return a list of integers representing the widths of each table column without padding.""" 90 | if not self.table_data: 91 | return list() 92 | return column_widths(self.table_data) 93 | 94 | @property 95 | def ok(self): # Too late to change API. # pylint: disable=invalid-name 96 | """Return True if the table fits within the terminal width, False if the table breaks.""" 97 | return self.table_width <= terminal_size()[0] 98 | 99 | @property 100 | def padded_table_data(self): 101 | """Return a list of lists of strings. It's self.table_data but with the cells padded with spaces and newlines. 102 | 103 | Most of the work in this class is done here. 104 | """ 105 | if not self.table_data: 106 | return list() 107 | 108 | # Set all rows to the same number of columns. 109 | max_columns = max(len(r) for r in self.table_data) 110 | new_table_data = [r + [''] * (max_columns - len(r)) for r in self.table_data] 111 | 112 | # Pad strings in each cell, and apply text-align/justification. 113 | widths = self.column_widths 114 | for row in new_table_data: 115 | height = max([c.count('\n') for c in row] or [0]) + 1 116 | for i in range(len(row)): 117 | align = self.justify_columns.get(i, 'left') 118 | cell = align_and_pad_cell(row[i], align, (widths[i], height, self.padding_left, self.padding_right)) 119 | row[i] = cell 120 | 121 | return new_table_data 122 | 123 | @property 124 | def table(self): 125 | """Return a large string of the entire table ready to be printed to the terminal.""" 126 | padded_table_data = self.padded_table_data 127 | widths = [c + self.padding_left + self.padding_right for c in self.column_widths] 128 | final_table_data = list() 129 | 130 | # Append top border. 131 | max_title = sum(widths) + ((len(widths) - 1) if self.inner_column_border else 0) 132 | if self.outer_border and self.title and string_width(self.title) <= max_title: 133 | pseudo_row = join_row( 134 | ['h' * w for w in widths], 135 | 'l', 't' if self.inner_column_border else '', 136 | 'r' 137 | ) 138 | pseudo_row_key = dict(h=self.CHAR_HORIZONTAL, l=self.CHAR_CORNER_UPPER_LEFT, t=self.CHAR_INTERSECT_TOP, 139 | r=self.CHAR_CORNER_UPPER_RIGHT) 140 | pseudo_row_re = re.compile('({0})'.format('|'.join(pseudo_row_key.keys()))) 141 | substitute = lambda s: pseudo_row_re.sub(lambda x: pseudo_row_key[x.string[x.start():x.end()]], s) 142 | row = substitute(pseudo_row[:1]) + self.title + substitute(pseudo_row[1 + string_width(self.title):]) 143 | final_table_data.append(row) 144 | elif self.outer_border: 145 | row = join_row( 146 | [self.CHAR_HORIZONTAL * w for w in widths], 147 | self.CHAR_CORNER_UPPER_LEFT, 148 | self.CHAR_INTERSECT_TOP if self.inner_column_border else '', 149 | self.CHAR_CORNER_UPPER_RIGHT 150 | ) 151 | final_table_data.append(row) 152 | 153 | # Build table body. 154 | indexes = range(len(padded_table_data)) 155 | for i in indexes: 156 | row = join_row( 157 | padded_table_data[i], 158 | self.CHAR_VERTICAL if self.outer_border else '', 159 | self.CHAR_VERTICAL if self.inner_column_border else '', 160 | self.CHAR_VERTICAL if self.outer_border else '' 161 | ) 162 | final_table_data.append(row) 163 | 164 | # Insert row separator. 165 | if i == indexes[-1]: 166 | continue 167 | if self.inner_row_border or (self.inner_heading_row_border and i == 0): 168 | row = join_row( 169 | [self.CHAR_HORIZONTAL * w for w in widths], 170 | self.CHAR_INTERSECT_LEFT if self.outer_border else '', 171 | self.CHAR_INTERSECT_CENTER if self.inner_column_border else '', 172 | self.CHAR_INTERSECT_RIGHT if self.outer_border else '' 173 | ) 174 | final_table_data.append(row) 175 | 176 | if i == indexes[-2] and self.inner_footing_row_border: 177 | row = join_row( 178 | [self.CHAR_HORIZONTAL * w for w in widths], 179 | self.CHAR_INTERSECT_LEFT if self.outer_border else '', 180 | self.CHAR_INTERSECT_CENTER if self.inner_column_border else '', 181 | self.CHAR_INTERSECT_RIGHT if self.outer_border else '' 182 | ) 183 | final_table_data.append(row) 184 | 185 | # Append bottom border. 186 | if self.outer_border: 187 | row = join_row( 188 | [self.CHAR_HORIZONTAL * w for w in widths], 189 | self.CHAR_CORNER_LOWER_LEFT, 190 | self.CHAR_INTERSECT_BOTTOM if self.inner_column_border else '', 191 | self.CHAR_CORNER_LOWER_RIGHT 192 | ) 193 | final_table_data.append(row) 194 | 195 | return '\n'.join(final_table_data) 196 | 197 | @property 198 | def table_width(self): 199 | """Return the width of the table including padding and borders.""" 200 | widths = self.column_widths 201 | borders_padding = (len(widths) * self.padding_left) + (len(widths) * self.padding_right) 202 | if self.outer_border: 203 | borders_padding += 2 204 | if self.inner_column_border and widths: 205 | borders_padding += len(widths) - 1 206 | return sum(widths) + borders_padding 207 | -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/w_lib/colorclass/codes.py: -------------------------------------------------------------------------------- 1 | """Handles mapping between color names and ANSI codes and determining auto color codes.""" 2 | 3 | import sys 4 | from collections import Mapping 5 | 6 | BASE_CODES = { 7 | '/all': 0, 'b': 1, 'f': 2, 'i': 3, 'u': 4, 'flash': 5, 'outline': 6, 'negative': 7, 'invis': 8, 'strike': 9, 8 | '/b': 22, '/f': 22, '/i': 23, '/u': 24, '/flash': 25, '/outline': 26, '/negative': 27, '/invis': 28, 9 | '/strike': 29, '/fg': 39, '/bg': 49, 10 | 11 | 'black': 30, 'red': 31, 'green': 32, 'yellow': 33, 'blue': 34, 'magenta': 35, 'cyan': 36, 'white': 37, 12 | 13 | 'bgblack': 40, 'bgred': 41, 'bggreen': 42, 'bgyellow': 43, 'bgblue': 44, 'bgmagenta': 45, 'bgcyan': 46, 14 | 'bgwhite': 47, 15 | 16 | 'hiblack': 90, 'hired': 91, 'higreen': 92, 'hiyellow': 93, 'hiblue': 94, 'himagenta': 95, 'hicyan': 96, 17 | 'hiwhite': 97, 18 | 19 | 'hibgblack': 100, 'hibgred': 101, 'hibggreen': 102, 'hibgyellow': 103, 'hibgblue': 104, 'hibgmagenta': 105, 20 | 'hibgcyan': 106, 'hibgwhite': 107, 21 | 22 | 'autored': None, 'autoblack': None, 'automagenta': None, 'autowhite': None, 'autoblue': None, 'autoyellow': None, 23 | 'autogreen': None, 'autocyan': None, 24 | 25 | 'autobgred': None, 'autobgblack': None, 'autobgmagenta': None, 'autobgwhite': None, 'autobgblue': None, 26 | 'autobgyellow': None, 'autobggreen': None, 'autobgcyan': None, 27 | 28 | '/black': 39, '/red': 39, '/green': 39, '/yellow': 39, '/blue': 39, '/magenta': 39, '/cyan': 39, '/white': 39, 29 | '/hiblack': 39, '/hired': 39, '/higreen': 39, '/hiyellow': 39, '/hiblue': 39, '/himagenta': 39, '/hicyan': 39, 30 | '/hiwhite': 39, 31 | 32 | '/bgblack': 49, '/bgred': 49, '/bggreen': 49, '/bgyellow': 49, '/bgblue': 49, '/bgmagenta': 49, '/bgcyan': 49, 33 | '/bgwhite': 49, '/hibgblack': 49, '/hibgred': 49, '/hibggreen': 49, '/hibgyellow': 49, '/hibgblue': 49, 34 | '/hibgmagenta': 49, '/hibgcyan': 49, '/hibgwhite': 49, 35 | 36 | '/autored': 39, '/autoblack': 39, '/automagenta': 39, '/autowhite': 39, '/autoblue': 39, '/autoyellow': 39, 37 | '/autogreen': 39, '/autocyan': 39, 38 | 39 | '/autobgred': 49, '/autobgblack': 49, '/autobgmagenta': 49, '/autobgwhite': 49, '/autobgblue': 49, 40 | '/autobgyellow': 49, '/autobggreen': 49, '/autobgcyan': 49, 41 | } 42 | 43 | 44 | class ANSICodeMapping(Mapping): 45 | """Read-only dictionary, resolves closing tags and automatic colors. Iterates only used color tags. 46 | 47 | :cvar bool DISABLE_COLORS: Disable colors (strip color codes). 48 | :cvar bool LIGHT_BACKGROUND: Use low intensity color codes. 49 | """ 50 | 51 | DISABLE_COLORS = not (sys.stdout.isatty() or sys.stderr.isatty()) # Disable colors when piped to another program. 52 | LIGHT_BACKGROUND = False 53 | 54 | def __init__(self, value_markup): 55 | """Constructor. 56 | 57 | :param str value_markup: String with {color} tags. 58 | """ 59 | self.whitelist = [k for k in BASE_CODES if '{' + k + '}' in value_markup] 60 | 61 | def __getitem__(self, item): 62 | """Return value for key or None if colors are disabled. 63 | 64 | :param str item: Key. 65 | 66 | :return: Color code integer. 67 | :rtype: int 68 | """ 69 | if item not in self.whitelist: 70 | raise KeyError(item) 71 | if self.DISABLE_COLORS: 72 | return None 73 | return getattr(self, item, BASE_CODES[item]) 74 | 75 | def __iter__(self): 76 | """Iterate dictionary.""" 77 | return iter(self.whitelist) 78 | 79 | def __len__(self): 80 | """Dictionary length.""" 81 | return len(self.whitelist) 82 | 83 | @classmethod 84 | def disable_all_colors(cls): 85 | """Disable all colors. Strips any color tags or codes.""" 86 | cls.DISABLE_COLORS = True 87 | 88 | @classmethod 89 | def enable_all_colors(cls): 90 | """Enable all colors. Strips any color tags or codes.""" 91 | cls.DISABLE_COLORS = False 92 | 93 | @classmethod 94 | def set_dark_background(cls): 95 | """Choose dark colors for all 'auto'-prefixed codes for readability on light backgrounds.""" 96 | cls.LIGHT_BACKGROUND = False 97 | 98 | @classmethod 99 | def set_light_background(cls): 100 | """Choose dark colors for all 'auto'-prefixed codes for readability on light backgrounds.""" 101 | cls.LIGHT_BACKGROUND = True 102 | 103 | @property 104 | def autoblack(self): 105 | """Return automatic black foreground color depending on background color.""" 106 | return BASE_CODES['black' if ANSICodeMapping.LIGHT_BACKGROUND else 'hiblack'] 107 | 108 | @property 109 | def autored(self): 110 | """Return automatic red foreground color depending on background color.""" 111 | return BASE_CODES['red' if ANSICodeMapping.LIGHT_BACKGROUND else 'hired'] 112 | 113 | @property 114 | def autogreen(self): 115 | """Return automatic green foreground color depending on background color.""" 116 | return BASE_CODES['green' if ANSICodeMapping.LIGHT_BACKGROUND else 'higreen'] 117 | 118 | @property 119 | def autoyellow(self): 120 | """Return automatic yellow foreground color depending on background color.""" 121 | return BASE_CODES['yellow' if ANSICodeMapping.LIGHT_BACKGROUND else 'hiyellow'] 122 | 123 | @property 124 | def autoblue(self): 125 | """Return automatic blue foreground color depending on background color.""" 126 | return BASE_CODES['blue' if ANSICodeMapping.LIGHT_BACKGROUND else 'hiblue'] 127 | 128 | @property 129 | def automagenta(self): 130 | """Return automatic magenta foreground color depending on background color.""" 131 | return BASE_CODES['magenta' if ANSICodeMapping.LIGHT_BACKGROUND else 'himagenta'] 132 | 133 | @property 134 | def autocyan(self): 135 | """Return automatic cyan foreground color depending on background color.""" 136 | return BASE_CODES['cyan' if ANSICodeMapping.LIGHT_BACKGROUND else 'hicyan'] 137 | 138 | @property 139 | def autowhite(self): 140 | """Return automatic white foreground color depending on background color.""" 141 | return BASE_CODES['white' if ANSICodeMapping.LIGHT_BACKGROUND else 'hiwhite'] 142 | 143 | @property 144 | def autobgblack(self): 145 | """Return automatic black background color depending on background color.""" 146 | return BASE_CODES['bgblack' if ANSICodeMapping.LIGHT_BACKGROUND else 'hibgblack'] 147 | 148 | @property 149 | def autobgred(self): 150 | """Return automatic red background color depending on background color.""" 151 | return BASE_CODES['bgred' if ANSICodeMapping.LIGHT_BACKGROUND else 'hibgred'] 152 | 153 | @property 154 | def autobggreen(self): 155 | """Return automatic green background color depending on background color.""" 156 | return BASE_CODES['bggreen' if ANSICodeMapping.LIGHT_BACKGROUND else 'hibggreen'] 157 | 158 | @property 159 | def autobgyellow(self): 160 | """Return automatic yellow background color depending on background color.""" 161 | return BASE_CODES['bgyellow' if ANSICodeMapping.LIGHT_BACKGROUND else 'hibgyellow'] 162 | 163 | @property 164 | def autobgblue(self): 165 | """Return automatic blue background color depending on background color.""" 166 | return BASE_CODES['bgblue' if ANSICodeMapping.LIGHT_BACKGROUND else 'hibgblue'] 167 | 168 | @property 169 | def autobgmagenta(self): 170 | """Return automatic magenta background color depending on background color.""" 171 | return BASE_CODES['bgmagenta' if ANSICodeMapping.LIGHT_BACKGROUND else 'hibgmagenta'] 172 | 173 | @property 174 | def autobgcyan(self): 175 | """Return automatic cyan background color depending on background color.""" 176 | return BASE_CODES['bgcyan' if ANSICodeMapping.LIGHT_BACKGROUND else 'hibgcyan'] 177 | 178 | @property 179 | def autobgwhite(self): 180 | """Return automatic white background color depending on background color.""" 181 | return BASE_CODES['bgwhite' if ANSICodeMapping.LIGHT_BACKGROUND else 'hibgwhite'] 182 | 183 | 184 | def list_tags(): 185 | """List the available tags. 186 | 187 | :return: List of 4-item tuples: opening tag, closing tag, main ansi value, closing ansi value. 188 | :rtype: list 189 | """ 190 | # Build reverse dictionary. Keys are closing tags, values are [closing ansi, opening tag, opening ansi]. 191 | reverse_dict = dict() 192 | for tag, ansi in sorted(BASE_CODES.items()): 193 | if tag.startswith('/'): 194 | reverse_dict[tag] = [ansi, None, None] 195 | else: 196 | reverse_dict['/' + tag][1:] = [tag, ansi] 197 | 198 | # Collapse 199 | four_item_tuples = [(v[1], k, v[2], v[0]) for k, v in reverse_dict.items()] 200 | 201 | # Sort. 202 | def sorter(four_item): 203 | """Sort /all /fg /bg first, then b i u flash, then auto colors, then dark colors, finally light colors. 204 | 205 | :param iter four_item: [opening tag, closing tag, main ansi value, closing ansi value] 206 | 207 | :return Sorting weight. 208 | :rtype: int 209 | """ 210 | if not four_item[2]: # /all /fg /bg 211 | return four_item[3] - 200 212 | if four_item[2] < 10 or four_item[0].startswith('auto'): # b f i u or auto colors 213 | return four_item[2] - 100 214 | return four_item[2] 215 | four_item_tuples.sort(key=sorter) 216 | 217 | return four_item_tuples 218 | -------------------------------------------------------------------------------- /ZabbixTool/lib_zabbix/w_lib/mylib/xlwt/Cell.py: -------------------------------------------------------------------------------- 1 | # -*- coding: windows-1252 -*- 2 | 3 | from struct import unpack, pack 4 | from . import BIFFRecords 5 | from .compat import xrange 6 | 7 | class StrCell(object): 8 | __slots__ = ["rowx", "colx", "xf_idx", "sst_idx"] 9 | 10 | def __init__(self, rowx, colx, xf_idx, sst_idx): 11 | self.rowx = rowx 12 | self.colx = colx 13 | self.xf_idx = xf_idx 14 | self.sst_idx = sst_idx 15 | 16 | def get_biff_data(self): 17 | # return BIFFRecords.LabelSSTRecord(self.rowx, self.colx, self.xf_idx, self.sst_idx).get() 18 | return pack('<5HL', 0x00FD, 10, self.rowx, self.colx, self.xf_idx, self.sst_idx) 19 | 20 | class BlankCell(object): 21 | __slots__ = ["rowx", "colx", "xf_idx"] 22 | 23 | def __init__(self, rowx, colx, xf_idx): 24 | self.rowx = rowx 25 | self.colx = colx 26 | self.xf_idx = xf_idx 27 | 28 | def get_biff_data(self): 29 | # return BIFFRecords.BlankRecord(self.rowx, self.colx, self.xf_idx).get() 30 | return pack('<5H', 0x0201, 6, self.rowx, self.colx, self.xf_idx) 31 | 32 | class MulBlankCell(object): 33 | __slots__ = ["rowx", "colx1", "colx2", "xf_idx"] 34 | 35 | def __init__(self, rowx, colx1, colx2, xf_idx): 36 | self.rowx = rowx 37 | self.colx1 = colx1 38 | self.colx2 = colx2 39 | self.xf_idx = xf_idx 40 | 41 | def get_biff_data(self): 42 | return BIFFRecords.MulBlankRecord(self.rowx, 43 | self.colx1, self.colx2, self.xf_idx).get() 44 | 45 | class NumberCell(object): 46 | __slots__ = ["rowx", "colx", "xf_idx", "number"] 47 | 48 | def __init__(self, rowx, colx, xf_idx, number): 49 | self.rowx = rowx 50 | self.colx = colx 51 | self.xf_idx = xf_idx 52 | self.number = float(number) 53 | 54 | def get_encoded_data(self): 55 | rk_encoded = 0 56 | num = self.number 57 | 58 | # The four possible kinds of RK encoding are *not* mutually exclusive. 59 | # The 30-bit integer variety picks up the most. 60 | # In the code below, the four varieties are checked in descending order 61 | # of bangs per buck, or not at all. 62 | # SJM 2007-10-01 63 | 64 | if -0x20000000 <= num < 0x20000000: # fits in 30-bit *signed* int 65 | inum = int(num) 66 | if inum == num: # survives round-trip 67 | # print "30-bit integer RK", inum, hex(inum) 68 | rk_encoded = 2 | (inum << 2) 69 | return 1, rk_encoded 70 | 71 | temp = num * 100 72 | 73 | if -0x20000000 <= temp < 0x20000000: 74 | # That was step 1: the coded value will fit in 75 | # a 30-bit signed integer. 76 | itemp = int(round(temp, 0)) 77 | # That was step 2: "itemp" is the best candidate coded value. 78 | # Now for step 3: simulate the decoding, 79 | # to check for round-trip correctness. 80 | if itemp / 100.0 == num: 81 | # print "30-bit integer RK*100", itemp, hex(itemp) 82 | rk_encoded = 3 | (itemp << 2) 83 | return 1, rk_encoded 84 | 85 | if 0: # Cost of extra pack+unpack not justified by tiny yield. 86 | packed = pack('