#

pak目录/opt
blank目录 /usr/local
设置selinux=disabled重启

#

1,安装数据库
autoconf: 生成configure脚本
automake:生成Makefile.in
安装后的配置库管理:
(1) 导出二进制程序目录至PATH环境变量中;
编辑文件/etc/profile.d/NAME.sh
export PATH=/PATH/TO/BIN:$PATH

(2) 导出库文件路径
编辑/etc/ld.so.conf.d/NAME.conf
添加新的库文件所在目录至此文件中;

让系统重新生成缓存:
ldconfig [-v]

(3) 导出头文件
基于链接的方式实现:
ln -sv

(4) 导出帮助手册
编辑/etc/man.config文件
添加一个MANPATH

cmake指定编译选项的方式不同于make,其实现方式对比如下:
./configure cmake .
./configure —help cmake . -LH or ccmake .

指定安装文件的安装路径时常用的选项:
-DCMAKE_INSTALL_PREFIX=/usr/local/mysql
-DMYSQL_DATADIR=/data/mysql
-DSYSCONFDIR=/etc

默认编译的存储引擎包括:csv、myisam、myisammrg和heap。若要安装其它存储引擎,可以使用类似如下编译选项:
-DWITH_INNOBASE_STORAGE_ENGINE=1
-DWITH_ARCHIVE_STORAGE_ENGINE=1
-DWITH_BLACKHOLE_STORAGE_ENGINE=1
-DWITH_FEDERATED_STORAGE_ENGINE=1

若要明确指定不编译某存储引擎,可以使用类似如下的选项:
-DWITHOUT_<ENGINE>_STORAGE_ENGINE=1
比如:
-DWITHOUT_EXAMPLE_STORAGE_ENGINE=1
-DWITHOUT_FEDERATED_STORAGE_ENGINE=1
-DWITHOUT_PARTITION_STORAGE_ENGINE=1

如若要编译进其它功能,如SSL等,则可使用类似如下选项来实现编译时使用某库或不使用某库:
-DWITH_READLINE=1
-DWITH_SSL=system
-DWITH_ZLIB=system
-DWITH_LIBWRAP=0

其它常用的选项:
-DMYSQL_TCP_PORT=3306
-DMYSQL_UNIX_ADDR=/tmp/mysql.sock
-DENABLED_LOCAL_INFILE=1
-DEXTRA_CHARSETS=all
-DDEFAULT_CHARSET=utf8
-DDEFAULT_COLLATION=utf8_general_ci
-DWITH_DEBUG=0
-DENABLE_PROFILING=1

如果想清理此前的编译所生成的文件,则需要使用如下命令:
make clean
rm CMakeCache.txt

yum cmake gcc openssl-devel ncurses-devel libaio-devel gcc-c++ bison gcc-g77 autoconf automake zlib fiex libxml libmcrypt libtool-ltdl-devel*

cmake . -DWITH_BOOST=/opt/mysql-5.7.21/boost/boost_1_59_0/ \
-DCMAKE_INSTALL_PREFIX=/usr/local/mysql-5.7.21 \
-DSYSCONFDIR=/etc \
-DWITH_SSL=system \
-DDEFAULT_CHARSET=utf8 \
-DWITH_ZLIB=system \
-DWITH_LIBWRAP=0 \
-DMYSQL_UNIX_ADDR=/database/mysql.sock \
-DDEFAULT_COLLATION=utf8_general_ci \
-DWITH_INNOBASE_STORAGE_ENGINE=1 \
-DWITH_ARCHIVE_STORAGE_ENGINE=1 \
-DWITH_BLACKHOLE_STORAGE_ENGINE=1 \
-DMYSQL_DATADIR=/database \
-DENABLE_DOWNLOADS=1

[mysqld]
datadir=/database
socket=/database/mysql.sock
user=mysql

Disabling symbolic-links is recommended to prevent assorted security risks

symbolic-links=0
explicit_defaults_for_timestamp=1
innodb_file_per_table=on
innodb_buffer_pool_size=28G
skip_name_resolve=1
innodb_flush_log_at_trx_commit=1

gtid_mode=0

innodb_log_buffer_size=64M
key_buffer_size=1024M
tmp_table_size=512M
max_heap_table_size=512M
read_buffer_size=16M
read_rnd_buffer_size=16M
sort_buffer_size=512M
max_connections=1024
query_cache_type=1
query_cache_size=64M
innodb_write_io_threads = 24
innodb_read_io_threads = 24
innodb_page_cleaners=4
innodb_use_native_aio=on
innodb_adaptive_flushing=on
innodb_change_buffer_max_size=50
innodb_random_read_ahead=on
innodb_thread_concurrency = 24
thread_cache_size=300
max_connect_errors=3000
max_connections=3000
innodb_autoinc_lock_mode=2
innodb_change_buffering=all

innodb_monitor_reset=’latch’
innodb_spin_wait_delay=1
innodb_adaptive_hash_index=off
innodb_flush_neighbors=1
innodb_log_compressed_pages=0

innodb_buffer_pool_chunk_size=1G
innodb_buffer_pool_instances=28

default-time-zone=timezone
default-time-zone = ‘+8:00’
innodb_buffer_pool_dump_at_shutdown=1
innodb_buffer_pool_load_at_startup = 1
performance_schema=ON

[mysqld_safe]
log-error=/database/error.log
pid-file=/database/mysqld.pid

useradd -r mysql

初始化

  1. ../bin/mysqld --defaults-file=/etc/my.cnf --initialize-insecure --user=mysql --datadir=/database/
  2. chmod -R 755 /database/
  3. export PATH=/usr/local/mysql-5.7.21/bin:$PATH

启动服务

  1. /usr/local/mysql-5.7.21/support-files
  2. ./mysql.server start

