13.日志管理及nginx入门

1、搭建时间服务器,日志服务器并简述sudo安全切换

  • 时间服务器

  • 时间服务器简介:通过NTP协议、chrony软件,多主机协作工作时,各个主机的时间同步很重要,时间不一致会造成 很多重要应用的故障,如:加密协议,日志,集群等, 利用NTP(Network Time Protocol) 协议使网络中的各个计算机时间达到同步。目前NTP协议属于 运维基础架构中必备的基本服务之一
    chrony软件:
    配置文件:
    /etc/chrony.conf
    监听端口:
    323/udp,123/udp
    主要进程:
    chronyd:后台运行的守护进程,用于调整内核中运行的系统时钟和时钟服务 器同步。它确定计算机增减时间的比率,并对此进行补偿
    chronyc:命令行用户工具,用于监控性能并进行多样化的配置。它可以在 chronyd实例控制的计算机上工作,也可在一台不同的远程计算机上工作

  • 搭建时间服务器,使用两台机,一台做服务器server(192.168.164.148),一台做客户端client(192.168.164.138)

1.server机安装chrony软件
[root@www centos]# yum install chrony -y 
[root@www centos]# vi /etc/chrony.conf 		//编辑配置文件,修改如下
# Allow NTP client access from local network.	//允许192.168.0.0/16网段的NTP client将本机作为时间服务器
allow 192.168.0.0/16

2.client主机安装chrony软件,编辑配置文件
[root@localhost centos]#yum install chrony -y
[root@localhost centos]#vi /etc/chrony.conf		//修改如下,添加192.168.164.148作时间服务器
# Use public servers from the pool.ntp.org project.
# Please consider joining the pool (http://www.pool.ntp.org/join.html).
#server 0.centos.pool.ntp.org iburst
#server 1.centos.pool.ntp.org iburst
#server 2.centos.pool.ntp.org iburst
#server 3.centos.pool.ntp.org iburst
server 192.168.164.148 iburst

修改完后重启服务查看
[root@localhost centos]#chronyc
chrony version 3.4
Copyright (C) 1997-2003, 2007, 2009-2018 Richard P. Curnow and others
chrony comes with ABSOLUTELY NO WARRANTY.  This is free software, and
you are welcome to redistribute it under certain conditions.  See the
GNU General Public License version 2 for details.

chronyc> sources
210 Number of sources = 1
MS Name/IP address         Stratum Poll Reach LastRx Last sample               
===============================================================================
^* 192.168.164.148               3   6    17     2    -23us[ -201us] +/-   11ms

或者修改/etc/ntp.conf文件也行
[root@localhost centos]#vi /etc/ntp.conf   
# Use public servers from the pool.ntp.org project.
# Please consider joining the pool (http://www.pool.ntp.org/join.html).
#server 0.centos.pool.ntp.org iburst
#server 1.centos.pool.ntp.org iburst
#server 2.centos.pool.ntp.org iburst
#server 3.centos.pool.ntp.org iburst
server 192.168.164.148 iburst		//自定义server主机

最后在服务器端可查看连接的主机
[root@www centos]# chronyc
chrony version 3.4
Copyright (C) 1997-2003, 2007, 2009-2018 Richard P. Curnow and others
chrony comes with ABSOLUTELY NO WARRANTY.  This is free software, and
you are welcome to redistribute it under certain conditions.  See the
GNU General Public License version 2 for details.

chronyc> clients
Hostname                      NTP   Drop Int IntL Last     Cmd   Drop Int  Last
===============================================================================
192.168.164.138                61      0   4   -    28       0      0   -     -
  • 日志服务器
    我们本机的日志通常是保存在/var/log目录下,同时我们也可以将自己本机的日志放在其他主机中保存,可以是其他主机或mysql中记录
    1.记录于其他主机,本机(192.164.164.138),日志服务器(192.168.164.148)
1.日志服务器安装rsyslog
[root@www centos]# yum install rsyslog -y

2.server编辑配置文件
[root@www centos]# vi /etc/rsyslog.conf 
#### MODULES ####  		//开启tcp/udp端口
# Provides UDP syslog reception 
$ModLoad imudp  
$UDPServerRun 514 
# Provides TCP syslog reception  
$ModLoad imtcp  
$InputTCPServerRun 514 

