#
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
初始化
../bin/mysqld --defaults-file=/etc/my.cnf --initialize-insecure --user=mysql --datadir=/database/
chmod -R 755 /database/
export PATH=/usr/local/mysql-5.7.21/bin:$PATH
启动服务
/usr/local/mysql-5.7.21/support-files
./mysql.server start
2,安装httpd
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
./configure --prefix=/usr/local/apr
make &&make install
./configure --prefix=/usr/local/apr-util --with-apr=/usr/local/apr/
make &&make install
# groupadd -r apache
# useradd -r -g apache apache
./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
make &&make install
yum install bzip2
yum install libxslt-devel
安装php
./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必须加上
# tar xf xcache-3.0.3.tar.gz
# cd xcache-3.0.3
# /usr/local/php/bin/phpize xcache借助/usr/local/php/bin/phpize模块生成的
# ./configure --enable-xcache --with-php-config=/usr/local/php/bin/php-config
# make && make install
# 编程成php的扩展
# /usr/local/php/bin/phpize --with-php-config=/usr/local/php/bin/php-config
# 安装结束时,会出现类似如下行:
# Installing shared extensions: /usr/local/php/lib/php/extensions/no-debug-zts-20100525/
# 编辑php.ini,整合php和xcache:
# 首先将xcache提供的样例配置导入php.ini
# mkdir /etc/php.d
# cp xcache.ini /etc/php.d
# 说明:xcache.ini文件在xcache的源码目录中。
# 接下来编辑/etc/php.d/xcache.ini,找到zend_extension开头的行,修改为如下行:
# zend_extension = /usr/local/php/lib/php/extensions/no-debug-zts-20100525/xcache.so
cp php.ini-production /etc/php.ini
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
post_max_size = 16M
enable_post_data_reading = On
max_execution_time = 300
max_input_time = 300
date.timezone = "Asia/Shanghai"
设置httpd.conf虚拟主机配置
LoadModule mpm_event_module modules/mod_mpm_event.so
<IfModule mpm_event_module>
StartServers 10
MinSpareThreads 75
MaxSpareThreads 250
ThreadsPerChild 25
MaxRequestWorkers 400
MaxConnectionsPerChild 0
</IfModule>
<IfModule mime_module>
AddType application/x-compress .Z
AddType application/x-gzip .gz .tgz
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
</IfModule>
<FilesMatch \.php$>
SetHandler application/x-httpd-php
</FilesMatch>
AddType text/html .php
不能创建session先注释
#php_value session.save_handler "files"
#php_value session.save_path "/var/lib/php/session"
<VirtualHost *:80>
ServerName 0.0.0.0
DocumentRoot "/usr/share/zabbix"
DirectoryIndex index.html index.php
Alias /zabbix /usr/share/zabbix
<Directory "/usr/share/zabbix">
Options FollowSymLinks
AllowOverride None
Require all granted
<IfModule mod_php5.c>
php_value max_execution_time 300
php_value memory_limit 128M
php_value post_max_size 16M
php_value upload_max_filesize 2M
php_value max_input_time 300
php_value always_populate_raw_post_data -1
# php_value date.timezone Asia/Shanghai
</IfModule>
<IfModule mod_deflate.c>
# 设置压缩类型
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE text/javascript
AddOutputFilterByType DEFLATE image/svg+xml
AddOutputFilterByType DEFLATE image/x-icon
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE text/php
AddOutputFilterByType DEFLATE image/gif image/png image/jpe image/swf image/jpeg image/bmp
</IfModule>
<IfModule mod_headers.c>
# 自定义Header
</IfModule>
</Directory>
</VirtualHost>
设置时区php.ini
date.timezone = "Asia/Shanghai"
修改zabbix web
#include/classes/setup/CFrontendSetup.php
#public function checkPhpAlwaysPopulateRawPostData() {
# $current = ini_get('always_populate_raw_post_data');
# $current=-1;
#
# return [
# 'name' => _s('PHP option "%1$s"', 'always_populate_raw_post_data'),
# 'current' => ($current != -1) ? _('on') : _('off'),
# 'required' => _('off'),
# 'result' => ($current != -1) ? self::CHECK_FATAL : self::CHECK_OK,
# 'error' => _s('PHP option "%1$s" must be set to "%2$s"', 'always_populate_raw_post_data', -1)
# ];
#}
中文支持
[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配置
[root@zabbix ~]# grep -Ev '^#|^$' /etc/zabbix/zabbix_agentd.conf
PidFile=/var/run/zabbix/zabbix_agentd.pid
LogFile=/var/log/zabbix/zabbix_agentd.log
LogFileSize=0
DebugLevel=3
Server=172.16.7.146
ServerActive=172.16.7.146
Hostname=172.16.7.146
Timeout=3
Include=/usr/local/zabbix-3.4.8/etc/zabbix_agentd.conf.d/*.conf
#UserParameter=test.tail,/usr/bin/tail -l /usr/lib/zabbix/alertscripts/zabbix_moniter.test
#UserParameter=snmp.ip.discover_snmp,/etc/zabbix/shell/snmp_check.py
#UserParameter=snmp.inter.check[*],/etc/zabbix/shell/inter_check.py $1
#UserParameter=snmp.ip.discover_snmpV2,/etc/zabbix/shell/snmp_check2.py
#UserParameter=snmp.inter.checkV2[*],/etc/zabbix/shell/inter_check.py $1
#UserParameter=win_cpu.load[*],/etc/zabbix/shell/win_cpu.py $1
#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
#########删除201708110000之前的所有数据。每天一个分区
call partition_drop('zabbix','history','201708110000');
call partition_drop('zabbix','history_log','201708110000');
call partition_drop('zabbix','history_str','201708110000');
call partition_drop('zabbix','history_text','201708110000');
call partition_drop('zabbix','history_uint','201708110000');
call partition_drop('zabbix','trends','201708110000');
call partition_drop('zabbix','trends_uint','201708110000');
##########
CALL partition_maintenance('zabbix', 'history', 365, 24, 90);
CALL partition_maintenance('zabbix', 'history_log', 365, 24, 90);
CALL partition_maintenance('zabbix', 'history_str', 365, 24, 90);
CALL partition_maintenance('zabbix', 'history_text', 365, 24, 90);
CALL partition_maintenance('zabbix', 'history_uint', 365, 24, 90);
CALL partition_maintenance('zabbix', 'trends', 365, 24, 90);
CALL partition_maintenance('zabbix', 'trends_uint', 365, 24, 90);
保留天数 265天 (注意5天前将被删除)
创建时间间隔 24小时
创建分区数 90 (分区不会自动创建,所以可以创建多点)
定时任务:
*/1 * * * * ntpdate time.windows.com
*/3 * * * * /usr/local/python-3.5.0/bin/python3.5 /etc/zabbix/shell/zabbix_api.py
00 08 * * * /usr/local/python-3.5.0/bin/python3.5 /etc/zabbix/shell/Partition_Clear.py
00 10 * * * /usr/local/python-3.5.0/bin/python3.5 /etc/zabbix/shell/Partition_Create.py
##################################################################
定时自动创建创建分区
##################################################################
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import pymysql,datetime
class db_action(object):
def __init__(self,host,port,user,password,database="mysql",charset="utf8"):
self.host=host
self.port=port
self.user=user
self.password=password
self.database=database
self.charset=charset
self.__cursor=self.__conn().cursor()
def __conn(self):
return pymysql.Connect(host=self.host,port=self.port,user=self.user,\
password=self.password,database=self.database,\
charset=self.charset)
def callproc(self,pl,t):
'''存储过程'''
ret=self.__cursor.callproc(pl,args=t)
return ret
def execute(self, tables_name):
'''sql'''
ret = self.__cursor.execute('select count(*) from PARTITIONS WHERE TABLE_NAME=%s and TABLE_ROWS=0',\
[tables_name])
return self.__cursor.fetchone()[0]
if __name__ == '__main__':
par_count=db_action(host='172.16.6.38',port=3306,user='root',password="zabbix",database="information_schema",charset='utf8')
par_create=db_action(host='172.16.6.38',port=3306,user='root',password="zabbix",database="zabbix",charset='utf8')
history_count=par_count.execute('history')
trends_count=par_count.execute('trends_uint')
with open('/root/pariton_create.log', encoding='utf-8', mode='a+') as f:
f.write('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@'+'\n')
with open('/root/pariton_create.log', encoding='utf-8', mode='a+') as f:
f.write('history分区统计' + str(history_count)+'\n')
with open('/root/pariton_create.log', encoding='utf-8', mode='a+') as f:
f.write('trends_uint分区统计' + str(trends_count) + '\n')
rets = []
if history_count<=7:
ret1=par_create.callproc('partition_maintenance',('zabbix','history',7, 24, 30,))
ret2=par_create.callproc('partition_maintenance',('zabbix','history_log',7, 24, 30,))
ret3=par_create.callproc('partition_maintenance',('zabbix','history_str',7, 24, 30,))
ret4=par_create.callproc('partition_maintenance',('zabbix','history_text',7, 24, 30,))
ret5=par_create.callproc('partition_maintenance',('zabbix','history_uint',7, 24, 30,))
rets.append(ret1)
rets.append(ret2)
rets.append(ret3)
rets.append(ret4)
rets.append(ret5)
if trends_count <= 7:
ret6=par_create.callproc('partition_maintenance', ('zabbix', 'trends',30, 24, 30,))
ret7=par_create.callproc('partition_maintenance', ('zabbix', 'trends_uint',30, 24, 30,))
rets.append(ret6)
rets.append(ret7)
if rets:
with open('/root/pariton_create.log',encoding='utf-8',mode='a+') as f:
f.write(rets+'\n')
############################################################
定时自动删除数据被清空分区。
############################################################
[root@zabbix shell]# cat Partition_Clear.py
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import pymysql,datetime
class db_action(object):
def __init__(self,host,port,user,password,database="mysql",charset="utf8"):
self.host=host
self.port=port
self.user=user
self.password=password
self.database=database
self.charset=charset
self.__cursor=self.__conn().cursor()
def __conn(self):
return pymysql.Connect(host=self.host,port=self.port,user=self.user,\
password=self.password,database=self.database,\
charset=self.charset)
def callproc(self,pl,t):
ret=self.__cursor.callproc(pl,args=t)
return ret
if __name__ == '__main__':
db=db_action(host='172.16.6.38',port=3306,user='root',password="zabbix",database="zabbix",charset='utf8')
rets=[]
ret=db.callproc('partition_drop',('zabbix','history',(datetime.datetime.now()+datetime.timedelta(days=-1)).strftime('%Y%m%d0000'),))
rets.append(ret)
ret=db.callproc('partition_drop',('zabbix','history_log',(datetime.datetime.now()+datetime.timedelta(days=-1)).strftime('%Y%m%d0000'),))
rets.append(ret)
ret=db.callproc('partition_drop',('zabbix','history_str',(datetime.datetime.now()+datetime.timedelta(days=-1)).strftime('%Y%m%d0000'),))
rets.append(ret)
ret=db.callproc('partition_drop',('zabbix','history_text',(datetime.datetime.now()+datetime.timedelta(days=-1)).strftime('%Y%m%d0000'),))
rets.append(ret)
ret=db.callproc('partition_drop',('zabbix','history_uint',(datetime.datetime.now()+datetime.timedelta(days=-1)).strftime('%Y%m%d0000'),))
rets.append(ret)
with open('/root/pariton_clear.log',encoding='utf-8',mode='a+') as f:
f.write(str(rets)+'\n')
#############################################################################
删除zabbix server上snmp检测
主机如果配置了snmp监控即可获取到snmp主机ip,如果取消就获取不到,及删除对应的检测。
#############################################################################
#!/usr/local/python
#-*- coding:utf-8 -*-
import json
import urllib.request
import urllib.error
import urllib.parse
import pymysql
import re,logging,os
class zabbix:
def __init__(self,ip='172.16.7.145',zabser_name='Admin',zabser_pwd='zabbix'):
self.ip=ip
self.url='http://%s/zabbix/api_jsonrpc.php' %self.ip
self.zabser_name=zabser_name
self.zabser_pwd=zabser_pwd
self.header = {"Content-Type": "application/json"}
def get_func(self,post_body):
# Auth Successful. The Auth ID Is:",response['result']
data = bytes(post_body,'utf-8') #urllib.parse.urlencode()转json的有问题,所以直接bytes
request = urllib.request.Request(self.url,data)
for key in self.header:
request.add_header(key,self.header[key])
try:
result = urllib.request.urlopen(request)
res = result.read().decode('utf-8')
except urllib.error.URLError as e:
print ("Auth Failed, Please Check Your Name AndPassword:",e.code)
else:
response = json.loads(res)
result.close()
return response
def get_authid(self):
'''获取认证信息'''
authid_body=self.auth_body = json.dumps(
{
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": self.zabser_name,
"password": self.zabser_pwd
},
"id": 0
}, ensure_ascii=False
)
response=self.get_func(authid_body)
id=response['id']
authid=response['result']
return id,authid
def get_hostids(self,hostname='172.16.6.38'):
'''获取hostids'''
hostids_body = json.dumps({
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": "extend",
"filter": {
"host": [
hostname
]
}
},
"auth": self.get_authid()[1],
"id": self.get_authid()[0]
})
response=self.get_func(hostids_body)
hostids=response['result'][0]['hostid']
return hostids
def get_itemsid(self):
'''通过hostid获取itemsid'''
itemsid_list=[]
for line in self.handler_key():
items_body = json.dumps({
"jsonrpc": "2.0",
"method": "item.get",
"params": {
"output": "extend",
"hostids": self.get_hostids(),
"search": {
"key_": line
},
"sortfield": "name"
},
"auth": self.get_authid()[1],
"id": self.get_authid()[0]
})
response = self.get_func(items_body)
itemsid_list.append(response['result'][0]['itemid'])
return itemsid_list
def handler_itemsid(self):
'''从数据库中获取items key列表 获取shmp的ip列表'''
items_body = json.dumps({
"jsonrpc": "2.0",
"method": "item.get",
"params": {
"output": "extend",
"hostids": self.get_hostids(),
"sortfield": "name"
},
"auth": self.get_authid()[1],
"id": self.get_authid()[0]
})
response = self.get_func(items_body)
key_list=[line['key_'] for line in response['result']]
ip_list=[]
for line in key_list:
try:
ip=re.search(r'\[((\d+.){3}\d+)\]',line)
ip_list.append(ip.groups()[0])
except AttributeError:
continue
return ip_list,key_list
def del_itemsid(self):
'''删除不存在的items'''
items_body=json.dumps({
"jsonrpc": "2.0",
"method": "item.delete",
"params":self.get_itemsid(),
"auth": self.get_authid()[1],
"id": self.get_authid()[0]
})
response = self.get_func(items_body)
self.save_log(response)
return response
def handler_key(self):
'''获取需要删除的key 列表'''
conn = pymysql.connect(host=self.ip, port=3306, user='root', passwd='zabbix', db='zabbix')
cur = conn.cursor()
cur.execute("select ip from zabbix.interface where port=161;")
res = cur.fetchall()
conn.close()
list_ip=[line[0] for line in res]
ip_list, key_list=self.handler_itemsid()
tmpip_list=[]
for line in ip_list:
if line not in list_ip:
tmpip_list.append(line)
######输出key
tmpkey_list=[]
for i in tmpip_list:
for j in key_list:
if re.findall(i,j):tmpkey_list.append(j)
return tmpkey_list
@staticmethod
def save_log(msg):
'''日志处理'''
logger=logging.getLogger(os.path.basename(__file__))
console_handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S', style='%')
console_handler.setFormatter(formatter)
console_handler.setLevel(10)
file_handler = logging.FileHandler('zkapi.log')
file_handler.setFormatter(formatter)
file_handler.setLevel(10)
logger.addHandler(console_handler)
logger.addHandler(file_handler)
logger.setLevel(10)
logger.info(msg)
if __name__ == '__main__':
z=zabbix()
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,报警媒介
weixin
zabbix_weixin.py
{ALERT.SUBJECT}
{ALERT.MESSAGE}
SMS
zabbix_sms.py
{ALERT.SENDTO}
{ALERT.MESSAGE}
zabbix_sendmail.py
{ALERT.SENDTO}
{ALERT.SUBJECT}
{ALERT.MESSAGE}
动作:
名称mail Report problems to Zabbix administrators
A 触发器示警度 = 灾难 移除
B 触发器示警度 = 严重 移除
C 触发器示警度 = 一般严重 移除
D 触发器示警度 = 警告 移除
E 触发器示警度 = 信息 移除
F 触发器示警度 = 未分类 移除
操作:
60s
{HOST.NAME} {TRIGGER.STATUS}: {TRIGGER.NAME} {EVENT.TIME}
告警主机: {HOST.NAME}
告警 IP: {HOST.IP}
触发状态: {TRIGGER.STATUS}
告警时间: {EVENT.DATE}-{EVENT.TIME}
告警等级: {TRIGGER.SEVERITY}
告警信息: {TRIGGER.NAME}
问题详情: {ITEM.NAME}:{ITEM.VALUE}
事件 ID: {EVENT.ID}
维护期间暂停操作
发送消息给用户: Admin (Zabbix Administrator) 通过 Email
发送消息给用户群组: Zabbix administrators 通过 Email
恢复动作
{HOST.NAME} {TRIGGER.STATUS}: {TRIGGER.NAME} {EVENT.RECOVERY.TIME}
告警主机: {HOST.NAME}
告警 IP: {HOST.IP}
触发状态: {TRIGGER.STATUS}
告警时间: {EVENT.DATE}-{EVENT.TIME}
告警等级: {TRIGGER.SEVERITY}
告警信息: {TRIGGER.NAME}
问题详情: {ITEM.NAME}:{ITEM.VALUE}
事件 ID: {EVENT.ID}
13,模板维护[自动发现]
AlertScriptsPath=/usr/lib/zabbix/alertscripts 报警script
ExternalScripts=/usr/lib/zabbix/externalscripts 外部检查script
############################################################
邮件
############################################################
#!/usr/bin/python
#coding:utf-8
import smtplib
from email.mime.text import MIMEText
import sys
import time
mail_host = 'mail.xxx.cn'
mail_user = 'tiantao'
mail_pass = 'xxxx'
mail_postfix = 'xxx.cn'
def send_mail(to_list,subject,content):
me = mail_user+"<"+mail_user+"@"+mail_postfix+">"
msg = MIMEText(content,_charset="utf-8")
msg['Subject'] = subject
msg['From'] = me
msg['to'] = to_list
try:
s = smtplib.SMTP()
s.connect(mail_host)
s.login(mail_user,mail_pass)
s.sendmail(me,to_list,msg.as_string())
s.close()
return True
except Exception as e:
print(str(e))
return False
if __name__ == "__main__":
send_mail(sys.argv[1], sys.argv[2], sys.argv[3])
##########################################################
sms
##########################################################
#!/usr/local/python-3.5.0/bin/python3.5
import http.cookiejar
import urllib.request
import socket
import json
import sys
from urllib.parse import quote
class sendMessage():
def __init__(self):
self.cookieJar = http.cookiejar.LWPCookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.cookieJar))
urllib.request.install_opener(opener)
def sendMessage(self,phone,content,url):
socket.setdefaulttimeout(5)
header = {'Content-Type':'application/x-www-form-urlencoded','charset':'utf-8'}
request = urllib.request.Request(url,headers=header)
request = urllib.request.urlopen(request)
pageHtml = request.read().decode('UTF-8')
print(pageHtml)
request.close()
if __name__ == '__main__':
phone = str(sys.argv[1])
content= str(sys.argv[2])
content=quote(content)
url='''http://172.16.5.31:8000/api/sms/?appid=xxx&sign=xxx&style=json&mobile=%s&message=%s''' %(phone,content)
up = sendMessage()
up.sendMessage(phone, content,url)
########################################################
微信
########################################################
[root@zabbix-service alertscripts]# cat zabbix_weixin.py
#!/usr/local/python-3.5.0/bin/python3.5
import http.cookiejar
import urllib.request
import socket
import json
import sys
class sendMessage():
def __init__(self):
self.cookieJar = http.cookiejar.LWPCookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.cookieJar))
urllib.request.install_opener(opener)
def sendMessage(self,subject,content):
socket.setdefaulttimeout(5)
getTokenUrl="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=xxx&corpsecret=xxxx"
request = urllib.request.Request(getTokenUrl)
request = urllib.request.urlopen(request)
pageHtml = request.read().decode('UTF-8')
if pageHtml:
pageHtml=eval(pageHtml)
token=pageHtml['access_token']
request.close()
data = { "touser": "@all","toparty": "@all", "msgtype": "text", "agentid": "1","text": { "content": subject+'\n'+content},"safe":"0"}
url=" https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+token
header = {'Content-Type':'application/x-www-form-urlencoded','charset':'utf-8'}
jdata = json.dumps(data,ensure_ascii=False).encode('UTF-8')
request = urllib.request.Request(url,data=jdata,headers=header)
request = urllib.request.urlopen(request)
pageHtml = request.read().decode('UTF-8')
request.close()
print(pageHtml)
if __name__ == '__main__':
#sendto=str(sys.argv[1])
# subject = '微信测试'
# content = '微信升级测试'
subject = str(sys.argv[1])
content = str(sys.argv[2])
up = sendMessage()
up.sendMessage(subject, content)
14,win cpu load监控
item名称 cpu_load
item类型 使用外部检查
cpuload.py[“{HOST.CONN}”]
[root@zabbix externalscripts]# cat cpuload.py
#!/usr/local/python
#-*- coding:utf-8 -*-
import netsnmp
class SnmpClass(object):
"""
SNMP
"""
def __init__(self, oid="sysDescr", version=1, destHost="localhost", community="public"):
self.oid = oid
self.version = version
self.destHost = destHost
self.community = community
@property
def query(self):
"""
snmpwalk
"""
try:
result = netsnmp.snmpwalk(self.oid,
Version=self.version,
DestHost=self.destHost,
Community=self.community)
except Exception as e:
print(e)
result = None
return result
def main(ip):
cpuload=0
test_obj = SnmpClass(oid="HOST-RESOURCES-MIB::hrProcessorLoad", destHost=ip)
for line in test_obj.query:
cpuload+=int(line)
return cpuload/len(test_obj.query)
if __name__ == '__main__':
import sys
ip=sys.argv[1]
result=main(ip)
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
2,安装net-snmp-devel-5.7.2-28.el7.x86_64
net-snmp-config 查询配置路径
net-snmp-config --snmpconfpath
[root@zabbix snmp]# net-snmp-config --snmpconfpath
/etc/snmp:/usr/share/snmp:/usr/lib64/snmp:/root/.snmp:/var/lib/net-snmp
拷贝
SW-MIB.txt 到/usr/share/snmp/mibs 下面
SW-MIB DEFINITIONS ::= BEGIN #注意文件名字必须是SW-MIB
IMPORTS
DisplayString, TEXTUAL-CONVENTION, TruthValue
FROM SNMPv2-TC
Counter32, Integer32, IpAddress,
OBJECT-TYPE, OBJECT-IDENTITY,
MODULE-IDENTITY, NOTIFICATION-TYPE
FROM SNMPv2-SMI
FcWwn, SwDomainIndex, SwNbIndex, SwSensorIndex,
SwPortIndex, SwTrunkMaster
FROM Brocade-TC #依赖
fcSwitch, bcsiModules
FROM Brocade-REG-MIB #依赖
connUnitPortStatEntry, connUnitPortEntry
FROM FCMGMT-MIB;
swMibModule MODULE-IDENTITY #swMibModule 注意导入的模块 env MIBS="+/usr/share/snmp/mibs/SW-MIB.txt" mib2c swMibModule 选择2 net-snmp
LAST-UPDATED "201409051112Z" -- Sep 5, 2014 11:12am
ORGANIZATION "Brocade Communications Systems, Inc.,"
CONTACT-INFO "Customer Support Group
Brocade Communications Systems,
1745 Technology Drive,
San Jose, CA 95110 U.S.A
Tel: +1-408-392-6061
Fax: +1-408-392-6656
Email: support@Brocade.COM
WEB: www.brocade.com"
将Test-MIB.txt拷贝到xxx/share/snmp/mibs/下面。使用snmptranslate -Ts -m ALL | grep Test,其实可以看到有我们的MIB。snmptranslate -Tp -IR Test-MIB::Test 查看我们的MIB和节点内容,也会提示一些语法错误。(-IR用-OS不知为什么错误)
也可以使用net-snmp-config --snmpconfpath命令得到:
/usr/local/etc/snmp:/usr/local/share/snmp:/usr/local/lib/snmp:/home/actiontec/.snmp:/var/net-snmp
env MIBS="+/usr/share/snmp/mibs/SW-MIB.txt" mib2c swMibModule
env MIBS="+/usr/share/snmp/mibs/WINDOWS-NT-PERFORMANCE-EXCHANGE.mib" mib2c WINDOWS-NT-PERFORMANCE-EXCHANGE
检测配置
snmpwalk -v 2c -c public 172.16.2.92 SW-MIB::swFCPortIndex
1,3,6,1,4,1,311,1,1,3,1,1,1,14
discovery[{#SNMPVALUE},SW-MIB::swFCPortIndex]
discovery[{#SNMPVALUE},IF-MIB::ifDescr]
IF-MIB::ifDescr
net-snmp-utils page
[root@zabbix mibs]# snmptranslate -Tz -m ALL|head -5
"org" "1.3"
"dod" "1.3.6"
"internet" "1.3.6.1"
"directory" "1.3.6.1.1"
"mgmt" "1.3.6.1.2"
[root@zabbix mibs]#
直接编译模块 disk mib module
./configure --prefix=/usr/local/snmp --with-mib-modules=mSExchangeMTA
cat share/snmp/mibs/WINDOWS-NT-PERFORMANCE-EXCHANGE.txt |grep -A 3 disk
./bin/snmptranslate -Tz -m ALL|grep -i mtaDiskFileReadsPerSec
./bin/snmpwalk -v 2c -c public 172.16.7.150 1.3.6.1.4.1.311.1.1.3.1.1.1.14
./bin/snmpwalk -v 2c -c public 172.16.7.150 .|grep mtaDiskFileReadsPerSec
./bin/snmpwalk -v 2c -c public 172.16.7.150 .|grep -i disk
./bin/snmptranslate -Tz -m ALL|grep -i mtaDiskFileReadsPerSec
15,配置参数维护
16, 修改监控项的
历史时间和趋势时间
16,注意事项
主机状态可用。必须获取到数据
zabbix server web端配置的主机地址必须和zabbix agentd配置的主机hostname一致