2,安装httpd

  1. yum -y install bzip2-devel libmcrypt-devel libxml2-devel libpng-devel freetype-devel libjpeg-turbo-devel openssl-devel bzip2-devel libcurl-devel libjpeg libpng freetype libjpeg-devel libpng-devel freetype-devel libxslt-deve expat-devel
  2. ./configure --prefix=/usr/local/apr
  3. make &amp;&amp;make install
  4. ./configure --prefix=/usr/local/apr-util --with-apr=/usr/local/apr/
  5. make &amp;&amp;make install
  6. # groupadd -r apache
  7. # useradd -r -g apache apache
  8. ./configure --prefix=/usr/local/apache24 --sysconf=/etc/httpd --enable-so --enable-ssl --enable-cgi --enable-rewrite --with-zlib --with-pcre --with-apr=/usr/local/apr --with-apr-util=/usr/local/apr-util/ --enable-modules=most --enable-mpms-shared=all --with-mpm=event
  9. make &amp;&amp;make install
  10. yum install bzip2
  11. yum install libxslt-devel

安装php

  1. ./configure --with-curl --with-freetype-dir --with-gd --with-gettext --with-iconv-dir --with-kerberos --with-libdir=lib64 --with-libxml-dir --with-pdo-mysql=mysqlnd --with-mysqli=mysqlnd --with-openssl --with-pcre-regex --with-pdo-mysql --with-pdo-sqlite --with-pear --with-png-dir --with-jpeg-dir --with-xmlrpc --with-xsl --with-zlib --with-bz2 --with-mhash --enable-fpm --enable-bcmath --enable-libxml --enable-inline-optimization --enable-gd-native-ttf --enable-mbregex --enable-mbstring --enable-opcache --enable-pcntl --enable-shmop --enable-soap --enable-sockets --enable-sysvsem --enable-sysvshm --enable-xml --enable-zip --with-apxs2=/usr/local/apache24/bin/apxs --with-png-dir --with-mcrypt --with-config-file-path=/etc --with-config-file-scan-dir=/etc/php.d --with-bz2 --enable-maintainer-zts

—with-apxs2=/usr/local/apache/bin/apxs
—with-mysqli=/usr/local/mysql/bin/mysql_configh另一种数据库处理接口
—with-freetype-dir 字体处理
—with-zlib压缩库
—with-libxml-dir=/usr处理xml文档
—enable-sockets支持sockets方式进行通信
—with-mcrypt支持加解密库
—with-config-file-scan-dir=/etc/php.d 点ini结尾的其他配置文件放置目录
—with-bz2
—enable-maintainer-zts 如果是worker和evenv必须加上

  1. # tar xf xcache-3.0.3.tar.gz
  2. # cd xcache-3.0.3
  3. # /usr/local/php/bin/phpize xcache借助/usr/local/php/bin/phpize模块生成的
  4. # ./configure --enable-xcache --with-php-config=/usr/local/php/bin/php-config
  5. # make &amp;&amp; make install
  6. # 编程成php的扩展
  7. # /usr/local/php/bin/phpize --with-php-config=/usr/local/php/bin/php-config
  8. # 安装结束时,会出现类似如下行:
  9. # Installing shared extensions: /usr/local/php/lib/php/extensions/no-debug-zts-20100525/
  10. # 编辑php.ini,整合php和xcache:
  11. # 首先将xcache提供的样例配置导入php.ini
  12. # mkdir /etc/php.d
  13. # cp xcache.ini /etc/php.d
  14. # 说明:xcache.ini文件在xcache的源码目录中。
  15. # 接下来编辑/etc/php.d/xcache.ini,找到zend_extension开头的行,修改为如下行:
  16. # zend_extension = /usr/local/php/lib/php/extensions/no-debug-zts-20100525/xcache.so
  17. cp php.ini-production /etc/php.ini
  18. mkdir -pv /var/lib/php/session

4,设置httpd
设置httpd.conf

ServerName 0.0.0.0
添加php解释器
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps

添加index
DirectoryIndex index.php index.html

User apache
Group apache

测试页
<?php
phpinfo();
?>

设置php.ini

  1. post_max_size = 16M
  2. enable_post_data_reading = On
  3. max_execution_time = 300
  4. max_input_time = 300
  5. date.timezone = "Asia/Shanghai"

设置httpd.conf虚拟主机配置

  1. LoadModule mpm_event_module modules/mod_mpm_event.so
  2. &lt;IfModule mpm_event_module&gt;
  3. StartServers 10
  4. MinSpareThreads 75
  5. MaxSpareThreads 250
  6. ThreadsPerChild 25
  7. MaxRequestWorkers 400
  8. MaxConnectionsPerChild 0
  9. &lt;/IfModule&gt;
  10. &lt;IfModule mime_module&gt;
  11. AddType application/x-compress .Z
  12. AddType application/x-gzip .gz .tgz
  13. AddType application/x-httpd-php .php
  14. AddType application/x-httpd-php-source .phps
  15. &lt;/IfModule&gt;
  16. &lt;FilesMatch \.php$&gt;
  17. SetHandler application/x-httpd-php
  18. &lt;/FilesMatch&gt;
  19. AddType text/html .php

不能创建session先注释

  1. #php_value session.save_handler "files"
  2. #php_value session.save_path "/var/lib/php/session"
  1. &lt;VirtualHost *:80&gt;
  2. ServerName 0.0.0.0
  3. DocumentRoot "/usr/share/zabbix"
  4. DirectoryIndex index.html index.php
  5. Alias /zabbix /usr/share/zabbix
  6. &lt;Directory "/usr/share/zabbix"&gt;
  7. Options FollowSymLinks
  8. AllowOverride None
  9. Require all granted
  10. &lt;IfModule mod_php5.c&gt;
  11. php_value max_execution_time 300
  12. php_value memory_limit 128M
  13. php_value post_max_size 16M
  14. php_value upload_max_filesize 2M
  15. php_value max_input_time 300
  16. php_value always_populate_raw_post_data -1
  17. # php_value date.timezone Asia/Shanghai
  18. &lt;/IfModule&gt;
  19. &lt;IfModule mod_deflate.c&gt;
  20. # 设置压缩类型
  21. AddOutputFilterByType DEFLATE text/plain
  22. AddOutputFilterByType DEFLATE text/html
  23. AddOutputFilterByType DEFLATE text/xml
  24. AddOutputFilterByType DEFLATE text/css
  25. AddOutputFilterByType DEFLATE text/javascript
  26. AddOutputFilterByType DEFLATE image/svg+xml
  27. AddOutputFilterByType DEFLATE image/x-icon
  28. AddOutputFilterByType DEFLATE application/xml
  29. AddOutputFilterByType DEFLATE application/xhtml+xml
  30. AddOutputFilterByType DEFLATE application/rss+xml
  31. AddOutputFilterByType DEFLATE application/javascript
  32. AddOutputFilterByType DEFLATE application/x-javascript
  33. AddOutputFilterByType DEFLATE text/php
  34. AddOutputFilterByType DEFLATE image/gif image/png image/jpe image/swf image/jpeg image/bmp
  35. &lt;/IfModule&gt;
  36. &lt;IfModule mod_headers.c&gt;
  37. # 自定义Header
  38. &lt;/IfModule&gt;
  39. &lt;/Directory&gt;
  40. &lt;/VirtualHost&gt;