3.client安装rsyslog
[root@localhost centos]#yum install rsyslog -y

4.client编辑配置文件
[root@localhost centos]#vi /etc/rsyslog.conf 	//修改如下,将日志发送给server
#*.info;mail.none;authpriv.none;cron.none                /var/log/messages
*.info;mail.none;authpriv.none;cron.none                @192.168.164.148

5.测试确认
client启动一个进程
[root@localhost centos]#systemctl restart httpd.service
在server日志上查看
[root@www centos]# tail /var/log/messages
May 17 05:48:56 localhost systemd: Starting The Apache HTTP Server...
May 17 05:48:56 localhost httpd: AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using localhost.localdomain. Set the 'ServerName' directive globally to suppress this message

2.通过mysql数据库记录日志信息,首先要安装rsyslog-mysql软件,这里已经装好
client与server主机地址和上面的一样,我们来配置一下

1.编辑server机上的rsyslog配置文件,首先要确保server上有mariadb数据库
[root@www centos]# vi /etc/my.cnf.d/server.cnf 	//修改下数据库配置
[mysqld]
skip_name_resolve=ON
innodb_file_per_table=ON
[root@www centos]# mysql < /usr/share/doc/rsyslog-8.24.0/mysql-createDB.sql 	//导入rsyslog

2.在mariadb数据库中创建授权用户
MariaDB [Syslog]> GRANT ALL ON Syslog.* TO 'user'@'192.168.164.%' IDENTIFIED BY 'qazxc';              
Query OK, 0 rows affected (0.00 sec)
MariaDB [Syslog]> flush privileges;
Query OK, 0 rows affected (0.00 sec)

3.修改rsyslog配置文件,完成后重启服务
[root@www centos]# vi /etc/rsyslog.conf 
### MODULES ####
$ModLoad  ommysql	//调用该模块
### MODULES ####		//将日志的保存发送给本机的数据库中
#*.info;mail.none;authpriv.none;cron.none                /var/log/messages
*.info;mail.none;authpriv.none;cron.none                :ommysql:192.168.164.148,Syslog,user,qazxc		//依次是模块名、server-ip、数据库名,用户名,密码

4.测试,在client操作,在服务器中查看日志
client安装vsftpd
[root@admin2 centos]#yum install vsftpd -y
server的mysql上查看日志
MariaDB [Syslog]> select * from SystemEvents\G;
*************************** 20. row ***************************
                ID: 20
        CustomerID: NULL
        ReceivedAt: 2020-05-17 22:06:16
DeviceReportedTime: 2020-05-17 10:06:16
          Facility: 1
          Priority: 6
          FromHost: admin2
           Message:  Installed: vsftpd-3.0.2-27.el7.x86_64

5.为了更好管理日志,我们还可以运用LAMP架构在web上管理日志,安装LogAnalyzer 软件
[root@www /]# tar xf loganalyzer-3.6.5.tar.gz 	//解压该包
[root@www /]# cd loganalyzer-3.6.5/
[root@www loganalyzer-3.6.5]# cp -r src /var/www/html/log	//将目录src移动到web站点目录下
[root@www log]# touch config.php 
[root@www log]# chmod 666 config.php
[root@www log]# systemctl restart httpd.service
到此完成,在web端访问,填入server机信息完成绑定即可,结果如下:

13.日志管理及nginx入门_第1张图片

  • sudo用法详解
    sudo能够让获得授权的用户以另外一个用户的身份运行指定的命令;
    授权配置文件 :/etc/sudoers ,以下所有用空格隔开
    root ALL=(ALL) ALL
    %wheel ALL=(ALL) ALL
    分别指users hosts=(runas) commands
    users可以是:username、#uid、%groupname、%#gid、user_alias,同时支持将多个用户定义为一组用户,称之为用户别名,即user_alias;指用户名
    hosts:ip、hostname、NetAddr、host_alias 指主机地址
    runas:runas_alias,指以什么身份运行,比如root
    commands:command、directory、sudoedit:特殊权限,可用于向其它用户授予sudo权限;cmnd_alias 指要运行的命令

  • 定义别名的方法:
    ALIAS_TYPE NAME=item1, item2, item3, …
    NAME:别名名称,必须使用全大写字符;
    ALIAS_TYPE:User_Alias、Host_Alias、Runas_Alias、Cmnd_Alias

  • 示例:
    //命令别名:
    Cmnd_Alias USERADMINCMNDS = /usr/sbin/useradd, /usr/sbin/usermod, /usr/bin/passwd [a-z]*, !/usr/bin/passwd root
    //用户别名:
    User_Alias USERADMIN = bob, alice
    //定义语句:
    USERADMIN ALL=(root) USERADMINCMNDS