设置时区php.ini

  1. date.timezone = "Asia/Shanghai"

修改zabbix web

  1. #include/classes/setup/CFrontendSetup.php
  2. #public function checkPhpAlwaysPopulateRawPostData() {
  3. # $current = ini_get('always_populate_raw_post_data');
  4. # $current=-1;
  5. #
  6. # return [
  7. # 'name' =&gt; _s('PHP option "%1$s"', 'always_populate_raw_post_data'),
  8. # 'current' =&gt; ($current != -1) ? _('on') : _('off'),
  9. # 'required' =&gt; _('off'),
  10. # 'result' =&gt; ($current != -1) ? self::CHECK_FATAL : self::CHECK_OK,
  11. # 'error' =&gt; _s('PHP option "%1$s" must be set to "%2$s"', 'always_populate_raw_post_data', -1)
  12. # ];
  13. #}

中文支持
[root@zabbix-server include]# vi defines.inc.php
修改第93行
define(‘ZBX_FONT_NAME’,’msyh’);
修改第45行改为
define(‘ZBX_GRAPH_FONT_NAME’,’msyh’)
拷贝msyhbd.ttf msyh.ttf到apache 的zabbix_web程序root的font下面

cp zabbix.conf.php.example zabbix.conf.php

chown -R apache:apache /usr/share/zabbix/

chown -R apache:apache /var/lib/php/session

启动服务:
/usr/local/apache24/bin/apachectl stop

export PATH=/usr/local/apache24/bin:$PATH

检测模块
[root@zabbix-service ~]# httpd -M
Loaded Modules:
core_module (static)
so_module (static)
http_module (static)
mpm_event_module (shared)
authn_file_module (shared)
authn_core_module (shared)
authz_host_module (shared)
authz_groupfile_module (shared)
authz_user_module (shared)
authz_core_module (shared)
access_compat_module (shared)
auth_basic_module (shared)
reqtimeout_module (shared)
filter_module (shared)
mime_module (shared)
log_config_module (shared)
env_module (shared)
headers_module (shared)
setenvif_module (shared)
version_module (shared)
unixd_module (shared)
status_module (shared)
autoindex_module (shared)
dir_module (shared)
alias_module (shared)
php7_module (shared)

5,编译安装zabbix
yum install net-snmp-devel
配置
export JAVA_HOME=/usr/local/jdk1.7.0_79
export JAVACMD=$JAVA_HOME/bin/java
export JRE_HOME=$JAVA_HOME/jre
export CLASSPATH=.:$JAVA_HOME/lib/tools.jar:$JAVA_HOME/lib:$JAVA_HOME/lib/dt.jar
export PATH=$JAVA_HOME/bin:$PATH

yum install libevent-devel perl-devel

./configure —prefix=/usr/local/zabbix-3.4.8 —enable-java —enable-server —enable-agent —with-mysql=/usr/local/mysql-5.7.21/bin/mysql_config —enable-ipv6 —with-net-snmp —with-libcurl —with-libxml2

groupadd zabbix
useradd -g zabbix zabbix

6,配置数据库
create database zabbix character set utf8 collate utf8_bin;
grant all on . to ‘zabbix’@’%’ IDENTIFIED BY ‘zabbix’;
flush privileges;

/opt/zabbix-3.2.7/database/mysql
/usr/local/mysql-5.7.21/bin/mysql -uzabbix -p zabbix <schema.sql
/usr/local/mysql-5.7.21/bin/mysql -uzabbix -p zabbix <images.sql
/usr/local/mysql-5.7.21/bin/mysql -uzabbix -p zabbix <data.sql

查看所有用户
SELECT DISTINCT CONCAT(‘User: ‘’’,user,’’’@’’’,host,’’’;’) AS query FROM mysql.user;

查看用户权限
show grants for ‘root’@’localhost’;

对比root用户在几个权限系统表中的数据
select * from mysql.user where user=’root’ and host=’localhost’;

撤销授权
REVOKE privilege ON databasename.tablename FROM ‘username’@’host’;

删除用户
DROP USER ‘username’@’host’;
Delete from user where user = “user_name” and host = “host_name” ;

修改所有密码
update mysql.user set authentication_string=password(‘zabbix’);

修改zabbix server密码
use zabbix
update users set passwd=md5(“zabbix”) where userid=’1’;

7,配置zabbix server和zabbix agent

mkdir -pv /var/log/zabbix/ /var/run/zabbix/ /var/log/snmptrap/ /usr/lib/zabbix/alertscripts /usr/lib/zabbix/externalscripts

chown -R zabbix:zabbix /var/log/zabbix/ /var/run/zabbix/ /var/log/snmptrap/ /usr/lib/zabbix/alertscripts /usr/lib/zabbix/externalscripts

chmod -R 755 /usr/lib/zabbix/alertscripts/ /usr/lib/zabbix/externalscripts/

zabbix server配置
LogFile=/var/log/zabbix/zabbix_server.log
LogFileSize=1024
DebugLevel=3
PidFile=/var/run/zabbix/zabbix_server.pid
DBHost=localhost
DBName=zabbix
DBUser=zabbix
DBPassword=zabbix
DBSocket=/database/mysql.sock
StartPollers=30
StartPollersUnreachable=10
StartPingers=30
StartDiscoverers=30
StartTimers=10
SNMPTrapperFile=/var/log/snmptrap/snmptrap.log
MaxHousekeeperDelete=1000000
SenderFrequency=60 #在介质类型配置(尝试间隔参数)中查找失败警报的重试频率,默认情况下为10秒。SenderFrequency的默认值为 30秒。
CacheSize=2G
CacheUpdateFrequency=120
StartDBSyncers=24
HistoryCacheSize=2048M
HistoryIndexCacheSize=2048M
TrendCacheSize=2048M
ValueCacheSize=2048M
Timeout=30
UnreachablePeriod=120
UnavailableDelay=60
UnreachableDelay=5
AlertScriptsPath=/usr/lib/zabbix/alertscripts
ExternalScripts=/usr/lib/zabbix/externalscripts
LogSlowQueries=5000

zabbix agentd配置

  1. [root@zabbix ~]# grep -Ev '^#|^$' /etc/zabbix/zabbix_agentd.conf
  2. PidFile=/var/run/zabbix/zabbix_agentd.pid
  3. LogFile=/var/log/zabbix/zabbix_agentd.log
  4. LogFileSize=0
  5. DebugLevel=3
  6. Server=172.16.7.146
  7. ServerActive=172.16.7.146
  8. Hostname=172.16.7.146
  9. Timeout=3
  10. Include=/usr/local/zabbix-3.4.8/etc/zabbix_agentd.conf.d/*.conf
  11. #UserParameter=test.tail,/usr/bin/tail -l /usr/lib/zabbix/alertscripts/zabbix_moniter.test
  12. #UserParameter=snmp.ip.discover_snmp,/etc/zabbix/shell/snmp_check.py
  13. #UserParameter=snmp.inter.check[*],/etc/zabbix/shell/inter_check.py $1
  14. #UserParameter=snmp.ip.discover_snmpV2,/etc/zabbix/shell/snmp_check2.py
  15. #UserParameter=snmp.inter.checkV2[*],/etc/zabbix/shell/inter_check.py $1
  16. #UserParameter=win_cpu.load[*],/etc/zabbix/shell/win_cpu.py $1
  17. #UserParameter=win_cpu.loadV2[*],/etc/zabbix/shell/win_cpu2.py $1

cp /usr/local/mysql-5.7.21/lib/libmysqlclient.so.20 /lib64

避免sock问题
chmod -R 755 /database/

启动服务
/usr/local/zabbix-3.4.8/sbin/zabbix_server -c /usr/local/zabbix-3.4.8/etc/zabbix_server.conf
/usr/local/zabbix-3.4.8/sbin/zabbix_agentd -c /usr/local/zabbix-3.4.8/etc/zabbix_agentd.conf

关闭程序
killall zabbix_server
killall zabbix_agentd

8,部署zabbix web
cp -r php/* /usr/share/zabbix/
chown -R apache:apache /usr/share/zabbix/

9,安装python3.5
yum install sqlite-devel
./configure —prefix=/usr/local/python-3.5 —enable-shared —enable-loadable-sqlite-extensions
make & make install

cp /usr/local/python-3.5/lib/libpython3.5m.so.1.0 /lib64/
/usr/local/python-3.5/bin/pip3.5 install —upgrade pip

export PATH=/usr/local/python-3.5/bin:$PATH

10,数据库分区维护[]
分区https://www.zabbix.org/wiki/Docs/howto/mysql_partition

  1. #########删除201708110000之前的所有数据。每天一个分区
  2. call partition_drop('zabbix','history','201708110000');
  3. call partition_drop('zabbix','history_log','201708110000');
  4. call partition_drop('zabbix','history_str','201708110000');
  5. call partition_drop('zabbix','history_text','201708110000');
  6. call partition_drop('zabbix','history_uint','201708110000');
  7. call partition_drop('zabbix','trends','201708110000');
  8. call partition_drop('zabbix','trends_uint','201708110000');
  9. ##########
  10. CALL partition_maintenance('zabbix', 'history', 365, 24, 90);
  11. CALL partition_maintenance('zabbix', 'history_log', 365, 24, 90);
  12. CALL partition_maintenance('zabbix', 'history_str', 365, 24, 90);
  13. CALL partition_maintenance('zabbix', 'history_text', 365, 24, 90);
  14. CALL partition_maintenance('zabbix', 'history_uint', 365, 24, 90);
  15. CALL partition_maintenance('zabbix', 'trends', 365, 24, 90);
  16. CALL partition_maintenance('zabbix', 'trends_uint', 365, 24, 90);
  17. 保留天数 265 (注意5天前将被删除)
  18. 创建时间间隔 24小时
  19. 创建分区数 90 (分区不会自动创建,所以可以创建多点)
  20. 定时任务:
  21. */1 * * * * ntpdate time.windows.com
  22. */3 * * * * /usr/local/python-3.5.0/bin/python3.5 /etc/zabbix/shell/zabbix_api.py
  23. 00 08 * * * /usr/local/python-3.5.0/bin/python3.5 /etc/zabbix/shell/Partition_Clear.py
  24. 00 10 * * * /usr/local/python-3.5.0/bin/python3.5 /etc/zabbix/shell/Partition_Create.py
  25. ##################################################################
  26. 定时自动创建创建分区
  27. ##################################################################
  28. #!/usr/bin/env python
  29. #-*- coding:utf-8 -*-
  30. import pymysql,datetime
  31. class db_action(object):
  32. def __init__(self,host,port,user,password,database="mysql",charset="utf8"):
  33. self.host=host
  34. self.port=port
  35. self.user=user
  36. self.password=password
  37. self.database=database
  38. self.charset=charset
  39. self.__cursor=self.__conn().cursor()
  40. def __conn(self):
  41. return pymysql.Connect(host=self.host,port=self.port,user=self.user,\
  42. password=self.password,database=self.database,\
  43. charset=self.charset)
  44. def callproc(self,pl,t):
  45. '''存储过程'''
  46. ret=self.__cursor.callproc(pl,args=t)
  47. return ret
  48. def execute(self, tables_name):
  49. '''sql'''
  50. ret = self.__cursor.execute('select count(*) from PARTITIONS WHERE TABLE_NAME=%s and TABLE_ROWS=0',\
  51. [tables_name])
  52. return self.__cursor.fetchone()[0]
  53. if __name__ == '__main__':
  54. par_count=db_action(host='172.16.6.38',port=3306,user='root',password="zabbix",database="information_schema",charset='utf8')
  55. par_create=db_action(host='172.16.6.38',port=3306,user='root',password="zabbix",database="zabbix",charset='utf8')
  56. history_count=par_count.execute('history')
  57. trends_count=par_count.execute('trends_uint')
  58. with open('/root/pariton_create.log', encoding='utf-8', mode='a+') as f:
  59. f.write('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@'+'\n')
  60. with open('/root/pariton_create.log', encoding='utf-8', mode='a+') as f:
  61. f.write('history分区统计' + str(history_count)+'\n')
  62. with open('/root/pariton_create.log', encoding='utf-8', mode='a+') as f:
  63. f.write('trends_uint分区统计' + str(trends_count) + '\n')
  64. rets = []
  65. if history_count&lt;=7:
  66. ret1=par_create.callproc('partition_maintenance',('zabbix','history',7, 24, 30,))
  67. ret2=par_create.callproc('partition_maintenance',('zabbix','history_log',7, 24, 30,))
  68. ret3=par_create.callproc('partition_maintenance',('zabbix','history_str',7, 24, 30,))
  69. ret4=par_create.callproc('partition_maintenance',('zabbix','history_text',7, 24, 30,))
  70. ret5=par_create.callproc('partition_maintenance',('zabbix','history_uint',7, 24, 30,))
  71. rets.append(ret1)
  72. rets.append(ret2)
  73. rets.append(ret3)
  74. rets.append(ret4)
  75. rets.append(ret5)
  76. if trends_count &lt;= 7:
  77. ret6=par_create.callproc('partition_maintenance', ('zabbix', 'trends',30, 24, 30,))
  78. ret7=par_create.callproc('partition_maintenance', ('zabbix', 'trends_uint',30, 24, 30,))
  79. rets.append(ret6)
  80. rets.append(ret7)
  81. if rets:
  82. with open('/root/pariton_create.log',encoding='utf-8',mode='a+') as f:
  83. f.write(rets+'\n')
  84. ############################################################
  85. 定时自动删除数据被清空分区。
  86. ############################################################
  87. [root@zabbix shell]# cat Partition_Clear.py
  88. #!/usr/bin/env python
  89. #-*- coding:utf-8 -*-
  90. import pymysql,datetime
  91. class db_action(object):
  92. def __init__(self,host,port,user,password,database="mysql",charset="utf8"):
  93. self.host=host
  94. self.port=port
  95. self.user=user
  96. self.password=password
  97. self.database=database
  98. self.charset=charset
  99. self.__cursor=self.__conn().cursor()
  100. def __conn(self):
  101. return pymysql.Connect(host=self.host,port=self.port,user=self.user,\
  102. password=self.password,database=self.database,\
  103. charset=self.charset)
  104. def callproc(self,pl,t):
  105. ret=self.__cursor.callproc(pl,args=t)
  106. return ret
  107. if __name__ == '__main__':
  108. db=db_action(host='172.16.6.38',port=3306,user='root',password="zabbix",database="zabbix",charset='utf8')
  109. rets=[]
  110. ret=db.callproc('partition_drop',('zabbix','history',(datetime.datetime.now()+datetime.timedelta(days=-1)).strftime('%Y%m%d0000'),))
  111. rets.append(ret)
  112. ret=db.callproc('partition_drop',('zabbix','history_log',(datetime.datetime.now()+datetime.timedelta(days=-1)).strftime('%Y%m%d0000'),))
  113. rets.append(ret)
  114. ret=db.callproc('partition_drop',('zabbix','history_str',(datetime.datetime.now()+datetime.timedelta(days=-1)).strftime('%Y%m%d0000'),))
  115. rets.append(ret)
  116. ret=db.callproc('partition_drop',('zabbix','history_text',(datetime.datetime.now()+datetime.timedelta(days=-1)).strftime('%Y%m%d0000'),))
  117. rets.append(ret)
  118. ret=db.callproc('partition_drop',('zabbix','history_uint',(datetime.datetime.now()+datetime.timedelta(days=-1)).strftime('%Y%m%d0000'),))
  119. rets.append(ret)
  120. with open('/root/pariton_clear.log',encoding='utf-8',mode='a+') as f:
  121. f.write(str(rets)+'\n')
  122. #############################################################################
  123. 删除zabbix serversnmp检测
  124. 主机如果配置了snmp监控即可获取到snmp主机ip,如果取消就获取不到,及删除对应的检测。
  125. #############################################################################
  126. #!/usr/local/python
  127. #-*- coding:utf-8 -*-
  128. import json
  129. import urllib.request
  130. import urllib.error
  131. import urllib.parse
  132. import pymysql
  133. import re,logging,os
  134. class zabbix:
  135. def __init__(self,ip='172.16.7.145',zabser_name='Admin',zabser_pwd='zabbix'):
  136. self.ip=ip
  137. self.url='http://%s/zabbix/api_jsonrpc.php' %self.ip
  138. self.zabser_name=zabser_name
  139. self.zabser_pwd=zabser_pwd
  140. self.header = {"Content-Type": "application/json"}
  141. def get_func(self,post_body):
  142. # Auth Successful. The Auth ID Is:",response['result']
  143. data = bytes(post_body,'utf-8') #urllib.parse.urlencode()转json的有问题,所以直接bytes
  144. request = urllib.request.Request(self.url,data)
  145. for key in self.header:
  146. request.add_header(key,self.header[key])
  147. try:
  148. result = urllib.request.urlopen(request)
  149. res = result.read().decode('utf-8')
  150. except urllib.error.URLError as e:
  151. print ("Auth Failed, Please Check Your Name AndPassword:",e.code)
  152. else:
  153. response = json.loads(res)
  154. result.close()
  155. return response
  156. def get_authid(self):
  157. '''获取认证信息'''
  158. authid_body=self.auth_body = json.dumps(
  159. {
  160. "jsonrpc": "2.0",
  161. "method": "user.login",
  162. "params": {
  163. "user": self.zabser_name,
  164. "password": self.zabser_pwd
  165. },
  166. "id": 0
  167. }, ensure_ascii=False
  168. )
  169. response=self.get_func(authid_body)
  170. id=response['id']
  171. authid=response['result']
  172. return id,authid
  173. def get_hostids(self,hostname='172.16.6.38'):
  174. '''获取hostids'''
  175. hostids_body = json.dumps({
  176. "jsonrpc": "2.0",
  177. "method": "host.get",
  178. "params": {
  179. "output": "extend",
  180. "filter": {
  181. "host": [
  182. hostname
  183. ]
  184. }
  185. },
  186. "auth": self.get_authid()[1],
  187. "id": self.get_authid()[0]
  188. })
  189. response=self.get_func(hostids_body)
  190. hostids=response['result'][0]['hostid']
  191. return hostids
  192. def get_itemsid(self):
  193. '''通过hostid获取itemsid'''
  194. itemsid_list=[]
  195. for line in self.handler_key():
  196. items_body = json.dumps({
  197. "jsonrpc": "2.0",
  198. "method": "item.get",
  199. "params": {
  200. "output": "extend",
  201. "hostids": self.get_hostids(),
  202. "search": {
  203. "key_": line
  204. },
  205. "sortfield": "name"
  206. },
  207. "auth": self.get_authid()[1],
  208. "id": self.get_authid()[0]
  209. })
  210. response = self.get_func(items_body)
  211. itemsid_list.append(response['result'][0]['itemid'])
  212. return itemsid_list
  213. def handler_itemsid(self):
  214. '''从数据库中获取items key列表 获取shmp的ip列表'''
  215. items_body = json.dumps({
  216. "jsonrpc": "2.0",
  217. "method": "item.get",
  218. "params": {
  219. "output": "extend",
  220. "hostids": self.get_hostids(),
  221. "sortfield": "name"
  222. },
  223. "auth": self.get_authid()[1],
  224. "id": self.get_authid()[0]
  225. })
  226. response = self.get_func(items_body)
  227. key_list=[line['key_'] for line in response['result']]
  228. ip_list=[]
  229. for line in key_list:
  230. try:
  231. ip=re.search(r'\[((\d+.){3}\d+)\]',line)
  232. ip_list.append(ip.groups()[0])
  233. except AttributeError:
  234. continue
  235. return ip_list,key_list
  236. def del_itemsid(self):
  237. '''删除不存在的items'''
  238. items_body=json.dumps({
  239. "jsonrpc": "2.0",
  240. "method": "item.delete",
  241. "params":self.get_itemsid(),
  242. "auth": self.get_authid()[1],
  243. "id": self.get_authid()[0]
  244. })
  245. response = self.get_func(items_body)
  246. self.save_log(response)
  247. return response
  248. def handler_key(self):
  249. '''获取需要删除的key 列表'''
  250. conn = pymysql.connect(host=self.ip, port=3306, user='root', passwd='zabbix', db='zabbix')
  251. cur = conn.cursor()
  252. cur.execute("select ip from zabbix.interface where port=161;")
  253. res = cur.fetchall()
  254. conn.close()
  255. list_ip=[line[0] for line in res]
  256. ip_list, key_list=self.handler_itemsid()
  257. tmpip_list=[]
  258. for line in ip_list:
  259. if line not in list_ip:
  260. tmpip_list.append(line)
  261. ######输出key
  262. tmpkey_list=[]
  263. for i in tmpip_list:
  264. for j in key_list:
  265. if re.findall(i,j):tmpkey_list.append(j)
  266. return tmpkey_list
  267. @staticmethod
  268. def save_log(msg):
  269. '''日志处理'''
  270. logger=logging.getLogger(os.path.basename(__file__))
  271. console_handler = logging.StreamHandler()
  272. formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
  273. datefmt='%Y-%m-%d %H:%M:%S', style='%')
  274. console_handler.setFormatter(formatter)
  275. console_handler.setLevel(10)
  276. file_handler = logging.FileHandler('zkapi.log')
  277. file_handler.setFormatter(formatter)
  278. file_handler.setLevel(10)
  279. logger.addHandler(console_handler)
  280. logger.addHandler(file_handler)
  281. logger.setLevel(10)
  282. logger.info(msg)
  283. if __name__ == '__main__':
  284. z=zabbix()
  285. res=z.del_itemsid()