2、详解nginx模块使用方法

  • nginx是一个功能强大的、高度模块化的工具,可作为web服务器,实现反向代理等等

  • nginx的程序架构: master/worker结构
    1.一个master进程: 负载加载和分析配置文件、管理worker进程、平滑升级
    2.一个或多个worker进程 处理并响应用户请求
    3.缓存相关的进程: cache loader 载入缓存对象
    cache manager:管理缓存对象

  • 模块分类:
    1.核心模块:core module
    2.标准模块:
    2.1 HTTP 模块: ngx_http_* HTTP Core modules 默认功能 HTTP Optional modules 需编译时指定
    2.2 Mail 模块 ngx_mail_* •
    2.3 Stream 模块 ngx_stream_*
    3.第三方模块

  • 配置文件:主配置文件:nginx.conf 子配置文件 include conf.d/*.conf ,注意配置指令必须以分号结尾

  • 配置文件结构:以主配置段加上多个标准模块配置段,即要实现什么功能就添加多赢的配置段即可,如web的http配置段

main block:主配置段,也即全局配置段;
					event {
						...
					}:事件驱动相关的配置;
				http {
					...
				}:http/https 协议相关的配置段;
				http协议相关的配置结构
				http {
					...
					...:各server的公共配置
					server {
						...
					}:每个server用于定义一个虚拟主机;
					server {
						...
						listen 
						server_name
						root
						alias
						location [OPERATOR] URL {
							...
							if CONDITION {
								...
							}
						}
  • 模块使用

  • httpd模块相关

  • 1.server { … }

配置一个虚拟主机;			
						server {
							listen address[:PORT]|PORT;
							server_name SERVER_NAME;
							root /PATH/TO/DOCUMENT_ROOT;							
						}
1.listen PORT|address[:port]|unix:/PATH/TO/SOCKET_FILE
isten address[:port] [default_server] [ssl] [http2 | spdy]  [backlog=number] [rcvbuf=size] [sndbuf=size]
default_server:设定为默认虚拟主机;
ssl:限制仅能够通过ssl连接提供服务;
backlog=number:后援队列长度;
rcvbuf=size:接收缓冲区大小;
sndbuf=size:发送缓冲区大小;

2.server_name name:指明服务器名称,支持正则表达式

3.tcp_nodelay on | off;在keepalived模式下的连接是否启用TCP_NODELAY选项;

4.tcp_nopush on|off;在sendfile模式下,是否启用TCP_CORK选项;

5、sendfile on | off;是否启用sendfile功能;

6.root path; 设置web资源路径映射;用于指明用户请求的url所对应的本地文件系统上的文档所在目录路径;

7.location [ = | ~ | ~* | ^~ ] url { ... }
location字段:在一个server中可包含多个location字段,用于实现从uri到文件系统的路径映射;ngnix会根据用户请求的URI来检查定义的所有location,并找出一个最佳匹配,而后应用其配置;
=:对URI做精确匹配;
~:对URI做正则表达式模式匹配,区分字符大小写;
~*:对URI做正则表达式模式匹配,不区分字符大小写;
^~:对URI的左半部分做匹配检查,不区分字符大小写;
不带符号:匹配起始于此uri的所有的url;
匹配优先级:=, ^~, ~/~*,不带符号;

8.error_page code ... [=[response]] url;自定义错误响应报文
  • 1.2ngx_http_access_module模块:
    实现基于ip的访问控制功能
allow address | CIDR | unix: | all;
					deny address | CIDR | unix: | all;
  • 1.3ngx_http_auth_basic_module模块
    实现基于用户的访问控制,使用basic机制进行用户认证
auth_basic string | off;
auth_basic_user_file file;
location /admin/ {
						alias /webapps/app1/data/;
						auth_basic "Admin Area";
						auth_basic_user_file /etc/nginx/.ngxpasswd;
					}
注意:htpasswd命令由httpd-tools所提供;
  • 1.4ngx_http_stub_status_module模块
    用于输出nginx的基本状态信息
Active connections: 291 
server accepts handled requests
16630948 16630948 31070465 
Reading: 6 Writing: 179 Waiting: 106
 	
各字段含义如下:					
Active connections: 活动状态的连接数;
accepts:已经接受的客户端请求的总数;
handled:已经处理完成的客户端请求的总数;
requests:客户端发来的总的请求数;
Reading:处于读取客户端请求报文首部的连接的连接数;
Writing:处于向客户端发送响应报文过程中的连接数;
Waiting:处于等待客户端发出请求的空闲连接数;
  • 1.5ngx_http_log_module模块
log_format name string ...;
string可以使用nginx核心模块及其它模块内嵌的变量;

access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];
access_log off;

访问日志文件路径,格式及相关的缓冲的配置;buffer=sizeflush=time 

open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time];
open_log_file_cache off;缓存各日志文件相关的元数据信息;
max:缓存的最大文件描述符数量;
min_uses:在inactive指定的时长内访问大于等于此值方可被当作活动项;
inactive:非活动时长;
valid:验正缓存中各缓存项是否为活动项的时间间隔;
1.6ngx_http_ssl_module模块:
```bash
ssl on | off;打开或关闭	

ssl_certificate file;当前虚拟主机使用PEM格式的证书文件;
						
ssl_certificate_key file;当前虚拟主机上与其证书匹配的私钥文件;
						
ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2];支持ssl协议版本,默认为后三个;
						
ssl_session_cache off | none | [builtin[:size]] [shared:name:size];
builtin[:size]:使用OpenSSL内建的缓存,此缓存为每worker进程私有;
[shared:name:size]:在各worker之间使用一个共享的缓存;
						
ssl_session_timeout time;客户端一侧的连接可以复用ssl session cache中缓存 的ssl参数的有效时长;
						
配置示例:
		server {
				listen 443 ssl;
				server_name www.aaa.com;
				root /var/www/html;
				ssl on;
				ssl_certificate /etc/nginx/ssl/nginx.crt;
				ssl_certificate_key /etc/nginx/ssl/nginx.key;
				ssl_session_cache shared:sslcache:20m;
				}						
  • 1.6ngx_http_rewrite_module模块
    将用户请求的URI基于regex所描述的模式进行检查,而后完成替换
rewrite regex replacement [flag]:将用户请求的URI基于regex所描述的模式进行检查,匹配到时将其替换为replacement指定的新的URI;
[flag]:
last:重写完成后停止对当前URI在当前location中后续的其它重写操作,而后对新的URI启动新一轮重写检查;提前重启新一轮循环; 
break:重写完成后停止对当前URI在当前location中后续的其它重写操作,而后直接跳转至重写规则配置块之后的其它配置;结束循环;
redirect:重写完成后以临时重定向方式直接返回重写后生成的新URI给客户端,由客户端重新发起请求;不能以http://或https://开头;
permanent:重写完成后以永久重定向方式直接返回重写后生成的新URI给客户端,由客户端重新发起请求;

if (condition) { ... }引入一个新的配置上下文 ;条件满足时,执行配置块中的配置指令;server, location;

set $variable value;用户自定义变量
  • 1.7ngx_http_referer_module模块:调转模块
valid_referers none | blocked | server_names | string ...;
定义referer首部的合法可用值;
none:请求报文首部没有referer首部;
blocked:请求报文的referer首部没有值;
server_names:参数,其可以有值作为主机名或主机名模式;
arbitrary_string:直接字符串,但可使用*作通配符;
regular expression:被指定的正则表达式模式匹配到的字符串;要使用~打头,例如 ~.*\.magedu\.com;
						
配置示例:
valid_referers none block server_names *.magedu.com *.mageedu.com magedu.* mageedu.* ~\.magedu\.;
if($invalid_referer) {
						return http://www.magedu.com/invalid.jpg;
					}
即如果请求的url符合if中的判断成立,就将这些请求响应到return里的url上去

你可能感兴趣的:(13.日志管理及nginx入门)