11,初始化系统
net.ipv4.tcp_keepalive_time = 1200
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_timestamps = 1
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_syn_retries = 3
net.ipv4.tcp_retries2 = 3
net.core.netdev_max_backlog = 2621440
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 2621440
net.core.rmem_default = 8388608
net.core.rmem_max = 16777216
net.core.wmem_default = 8388608
net.core.wmem_max = 16777216
net.ipv4.tcp_mem = 94500000 915000000 927000000
net.ipv4.tcp_sack = 1
net.ipv4.tcp_fack = 1
kernel.shmmni = 4096
kernel.shmmax = 68719476736
kernel.shmall = 4294967296
fs.file-max = 6553500

kernel.pid_max=3276800
kernel.threads-max=51525800
vm.max_map_count=6553000

vm.dirty_background_ratio=2
vm.dirty_ratio=40

  • soft nofile 655350
  • soft nproc 655350
  • hard nofile 655350
  • hard nproc 655350

12,邮件和微信报警维护[]

  1. 1,报警媒介
  2. weixin
  3. zabbix_weixin.py
  4. {ALERT.SUBJECT}
  5. {ALERT.MESSAGE}
  6. SMS
  7. zabbix_sms.py
  8. {ALERT.SENDTO}
  9. {ALERT.MESSAGE}
  10. Email
  11. zabbix_sendmail.py
  12. {ALERT.SENDTO}
  13. {ALERT.SUBJECT}
  14. {ALERT.MESSAGE}
  15. 动作:
  16. 名称mail Report problems to Zabbix administrators
  17. A 触发器示警度 = 灾难 移除
  18. B 触发器示警度 = 严重 移除
  19. C 触发器示警度 = 一般严重 移除
  20. D 触发器示警度 = 警告 移除
  21. E 触发器示警度 = 信息 移除
  22. F 触发器示警度 = 未分类 移除
  23. 操作:
  24. 60s
  25. {HOST.NAME} {TRIGGER.STATUS}: {TRIGGER.NAME} {EVENT.TIME}
  26. 告警主机: {HOST.NAME}
  27. 告警 IP: {HOST.IP}
  28. 触发状态: {TRIGGER.STATUS}
  29. 告警时间: {EVENT.DATE}-{EVENT.TIME}
  30. 告警等级: {TRIGGER.SEVERITY}
  31. 告警信息: {TRIGGER.NAME}
  32. 问题详情: {ITEM.NAME}:{ITEM.VALUE}
  33. 事件 ID: {EVENT.ID}
  34. 维护期间暂停操作
  35. 发送消息给用户: Admin (Zabbix Administrator) 通过 Email
  36. 发送消息给用户群组: Zabbix administrators 通过 Email
  37. 恢复动作
  38. {HOST.NAME} {TRIGGER.STATUS}: {TRIGGER.NAME} {EVENT.RECOVERY.TIME}
  39. 告警主机: {HOST.NAME}
  40. 告警 IP: {HOST.IP}
  41. 触发状态: {TRIGGER.STATUS}
  42. 告警时间: {EVENT.DATE}-{EVENT.TIME}
  43. 告警等级: {TRIGGER.SEVERITY}
  44. 告警信息: {TRIGGER.NAME}
  45. 问题详情: {ITEM.NAME}:{ITEM.VALUE}
  46. 事件 ID: {EVENT.ID}

13,模板维护[自动发现]
AlertScriptsPath=/usr/lib/zabbix/alertscripts 报警script
ExternalScripts=/usr/lib/zabbix/externalscripts 外部检查script

  1. ############################################################
  2. 邮件
  3. ############################################################
  4. #!/usr/bin/python
  5. #coding:utf-8
  6. import smtplib
  7. from email.mime.text import MIMEText
  8. import sys
  9. import time
  10. mail_host = 'mail.xxx.cn'
  11. mail_user = 'tiantao'
  12. mail_pass = 'xxxx'
  13. mail_postfix = 'xxx.cn'
  14. def send_mail(to_list,subject,content):
  15. me = mail_user+"&lt;"+mail_user+"@"+mail_postfix+"&gt;"
  16. msg = MIMEText(content,_charset="utf-8")
  17. msg['Subject'] = subject
  18. msg['From'] = me
  19. msg['to'] = to_list
  20. try:
  21. s = smtplib.SMTP()
  22. s.connect(mail_host)
  23. s.login(mail_user,mail_pass)
  24. s.sendmail(me,to_list,msg.as_string())
  25. s.close()
  26. return True
  27. except Exception as e:
  28. print(str(e))
  29. return False
  30. if __name__ == "__main__":
  31. send_mail(sys.argv[1], sys.argv[2], sys.argv[3])
  32. ##########################################################
  33. sms
  34. ##########################################################
  35. #!/usr/local/python-3.5.0/bin/python3.5
  36. import http.cookiejar
  37. import urllib.request
  38. import socket
  39. import json
  40. import sys
  41. from urllib.parse import quote
  42. class sendMessage():
  43. def __init__(self):
  44. self.cookieJar = http.cookiejar.LWPCookieJar()
  45. opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.cookieJar))
  46. urllib.request.install_opener(opener)
  47. def sendMessage(self,phone,content,url):
  48. socket.setdefaulttimeout(5)
  49. header = {'Content-Type':'application/x-www-form-urlencoded','charset':'utf-8'}
  50. request = urllib.request.Request(url,headers=header)
  51. request = urllib.request.urlopen(request)
  52. pageHtml = request.read().decode('UTF-8')
  53. print(pageHtml)
  54. request.close()
  55. if __name__ == '__main__':
  56. phone = str(sys.argv[1])
  57. content= str(sys.argv[2])
  58. content=quote(content)
  59. url='''http://172.16.5.31:8000/api/sms/?appid=xxx&amp;sign=xxx&amp;style=json&amp;mobile=%s&amp;message=%s''' %(phone,content)
  60. up = sendMessage()
  61. up.sendMessage(phone, content,url)
  62. ########################################################
  63. 微信
  64. ########################################################
  65. [root@zabbix-service alertscripts]# cat zabbix_weixin.py
  66. #!/usr/local/python-3.5.0/bin/python3.5
  67. import http.cookiejar
  68. import urllib.request
  69. import socket
  70. import json
  71. import sys
  72. class sendMessage():
  73. def __init__(self):
  74. self.cookieJar = http.cookiejar.LWPCookieJar()
  75. opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.cookieJar))
  76. urllib.request.install_opener(opener)
  77. def sendMessage(self,subject,content):
  78. socket.setdefaulttimeout(5)
  79. getTokenUrl="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=xxx&amp;corpsecret=xxxx"
  80. request = urllib.request.Request(getTokenUrl)
  81. request = urllib.request.urlopen(request)
  82. pageHtml = request.read().decode('UTF-8')
  83. if pageHtml:
  84. pageHtml=eval(pageHtml)
  85. token=pageHtml['access_token']
  86. request.close()
  87. data = { "touser": "@all","toparty": "@all", "msgtype": "text", "agentid": "1","text": { "content": subject+'\n'+content},"safe":"0"}
  88. url=" https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+token
  89. header = {'Content-Type':'application/x-www-form-urlencoded','charset':'utf-8'}
  90. jdata = json.dumps(data,ensure_ascii=False).encode('UTF-8')
  91. request = urllib.request.Request(url,data=jdata,headers=header)
  92. request = urllib.request.urlopen(request)
  93. pageHtml = request.read().decode('UTF-8')
  94. request.close()
  95. print(pageHtml)
  96. if __name__ == '__main__':
  97. #sendto=str(sys.argv[1])
  98. # subject = '微信测试'
  99. # content = '微信升级测试'
  100. subject = str(sys.argv[1])
  101. content = str(sys.argv[2])
  102. up = sendMessage()
  103. up.sendMessage(subject, content)

14,win cpu load监控
item名称 cpu_load
item类型 使用外部检查
cpuload.py[“{HOST.CONN}”]

  1. [root@zabbix externalscripts]# cat cpuload.py
  2. #!/usr/local/python
  3. #-*- coding:utf-8 -*-
  4. import netsnmp
  5. class SnmpClass(object):
  6. """
  7. SNMP
  8. """
  9. def __init__(self, oid="sysDescr", version=1, destHost="localhost", community="public"):
  10. self.oid = oid
  11. self.version = version
  12. self.destHost = destHost
  13. self.community = community
  14. @property
  15. def query(self):
  16. """
  17. snmpwalk
  18. """
  19. try:
  20. result = netsnmp.snmpwalk(self.oid,
  21. Version=self.version,
  22. DestHost=self.destHost,
  23. Community=self.community)
  24. except Exception as e:
  25. print(e)
  26. result = None
  27. return result
  28. def main(ip):
  29. cpuload=0
  30. test_obj = SnmpClass(oid="HOST-RESOURCES-MIB::hrProcessorLoad", destHost=ip)
  31. for line in test_obj.query:
  32. cpuload+=int(line)
  33. return cpuload/len(test_obj.query)
  34. if __name__ == '__main__':
  35. import sys
  36. ip=sys.argv[1]
  37. result=main(ip)
  38. print(int(result))

14,添加三方oid
snmpwalk -v 2c -c public 172.16.2.219 1.3.6.1.4.1.2.3.51.3.1.4.2.1.3
1,安装mib2c
yum install net-snmp-perl

  1. 2,安装net-snmp-devel-5.7.2-28.el7.x86_64
  2. net-snmp-config 查询配置路径
  3. net-snmp-config --snmpconfpath
  4. [root@zabbix snmp]# net-snmp-config --snmpconfpath
  5. /etc/snmp:/usr/share/snmp:/usr/lib64/snmp:/root/.snmp:/var/lib/net-snmp
  6. 拷贝
  7. SW-MIB.txt 到/usr/share/snmp/mibs 下面
  8. SW-MIB DEFINITIONS ::= BEGIN #注意文件名字必须是SW-MIB
  9. IMPORTS
  10. DisplayString, TEXTUAL-CONVENTION, TruthValue
  11. FROM SNMPv2-TC
  12. Counter32, Integer32, IpAddress,
  13. OBJECT-TYPE, OBJECT-IDENTITY,
  14. MODULE-IDENTITY, NOTIFICATION-TYPE
  15. FROM SNMPv2-SMI
  16. FcWwn, SwDomainIndex, SwNbIndex, SwSensorIndex,
  17. SwPortIndex, SwTrunkMaster
  18. FROM Brocade-TC #依赖
  19. fcSwitch, bcsiModules
  20. FROM Brocade-REG-MIB #依赖
  21. connUnitPortStatEntry, connUnitPortEntry
  22. FROM FCMGMT-MIB;
  23. swMibModule MODULE-IDENTITY #swMibModule 注意导入的模块 env MIBS="+/usr/share/snmp/mibs/SW-MIB.txt" mib2c swMibModule 选择2 net-snmp
  24. LAST-UPDATED "201409051112Z" -- Sep 5, 2014 11:12am
  25. ORGANIZATION "Brocade Communications Systems, Inc.,"
  26. CONTACT-INFO "Customer Support Group
  27. Brocade Communications Systems,
  28. 1745 Technology Drive,
  29. San Jose, CA 95110 U.S.A
  30. Tel: +1-408-392-6061
  31. Fax: +1-408-392-6656
  32. Email: support@Brocade.COM
  33. WEB: www.brocade.com"
  34. Test-MIB.txt拷贝到xxx/share/snmp/mibs/下面。使用snmptranslate -Ts -m ALL | grep Test,其实可以看到有我们的MIBsnmptranslate -Tp -IR Test-MIB::Test 查看我们的MIB和节点内容,也会提示一些语法错误。(-IR用-OS不知为什么错误)
  35. 也可以使用net-snmp-config --snmpconfpath命令得到:
  36. /usr/local/etc/snmp:/usr/local/share/snmp:/usr/local/lib/snmp:/home/actiontec/.snmp:/var/net-snmp
  37. env MIBS="+/usr/share/snmp/mibs/SW-MIB.txt" mib2c swMibModule
  38. env MIBS="+/usr/share/snmp/mibs/WINDOWS-NT-PERFORMANCE-EXCHANGE.mib" mib2c WINDOWS-NT-PERFORMANCE-EXCHANGE
  39. 检测配置
  40. snmpwalk -v 2c -c public 172.16.2.92 SW-MIB::swFCPortIndex
  41. 1,3,6,1,4,1,311,1,1,3,1,1,1,14
  42. discovery[{#SNMPVALUE},SW-MIB::swFCPortIndex]
  43. discovery[{#SNMPVALUE},IF-MIB::ifDescr]
  44. IF-MIB::ifDescr
  45. net-snmp-utils page
  46. [root@zabbix mibs]# snmptranslate -Tz -m ALL|head -5
  47. "org" "1.3"
  48. "dod" "1.3.6"
  49. "internet" "1.3.6.1"
  50. "directory" "1.3.6.1.1"
  51. "mgmt" "1.3.6.1.2"
  52. [root@zabbix mibs]#
  53. 直接编译模块 disk mib module
  54. ./configure --prefix=/usr/local/snmp --with-mib-modules=mSExchangeMTA
  55. cat share/snmp/mibs/WINDOWS-NT-PERFORMANCE-EXCHANGE.txt |grep -A 3 disk
  56. ./bin/snmptranslate -Tz -m ALL|grep -i mtaDiskFileReadsPerSec
  57. ./bin/snmpwalk -v 2c -c public 172.16.7.150 1.3.6.1.4.1.311.1.1.3.1.1.1.14
  58. ./bin/snmpwalk -v 2c -c public 172.16.7.150 .|grep mtaDiskFileReadsPerSec
  59. ./bin/snmpwalk -v 2c -c public 172.16.7.150 .|grep -i disk
  60. ./bin/snmptranslate -Tz -m ALL|grep -i mtaDiskFileReadsPerSec

15,配置参数维护

16, 修改监控项的
历史时间和趋势时间

16,注意事项
主机状态可用。必须获取到数据
zabbix server web端配置的主机地址必须和zabbix agentd配置的主机hostname一致

文档更新时间: 2019-01-02 10:15   作者:张尚