Author Archives: Node

如何在Centos 7上用Logrotate管理日志文件

何为Logrotate?

Logrotate是一个实用的日志管理工具,旨在简化对系统上生成大量的日志文件进行管理。 Logrotate允许自动旋转压缩,删除和邮寄日志文件,从而节省宝贵的磁盘空间。 Logrotate可以设置为每天、每周、每月或当日志文件达到一定的大小时处理日志文件。还可以完全控制日志的自动化管理方式,而不需要人工干预。Logrotate支持Linux系统上的所有日志文件,包括但不限于ApacheNginxTomcatELKzabbix等应用。

1.安装logrotate

系统默认已经安装,某些Linux发行版可能并未安装,那么请执行以下命令安装:

Centos:

$ yum install logrotate -y

Ubuntu:

$ apt-get install logrotate -y

通过yum默认安装的文件存储位置说明

/etc/cron.daily            # logrotate脚本文件存放位置
/etc/logrotate.conf        # 主配置文件
/usr/sbin/logrotate        # 二进制程序文件
/etc/logrotate.d/          # 特定服务日志存储目录(自己设定的配置文件)
/var/lib/logrotate.status  # 状态文件

2.查看logrotate主文件默认配置情况

$ cat /etc/logrotate.conf

# see "man logrotate" for details
# rotate log files weekly
weekly		            # 每周转存一次

# keep 4 weeks worth of backlogs
rotate 4                    # 保留四个日志备份文件

# create new (empty) log files after rotating old ones
create	                    # rotate后,创建一个新的空文件

# use date as a suffix of the rotated file
dateext                     # 轮转的文件名字带有日期信息

# uncomment this if you want your log files compressed
#compress

# RPM packages drop log rotation information into this directory
include /etc/logrotate.d    # 此目录下的配置文件优先生效

# no packages own wtmp and btmp -- we'll rotate them here
/var/log/wtmp {             # 指定/var/log/wtmp日志文件;
    monthly                 # 每月轮转一次,优先于全局设定的每周轮转一次;
    minsize 1M              # 日志文件大于1M才会去轮转;
    create 0664 root utmp   # 新日志文件的权限,属主,属组;
    rotate 1                # 保留一个日志备份,优先于全局设置的四个;
}
/var/log/btmp {             # 指定/var/log/btmp日志文件;
    missingok               # 如果日志丢失,不报错;
    monthly
    create 0600 root utmp
    rotate 1
}

# system-specific logs may be also be configured here.
# 系统特定的日志也可以在主文件中配置。

3.logrotate日志切割

在定义日志文件时可以使用通配符,但不建议使用,因为它会包括已切换过的日志,如必须使用,请在*号后加上已知的文件扩展名, 例如:*.log

Nginx日志:

/etc/logrotate.d/目录下创建Nginx服务日志配置文件

$ vim /etc/logrotate.d/nginx

/usr/local/nginx/logs/*.log {
create 644 www root
daily
dateext
rotate 3
minsize 10K
copytruncate
nocompress
missingok
notifempty
noolddir
postrotate
/bin/kill -USR1 `cat /usr/local/nginx/logs/nginx.pid`
endscript
}

php日志:

/usr/local/php/var/log/*.log {
missingok
notifempty
sharedscripts
delaycompress
create 0664 www www
postrotate
/bin/kill -SIGUSR1 `cat /usr/local/php/var/run/php-fpm.pid 2>/dev/null` 2>/dev/null || true
endscript
}

注:你也可以手动生成一个20M内容的日志文件进行测试,例如:

$ head -c 20M < /dev/urandom > /var/log/renwole-log

配置完成后,可以通过如下命令来手动执行查看效果:

$ logrotate -f /etc/logrotate.d/nginx

另外还可以使用如下命令查看logrotate运行状态:

$ cat /var/lib/logrotate/logrotate.status

由于Logrotate是基于cron定时运行的,所以logrotate脚本默认在 /etc/cron.daily/ 目录下,文件名是logrotate。你可以设置 /etc/anacrontab 来控制Logrotate何时运行。

4.查看anacrontab默认配置

$ cat /etc/anacrontab

# /etc/anacrontab: configuration file for anacron

# See anacron(8) and anacrontab(5) for details.

SHELL=/bin/sh
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
# the maximal random delay added to the base delay of the jobs
RANDOM_DELAY=45
# the jobs will be started during the following hours only
START_HOURS_RANGE=3-22

#period in days   delay in minutes   job-identifier   command
1       5       cron.daily              nice run-parts /etc/cron.daily
7       25      cron.weekly             nice run-parts /etc/cron.weekly
@monthly 45     cron.monthly            nice run-parts /etc/cron.monthly

5.关于logrotate常用配置参数注解

daily,weekly,monthly  # 转储周期分别是每天/每周/每月;
minsize 15M           # 日志体积大于此值时轮换(例如:100K,4M);
dateext	              # 轮询的文件名字带有日期信息;
missingok             # 如果日志文件丢失,不要显示错误;
rotate 5              # 轮转存储中包含多少备份日志文件,0为无备份,以数字为准;
compress              # 通过gzip压缩转储以后的日志,以*.gz结尾;
nocompress            # 不需要压缩时,用这个参数;
delaycompress         # 延迟压缩,和compress一起使用时压缩所有日志,除当前和下一个最近的;
nodelaycompress       # 覆盖delaycompress选项,转储同时压缩;
copytruncate          # 用于还在打开中的日志文件,把当前日志备份并截断;
nocopytruncate        # 备份日志文件但是不截断;
create 644 www root   # 转储文件,使用指定的文件模式创建新的日志文件;
nocreate              # 不建立新的日志文件;
errors renwole@my.org # 专储时的错误信息发送到指定的Email地址;
ifempty               # 即使是空文件也转储,这个是logrotate的缺省选项;
notifempty            # 如果日志文件为空,则不转储;
mail renwole@my.org   # 把转储的日志文件发送到指定的E-mail地;
nomail                # 转储时不发送日志文件;
olddir /tmp           # 转储后的日志文件放入指定目录,必须和当前日志文件在同一个文件系统;
noolddir              # 转储后的日志文件和当前日志文件放在同一个目录下;
prerotate/endscript   # 在转储以前需要执行的命令可以放入这个对,这两个关键字必须单独成行;
postrotate/endscript  # 在转储以后需要执行的命令可以放入这个对,这两个关键字必须单独成行;
tabooext              # 不转储指定扩展名的文件,缺省扩展名:cfsaved,.disabled,.dpkg-dist等;
sharedscripts         # 共享脚本,让postrotate/endscript包含脚本只执行一次即可;
dateformat            # 配合dateext使用可以为切割后的日志加上YYYYMMDD格式的日期;

以上参数都可以在全局主配置文件中定义,或指定为某个日志文件进行配置,注意:使用时参数之间不要冲突。

更多参数配置请参阅:

//jlk.fjfi.cvut.cz/arch/manpages/man/logrotate.8
//www.skrenta.com/rt/man/logrotate.8.html
//www.freebsd.org/cgi/man.cgi?query=logrotate&sektion=8&apropos=0&manpath=CentOS+7.1

如何在Linux中设置SSH无密码登录

作为一名运维人员来说,管理1-5台机器尚有余力,但如果是10台、100台或更多服务器,是不是每次登录输入密码非常繁琐,且费时费力,无法提高工作效率。
今天我们通过使用ssh-kengen命令生成私钥&公钥对,目的:免密码登录SSH。其算法有两种,分别是RSADSA

RSA 是非对称加密算法,可以用来加密和签名。
DSA(Digital Signature Algorithm) 只能用来数字签名的算法。

以下操作适用于OS:Centos 7Ubuntu 17,其他系统没测,理论上都可以使用。

服务器:

10.10.204.63
10.10.204.64

1.如何生成ssh公钥

登录10.10.204.63服务器生成公私密钥对:

[root@10-10-204-63 ~]# ssh-keygen -b 4096 -t rsa

Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:qLcoj2nSzq6G9ZpFQZ/OFqFT+oBDf3ousHkt82F1/xM root@10-10-204-63.10.10.204.63
The key's randomart image is:
+---[RSA 4096]----+
|  . . o          |
| . + = o         |
|  o B =          |
|   . X o         |
|  . o B S .      |
|  .= * . . .  E  |
|.oo.B *     .  . |
|oo+*.O o     ..  |
|o*O+o o       .. |
+----[SHA256]-----+

三次回车即可生成 ssh key

注解:

-b 指定密钥长度。对于RSA密钥,最小要求768位,默认是2048位,最长4096字节。
-t 指定要创建的密钥类型。可以使用:”rsa1″(SSH-1) “rsa”(SSH-2) “dsa”(SSH-2)。

2.查看生成的文件

[root@10-10-204-63 ~]# ll .ssh/
total 8
-rw------- 1 root root 3243 Nov 25 15:58 id_rsa
-rw-r--r-- 1 root root  758 Nov 25 15:58 id_rsa.pub

说明:

id_rsa 私钥
id_rsa.pub 公钥

3.将公钥上传到10.10.204.64

[root@10-10-204-63 ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub root@10.10.204.64
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host '10.10.204.64 (10.10.204.64)' can't be established.
ECDSA key fingerprint is SHA256:/YI/L4RT1QH7lkfxMCAkKnvniQslyUl15mOUKUo8K3k.
ECDSA key fingerprint is MD5:6d:b6:f3:93:8e:48:53:24:9d:5d:c2:2a:5f:28:f4:d2.
Are you sure you want to continue connecting (yes/no)? yes【输入yes回车】
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@10.10.204.64's password:【输入服务器密码回车】

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'root@10.10.204.64'"
and check to make sure that only the key(s) you wanted were added.

上传成功。

4.修改SSH配置文件

登录10.28.204.64修改,操作如下:

$ vim /etc/ssh/sshd_config

去除以下注释:

RSAAuthentication yes
PubkeyAuthentication yes

5.重启SSH服务

$ systemctl restart sshd

6.测试免密码登录10.10.204.64

[root@10-10-204-63 ~]# ssh 'root@10.10.204.64'
Last failed login: Sat Nov 25 16:09:48 CST 2017 from 83.234.149.66 on ssh:notty
There was 1 failed login attempt since the last successful login.
Last login: Sat Nov 25 15:57:33 2017 from 36.7.69.84
[root@10-10-204-64 ~]#

在不输入密码的情况下成功登录。

登陆成功后,建议在10.10.204.64服务器上也生成ssh公钥,并上传到10.10.204.63服务器,这样以来我们就可以相互免密码SSH登陆。多台服务器亦是如此。

7.查看公钥

[root@10-10-204-64 ~]# ll /root/.ssh/
total 8
-rw-------  1 root root 758 Nov 25 16:08 authorized_keys
-rw-r--r--. 1 root root 175 Aug  9 09:19 known_hosts

authorized_keys是刚上传过来的公钥名称

8.如果公钥丢失,可以使用私钥再次生成公钥,命令如下:

[root@10-10-204-63 ~]# ssh-keygen -y -f ~/.ssh/id_rsa > ~/.ssh/id_rsa.pub

完结。

MySQL自动备份并提交到码云Git仓库

之所以选择码云是因为其私有仓库是免费的,而GitHub私有仓库是收费,约7+美元一月,对于个人开发者似乎也是一笔不小的费用。

在创建自动将备份上传到码云Git仓库前,建议您先看下以下文章:

如何通过Git将本地项目推送到码云或GitHub

对于不太了解Git的朋友来说,此文章非常有用,否则在进行以下步骤时会出现各种报错。

实现方案:

    • 登录到码云
    • 创建私有仓库
    • 服务器生成ssh公钥
    • 创建SSH公钥

以上步骤在上文中有详细说明。

1.创建shell脚本文件:

$ cd /mnt/renwole
$ vim mysqlbak.sh

2.添加以下内容:

#!/bin/bash
createAt=`date +%Y-%m-%d-%H:%M:%S`
mysql_back_path=/mnt/MySQL-Bak
/usr/local/mysql/bin/mysqldump -u数据库用户名 -p密码 数据库名 > $mysql_back_path/renwoleblog-$createAt.sql
# 自动删除7天前的备份
# -type 文件类型 f是文件
find $mysql_back_path -name "*.sql" -type f -mtime +7 -exec rm -rf {} \;
cd $mysql_back_path
git add -A
git commit -m "${createAt}"
git push origin master

注意:上面的路径一定要是绝对路径,否则执行crontabmysqldump成功,但是导出结果为空,手动执行正常!

3.设置执行权限:

$ chmod +x mysqlbak.sh

4.添加任务计划:

通过crontab定时执行备份脚本

$ crontab -e

插入如下内容:

*/50 2 * * * /mnt/renwole/mysqlbak.sh
$ systemctl restart crond

设置完成后,每日凌晨2点50分,自动备份mysql数据库并推送到码云git仓库,后期可以通过Git查看历史提交的版本。再也不用担心数据丢失了。

如何通过Git将本地项目提交到码云或GitHub

何为码云?

码云是专为开发者提供稳定、高效、安全的云端软件开发协作平台。
无论是个人、团队、或是企业,都能够用码云实现代码托管、项目管理、协作开发。

PS:

说白了就是和Github一样。但没有Github的开发者和项目多,再怎么说,人家是全球性的。
但码云速度快(毕竟在国内),私有仓库免费,而且不限制私有库和公有库数量,可以作为备份仓库。

OS环境:CentOS Linux release 7.4.1708 (Core)

1.安装配置Git

$ yum install git -y
$ git config --global user.name "renwole"
$ git config --global user.email renwole@renwole.com

2.在终端生成ssh公钥

执行下面命令,三次回车即可生成 ssh key

$ ssh-keygen -t rsa -C "renwole@renwole.com"

3.查看生成的public key

$ cat ~/.ssh/id_rsa.pub
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDR9k1FgZRJN3P7V9tLfWZQ......

将以上打印出屏幕的内容添加到码云。

说明:SSH key添加地址://gitee.com/profile/sshkeys。公钥标题任意。

4.测试是否可以信任连接

添加后,在终端中输入以下命令:

$ ssh -T git@gitee.com
The authenticity of host 'gitee.com (120.55.226.24)' can't be established.
ECDSA key fingerprint is SHA256:FQGC9Kn/eye1W8icdBgrQp+KkGYoFgbVr17bmjey0Wc.
ECDSA key fingerprint is MD5:27:e5:d3:79:2a:9e:eb:6c:93:cd:1f:c1:47:a3:54:b1.
Are you sure you want to continue connecting (yes/no)? yes【输入yes回车】
Warning: Permanently added 'gitee.com,120.55.226.24' (ECDSA) to the list of known hosts.
Authentication failed.

再次执行:

$ ssh -T git@gitee.com
Welcome to Gitee.com, yourname!

返回信息表示已经成功。

5.在码云创建私有仓库

打开码云首页 – 登录 – 点击右上角圆形+号 – 填写你的项目信息 – 创建完成。

打开你的项目地址,例如:

//gitee.com/renwole/renwolecom

点击克隆/下载 – 获取你的SSH地址,下面要用到。

6.把远程仓库项目clone到本地

$ cd /mnt
$ git clone git@gitee.com:renwole/renwolecom.git
Cloning into 'renwolecom'...
remote: Counting objects: 11, done.
remote: Compressing objects: 100% (10/10), done.
remote: Total 11 (delta 2), reused 0 (delta 0)
Receiving objects: 100% (11/11), 19.51 MiB | 5.46 MiB/s, done.
Resolving deltas: 100% (2/2), done.
$ cd renwolecom
$ ll
total 16
-rw-r--r--. 1 root root 10254 Nov 22 09:26 LICENSE
-rw-r--r--. 1 root root    13 Nov 22 09:26 README.md

已经成功克隆到本地。

7.提交项目

你可以将renwolecom目录视为你的项目,鲁完代码直接提交。

无论此项目是否多人参与,push之前先pull,看是否有merge代码,若存在merge就解决merge,若无,请执行以下命令:

$ git pull origin master
$ git add -A
$ git commit -m 'init'
$ git push origin master

8.删除GIT仓库所有提交历史记录

8.1.Checkout

$ git checkout --orphan latest_branch

8.2. Add all the files

$ git add -A

8.3. Commit the changes

$ git commit -am "commit message"

8.4. Delete the branch

$ git branch -D master

8.5.Rename the current branch to master

$ git branch -m master

8.6.Finally, force update your repository

$ git push -f origin master

删除远程文件,本地保留:

$ git rm --cached 文件名
$ git commit -m "remove file from remote repository"
$ git push

删除远程文件夹,本地保留:

$ git rm --cached -r 文件夹名
$ git commit -m "remove directory from remote repository"
$ git push

注意:删除文件夹请使用 -r 参数。

说明:最后上传项目时可选参数 git push origin master -f 表示强制推送要上传的文件。

执行结束后,可以刷新项目地址并查看从本地push仓库的内容。

Centos 7源代码安装配置 Apache 生产篇

什么是Apache?

Apache是​​互联网上最流行的网络web服务器。全球一半以上网站都是使用Apache作为服务器。其也是一个工业级的 Web服务器。

在本文中我主要介绍如何安装Apache HTTP服务器,你只要按照本教程的步骤操作,一定可以安装成功,需要说明的是,如果你只安装Apache,而不安装php,请在配置文件中,删除 FilesMatch 包含的内容,否则会报错找不到PHP。

如果你需要安装PHP/Mysql数据库,那么本站教程太适合你了,关于php和mysql的安装,请阅读:11、12步骤。

说明:本文教程适用于生产环境,Apache是基于FPM/FastCGI解析的PHP。

系统环境:Centos 7.4 Apache 2.4.29

1.更新系统

$ yum update && yum upgrade -y

2.安装扩展包以及依赖包

$ yum install epel-release -y
$ yum install gcc gcc-c++ openssl openssl-devel libtool expat-devel zlib-devel python-devel -y

3.安装pcre

$ wget ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.41.tar.gz
$ tar zxvf pcre-8.41.tar.gz
$ cd pcre-8.41
$ ./configure
$ make -j8 && make install

4.安装nghttp2

$ wget //github.com/nghttp2/nghttp2/releases/download/v1.27.0/nghttp2-1.27.0.tar.gz
$ tar zxvf nghttp2-1.27.0.tar.gz
$ cd nghttp2-1.27.0
$ ./configure
$ make -j8 && make install
$ echo '/usr/local/lib' > /etc/ld.so.conf.d/local.conf
$ ldconfig

5.安装Apache httpd

创建用户与组并下载httpd apr apr-util安装包:

$ groupadd www
$ useradd -g www www
$ cd /tmp
$ wget //mirrors.shuosc.org/apache//httpd/httpd-2.4.29.tar.gz
$ wget //mirrors.tuna.tsinghua.edu.cn/apache//apr/apr-1.6.3.tar.gz
$ wget //mirrors.tuna.tsinghua.edu.cn/apache//apr/apr-util-1.6.1.tar.gz

解压相关包:

$ tar xvf httpd-2.4.29.tar.gz
$ tar xvf apr-1.6.3.tar.gz
$ tar xvf apr-util-1.6.1.tar.gz

apr-1.6.3apr-util-1.6.1移动到httpd-2.4.29/srclib目录下。操作如下:

$ cd httpd-2.4.29
$ cp -R ../apr-1.6.3 srclib/apr
$ cp -R ../apr-util-1.6.1 srclib/apr-util

注意:移动不准带版本号,否则编译安装时找不到库。

开始安装:

$ ./configure \
--prefix=/usr/local/apache \
--enable-mods-shared=most \
--enable-headers \
--enable-mime-magic \
--enable-proxy \
--enable-so \
--enable-rewrite \
--with-ssl \
--with-nghttp2 \
--enable-ssl \
--enable-deflate \
--with-pcre \
--with-included-apr \
--with-apr-util \
--enable-mpms-shared=all \
--with-mpm=prefork \
--enable-remoteip \
--enable-http2 \
--enable-dav \
--enable-expires \
--enable-static-support \
--enable-suexec \
--enable-modules=all \
$ make -j8 && make install

安装完成。

6.配置httpd.conf

$ cd /usr/local/apache/conf
$ vim httpd.conf

除默认配置外,请取消以下注释,开启相关模块:

LoadModule ext_filter_module modules/mod_ext_filter.so
LoadModule deflate_module modules/mod_deflate.so
LoadModule expires_module modules/mod_expires.so
LoadModule remoteip_module modules/mod_remoteip.so
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_connect_module modules/mod_proxy_connect.so
LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so
LoadModule proxy_scgi_module modules/mod_proxy_scgi.so
LoadModule proxy_wstunnel_module modules/mod_proxy_wstunnel.so
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule proxy_express_module modules/mod_proxy_express.so
LoadModule slotmem_shm_module modules/mod_slotmem_shm.so
LoadModule ssl_module modules/mod_ssl.so
LoadModule http2_module modules/mod_http2.so
LoadModule lbmethod_byrequests_module modules/mod_lbmethod_byrequests.so
LoadModule lbmethod_bytraffic_module modules/mod_lbmethod_bytraffic.so
LoadModule lbmethod_bybusyness_module modules/mod_lbmethod_bybusyness.so
LoadModule lbmethod_heartbeat_module modules/mod_lbmethod_heartbeat.so
LoadModule suexec_module modules/mod_suexec.so
LoadModule rewrite_module modules/mod_rewrite.so

在模块结尾部分添加如下内容:

<IfModule http2_module>
ProtocolsHonorOrder On
Protocols h2 http/1.1
</IfModule>

修改以下参数配置

将用户组设置为:

User www
Group www

默认值:

#ServerName www.example.com:80

修改为:

ServerName 0.0.0.0:80

注意:如果基于端口创建虚拟主机,请换行加端口,然后在虚拟主机配置文件中指定端口即可。

将配置文件中的所有:

AllowOverride None

修改为:

AllowOverride All

在以下内容位置:

AddType application/x-compress .Z
AddType application/x-gzip .gz .tgz

添加:

AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps

取消以下注释并添加apache支持python:

AddHandler cgi-script .cgi .py

取消以下注释:

Include conf/extra/httpd-mpm.conf
Include conf/extra/httpd-vhosts.conf
Include conf/extra/httpd-default.conf

以下内容在文件尾部添加

开启GZIP:

<IfModule mod_headers.c>
 AddOutputFilterByType DEFLATE text/html text/plain text/css text/xml text/javascript
 <FilesMatch "\.(js|css|html|htm|png|jpg|swf|pdf|shtml|xml|flv|gif|ico|jpeg)$">
 RequestHeader edit "If-None-Match" "^(.*)-gzip(.*)$" "$1$2"
 Header edit "ETag" "^(.*)-gzip(.*)$" "$1$2"
 </FilesMatch>
 DeflateCompressionLevel 6
 SetOutputFilter DEFLATE
</IfModule>

设置apache安全:

ProtocolsHonorOrder On
PidFile /usr/local/apache/logs/httpd.pid
ServerTokens ProductOnly
ServerSignature Off

引入虚拟主机配置文件:

IncludeOptional conf/vhost/*.conf

7.创建目录及虚拟主机配置文件

$ mkdir -p /usr/local/apache/conf/vhost
$ mkdir -p /data/apps/web/renwolecom
$ vim /usr/local/apache/conf/vhost/renwolecom.conf

插入以下内容:

<VirtualHost *:80>
 ServerAdmin webmaster@example.com
 DocumentRoot "/data/apps/web/renwolecom"
 ServerName www.renwole.com
 ServerAlias renwole.com
 errorDocument 404 /404.html
 ErrorLog "/usr/local/apache/logs/renwolecom-error_log"
 CustomLog "/usr/local/apache/logs/renwolecom-access_log" combined

<FilesMatch \.php$>
 SetHandler "proxy:unix:/tmp/php-cgi.sock|fcgi://localhost"
 </FilesMatch>

<Directory "/data/apps/web/renwolecom">
 SetOutputFilter DEFLATE
 Options FollowSymLinks
 AllowOverride All
 Require all granted
 DirectoryIndex index.php index.html index.htm default.php default.html default.htm
 </Directory>
</VirtualHost>

以上内容请根据自己的网站实际路径修改。

说明:如果没有域名,请将域名绑定部分修改为127.0.0.1,在http.conf中添加其他端口即可实现IP+端口访问,要记得防火墙放行端口。

注意:建议清空httpd-vhosts.conf中的内容,或者不开启引用,否则重启httpd服务时会有警告,但不影响使用,主要原因是找到默认配置中的网站目录路径。

8.创建system系统单元启动文件

$ vim /usr/lib/systemd/system/httpd.service

添加以下内容:

[Unit]
Documentation=man:systemd-sysv-generator(8)
SourcePath=/usr/local/apache/bin/apachectl
Description=LSB: starts Apache Web Server
Before=runlevel2.target
Before=runlevel3.target
Before=runlevel4.target
Before=runlevel5.target
Before=shutdown.target
After=all.target
After=network-online.target
Conflicts=shutdown.target

[Service]
Type=forking
Restart=no
TimeoutSec=5min
IgnoreSIGPIPE=no
KillMode=process
GuessMainPID=no
RemainAfterExit=yes
ExecStart=/usr/local/apache/bin/apachectl start
ExecStop=/usr/local/apache/bin/apachectl stop

9.加入开机自启/启动/停止/重启

$ systemctl enable httpd
$ systemctl start httpd
$ systemctl stop httpd
$ systemctl restart httpd

10.设置Firewalld防火墙

$ firewall-cmd --permanent --zone=public --add-service=http
$ firewall-cmd --permanent --zone=public --add-service=https
$ firewall-cmd --reload

接下来你就可以使用域名或IP访问你的网站了。

11.部署PHP篇

请参阅《Centos 7源码编译安装 php7.1 生产篇

12.部署Mysql篇

请参阅《Centos 7二进制安装配置 MariaDB(MySQL)数据库

Apache HTTP服务器的安装与配置至此已经结束,如果在安装配置过程中出现任何报错,请查看/usr/local/apache/logs/下的错误日志,以便你能快速解决所遇到的问题。

若还有其他指教,欢迎你的留言。

Apache Nginx 禁止目录执行PHP脚本文件

我们在搭建网站的时候,可能需要单独对一些目录进行设置权限,以达到我们需要的安全效果。下面举例说明在Apache或Nginx下如何设置禁止某个目录执行php文件。

1.Apache配置

<Directory /apps/web/renwole/wp-content/uploads>
 php_flag engine off
</Directory>
<Directory ~ "^/apps/web/renwole/wp-content/uploads">
 <Files ~ ".php">
 Order allow,deny
 Deny from all
 </Files>
</Directory>

2.Nginx配置

location /wp-content/uploads {
    location ~ .*\.(php)?$ {
    deny all;
    }
}

Nginx禁止多个目录执行PHP:

location ~* ^/(css|uploads)/.*\.(php)${
    deny all;
}

配置完成后,重载配置文件或重启Apache或Nginx服务,之后所有通过uploads来访问php文件,都将返回403,大大地增加了web目录安全性。

MongoDB 基本常用管理命令详解

创建认证用户

取消认证:

如不取消认证则无法创建用户,新安装的 MongoDB 默认没开启认证。

注释掉 /etc/mongod.conf 以下内容:

#security:
 # authorization: enabled

注意:创建用户完成后再加上参数并取消注释,修改MongoDB配置文件必须重启MongoDB服务。

重启MongoDB

$ systemctl restart mongod

登录mongo数据库:

$ mongo
MongoDB shell version v3.4.9
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.9
Server has startup warnings:
2017-11-20T14:50:48.633+0800 I STORAGE  [initandlisten]
2017-11-20T14:50:48.633+0800 I STORAGE  [initandlisten] ** WARNING: Readahead for /apps/mongo is set to 4096KB
2017-11-20T14:50:48.633+0800 I STORAGE  [initandlisten] **          We suggest setting it to 256KB (512 sectors) or less
2017-11-20T14:50:48.633+0800 I STORAGE  [initandlisten] **          //dochub.mongodb.org/core/readahead
2017-11-20T14:50:48.658+0800 I CONTROL  [initandlisten]
2017-11-20T14:50:48.658+0800 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2017-11-20T14:50:48.658+0800 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2017-11-20T14:50:48.658+0800 I CONTROL  [initandlisten]
>

在 admin 库中创建超级用户,超级用户用于管理其他用户的权限:

> use admin
db.createUser(
  {
    user: "admin",
    pwd: "admin",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)

以上参数说明:

user:用户
pwd:用户密码
roles:一组角色设置(对象)
role:角色名
db:角色所控制的数据库名

MongoDB数据库角色说明:

普通用户角色:readreadWrite
数据库管理员角色:dbAdmindbOwneruserAdmin
集群管理员角色:clusterAdminclusterManagerclusterMonitorhostManager
数据库备份与恢复角色:backuprestore
所有数据库角色:readAnyDatabasereadWriteAnyDatabaseuserAdminAnyDatabasedbAdminAnyDatabase
超级用户角色:root,这里还有几个角色间接或直接提供了系统超级用户的访问(dbOwneruserAdminuserAdminAnyDatabase)。
核心角色:__system

开启认证并登录 MongoDB 查看数据库:

$ mongo
MongoDB shell version v3.4.9
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.9
> use admin
switched to db admin
> show dbs
2017-11-20T15:23:04.399+0800 E QUERY    [thread1] Error: listDatabases failed:{
        "ok" : 0,
        "errmsg" : "not authorized on admin to execute command { listDatabases: 1.0 }",
        "code" : 13,
        "codeName" : "Unauthorized"
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
Mongo.prototype.getDBs@src/mongo/shell/mongo.js:62:1
shellHelper.show@src/mongo/shell/utils.js:769:19
shellHelper@src/mongo/shell/utils.js:659:15
@(shellhelp2):1:1

提示无权限,下面开始认证数据库:

> db.auth("admin","admin")
1

说明:1表示认证通过,0表示认证无法通过。

再次获取数据库列表成功:

> show dbs
admin         0.078GB
local         0.078GB

创建MongoDB用户及数据库

创建普通用户:

> use renwolecomdb
db.createUser(
  {
    user: "renwolecom",
    pwd: "renwolecom",
    roles: [ { role: "readWrite", db: "renwolecomdb" } ]
  }
)

查看系统所有用户授权情况:

> use admin
> db.system.users.find()

查看当前库用户角色情况(包含当前数据库下所有用户):

> use renwolecomdb
> show users

创建数据库

use 命令只是向 MongoDB 注册database,并没有实际的创建,而使用 show dbs 命令也无法查看列表中新建的database

> use renwolecomdb
switched to db renwolecomdb

认证数据库:

> db.auth("renwolecom","renwolecom")

注意:这里需要说明:你每切换一个数据库都需要进行用户认证,否则会提示你没有授权,无法写入。

要在列表中显示新建的(renwolecomdb)数据库,至少需要插入一条文档数据,空数据库无法在列表显示。

现在在当前database中创建collection,并向集合中插入数据:

> db.renwolecomdb.insert({"name":"任我乐-知识分享的开发者技术博客"})
WriteResult({ "nInserted" : 1 })

查看数据库列表:

> show dbs
admin         0.078GB
local         0.078GB
renwolecomdb  0.078GB

已经显示刚刚新建的数据库名。

获取当前数据库详细信息:

> db.stats()
{
        "db" : "renwolecomdb",
        "collections" : 5,
        "views" : 0,
        "objects" : 13,
        "avgObjSize" : 82.46153846153847,
        "dataSize" : 1072,
        "storageSize" : 36864,
        "numExtents" : 5,
        "indexes" : 3,
        "indexSize" : 24528,
        "fileSize" : 67108864,
        "nsSizeMB" : 16,
        "extentFreeList" : {
                "num" : 0,
                "totalSize" : 0
        },
        "dataFileVersion" : {
                "major" : 4,
                "minor" : 22
        },
        "ok" : 1
}

说明:在进行任何集合操作前,都必须先切换到一个数据库。

MongoDB用户角色添加删除管理

给已存在的用户添加额外角色:

db.grantRolesToUser(
   "renwolecom",
   [ { role: "dbAdmin",db:"renwolecomdb"} ]
)

删除回收指定用户角色:

db.revokeRolesFromUser(
   "renwolecom",
   [{ role: "dbAdmin",db:"renwolecomdb"}]
)

查看当前数据库集合信息

获取集合信息(类似于关系型数据库的表):

> show collections
renwolecomdb
system.indexes

查看集合文档中数据

以下实例我们查询了集合 renwolecomdb 中的数据:

> use renwolecomdb
> db.auth("renwolecom","renwolecom")
1
> db.renwolecomdb.find().pretty()
{ "_id" : ObjectId("59f439c17a22e643554d915c"), "name" : "任我乐-知识分享的开发者技术博客" }

删除集合

集合删除语法格式如下:

db.renwolecomdb.drop()

删除数据库

删除指定数据库:

这时需要授权 renwolecom 用户删除角色即(dbAdmin),否则用户只有读写,并没有删除权限。

> use renwolecomdb
> db.dropDatabase()
{ "dropped" : "renwolecomdb", "ok" : 1 }

修改MongoDB用户密码信息

方法一:

以下命令不仅可以更新密码,还可以更新用户名:

> use admin
switched to db admin
> db.changeUserPassword("admin", "7utVM2RAfeAnDosq0jN20tu9jWkZQyNj")
> db.auth("admin","7utVM2RAfeAnDosq0jN20tu9jWkZQyNj")
1

已经修改成功,并且通过验证。

方法二(推荐):

只修改用户密码:

> use admin
switched to db admin
> db.changeUserPassword("admin", "7utVM2RAfeAnDosq0jN20tu9jWkZQyNj")

删除用户

将系统中所有关于 renwolecom 的用户删除:

> use admin
> db.system.users.remove({user:"renwolecom"});

只删除本数据中的 renwolecom 用户

> use renwolecomdb
> db.dropUser("renwolecom");

删除本数据下面所有用户

> use renwolecomdb
> db.dropAllUsers()

授权登录MongoDB

通过下面的方式可以直接登陆数据库并且已获得相应权限:

$ mongo renwolecomdb -u renwolecom -p
MongoDB shell version v3.4.9
Enter password:

更多命令可以输入以下命令查看:

> help

参考:

关于用户认证方法://docs.mongodb.com/manual/tutorial/enable-authentication/
关于用户管理方法://docs.mongodb.com/manual/reference/method/js-user-management/
关于角色管理方法://docs.mongodb.com/manual/reference/method/js-role-management/

利用百度网盘直接下载助手下载大文件

介绍:

百度网盘直接下载助手 是一款浏览器用户脚本(user scripts),在无登录,无客户端情况下直接下载百度网盘和百度网盘分享的大文件,避免下载文件时调用百度网盘客户端,获取网盘文件的直接下载地址。

此脚本不仅限于上述特性,而且还不限速,非常好用。

1.安装一个用户脚本管理器

使用Tampermonkey(油猴)脚本,需要在浏览器安装一个扩展,然后再安装脚本,支持以下浏览器:

ChromeMicrosoft Edge、SafariFirefoxOpera NextDolphin BrowserUC Browser

安装方法:

打开Tampermonkey官网选择匹配的浏览器点击下载安装即可:

//tampermonkey.net/

2.安装百度网盘直接下载助手脚本

打开以下连接安装此脚本即可:

//greasyfork.org/zh-CN/scripts/39504-%E7%99%BE%E5%BA%A6%E7%BD%91%E7%9B%98%E7%9B%B4%E6%8E%A5%E4%B8%8B%E8%BD%BD%E5%8A%A9%E6%89%8B-%E7%9B%B4%E9%93%BE%E5%8A%A0%E9%80%9F%E7%89%88

安装完成后,在百度网盘重新打开需要下载的链接地址,或刷新地址,此时你应该看到一个 下载助手 鼠标放上去会显示 直接下载 & 显示连接 如果你使用迅雷下载,复制下载连接,在迅雷中新建下载任务即可。

如果百度网盘直接下载助手不能使用,请打开 //greasyfork.org 网站,搜索关键字 百度网盘 会列出多个脚本,根据需要安装脚本即可,如果不行就多尝试几个,总有一款适合你。

Linux下的21个ss命令使用示例详解

简介:

Socket Statisticsss)命令类似于netstat,它用于显示各种有用的网络套接字信息。

长时间看,已经注意到netstat这个命令程序已经过时了。从而代替netstat的是ss命令。一个全新的ss命令使用起来必定有些陌生,不过ss许多选项与netstat使用的选项类似,但我们还会看到一些差异。

ss命令是Linux CentOS 7iproute软件包的一部分,默认已经安装。

一般来说,网络套接字是由IP地址,传输协议和端口来定义的。这种组合构成了双向连接的一个方面。例如:一个Web服务器可能正在侦听172.28.204.62:80上的传入TCP连接,这是套接字。不过需要说明的是套接字不是连接本身,而是连接的端点之一。

下面我讲解如何使用ss命令查看各种信息。具体使用语法如下:

ss [options] [ FILTER ]

1.列出已建立的连接

默认情况下,如果我们运行ss命令而没有指定其他选项,它将显示所有已建立连接的打开的非侦听套接字的列表,例如TCPUDPUNIX套接字。

[root@renwolecom ~]# ss | head -n 5
Netid  State  Recv-Q Send-Q Local Address:Port   Peer Address:Port
u_str  ESTAB  0      0       * 19098                 * 18222
u_str  ESTAB  0      0       * 19441                 * 19440
u_str  ESTAB  0      0       * 19440                 * 19441
u_str  ESTAB  0      0       * 19396                 * 19397

2.显示监听套接字

我们可以使用-l选项专门列出当前正在侦听连接的套接字,而不是列出所有的套接字。

[root@renwolecom ~]# ss -lt
State   Recv-Q Send-Q    Local Address:Port       Peer Address:Port
LISTEN  0      128                   *:http                  *:*
LISTEN  0      100           127.0.0.1:smtp                  *:*
LISTEN  0      128                   *:entexthigh            *:*
LISTEN  0      128       172.28.204.62:zabbix-trapper        *:*
LISTEN  0      128           127.0.0.1:cslistener            *:*
LISTEN  0      80                   :::mysql                :::*
LISTEN  0      100                 ::1:smtp                 :::*
LISTEN  0      128                  :::entexthigh           :::*

在这个示例中,我们还使用-t选项只列出TCP,稍后将对此进行详细说明。在后面的例子中,你会看到我将结合多种选择,以快速过滤掉,从而达到我们的目的。

3.显示进程

我们可以用-p选项打印出拥有套接字的进程或PID号。

[root@renwolecom ~]# ss -pl

Netid  State      Recv-Q Send-Q Local Address:Port     Peer Address:Port
tcp    LISTEN     0      128    :::http                :::*                 users:(("httpd",pid=10522,fd=4),("httpd",pid=10521,fd=4),("httpd",pid=10520,fd=4),("httpd",pid=10519,fd=4),("httpd",pid=10518,fd=4),("httpd",pid=10516,fd=4))

在上面的例子中我只列出了一个结果,没有进行进一步选项,因为ss的完整输出打印出超过500行到标准输出。所以我只列出一条结果,由此我们可以看到服务器上运行的各种Apache进程ID。

4.不解析服务名称

默认情况下,ss只会解析端口号,例如在下面的行中,我们可以看到172.28.204.62:mysql,其中mysql被列为本地端口。

[root@renwolecom ~]# ss
Netid State Recv-Q Send-Q   Local Address:Port      	Peer Address:Port
tcp   ESTAB 0      0 ::ffff:172.28.204.62:mysql ::ffff:172.28.204.62:38920
tcp   ESTAB 0      0 ::ffff:172.28.204.62:mysql ::ffff:172.28.204.62:51598
tcp   ESTAB 0      0 ::ffff:172.28.204.62:mysql ::ffff:172.28.204.62:51434
tcp   ESTAB 0      0 ::ffff:172.28.204.62:mysql ::ffff:172.28.204.62:36360

但是,如果我们指定-n选项,看到的是端口号而不是服务名称。

[root@renwolecom ~]# ss -n
Netid State Recv-Q Send-Q   Local Address:Port      	Peer Address:Port
tcp   ESTAB 0      0 ::ffff:172.28.204.62:3306  ::ffff:172.28.204.62:38920
tcp   ESTAB 0      0 ::ffff:172.28.204.62:3306  ::ffff:172.28.204.62:51598
tcp   ESTAB 0      0 ::ffff:172.28.204.62:3306  ::ffff:172.28.204.62:51434
tcp   ESTAB 0      0 ::ffff:172.28.204.62:3306  ::ffff:172.28.204.62:36360

现在显示3306,而非mysql,因为禁用了主机名和端口的所有名称解析。另外你还可以查看/etc/services得到所有服务对应的端口列表。

5.解析数字地址/端口

-r选项可以解析IP地址和端口号。用此方法可以列出172.28.204.62服务器的主机名。

[root@renwolecom ~]# ss -r
Netid  State  Recv-Q Send-Q        Local Address:Port      Peer Address:Port
tcp    ESTAB      0      0         renwolecom:mysql        renwolecom:48134

6.IPv4套接字

我们可以通过-4选项只显示与IPv4套接字对应的信息。在下面的例子中,我们还使用-l选项列出了在IPv4地址上监听的所有内容。

[root@renwolecom ~]# ss -l4
Netid State      Recv-Q Send-Q  Local Address:Port            Peer Address:Port
tcp   LISTEN     0      128                 *:http                       *:*
tcp   LISTEN     0      100         127.0.0.1:smtp                       *:*
tcp   LISTEN     0      128                 *:entexthigh                 *:*
tcp   LISTEN     0      128     172.28.204.62:zabbix-trapper             *:*
tcp   LISTEN     0      128         127.0.0.1:cslistener                 *:*

7.IPv6套接字

同样,我们可以使用-6选项只显示与IPv6套接字相关信息。在下面的例子中,我们还使用-l选项列出了在IPv6地址上监听的所有内容。

[root@renwolecom ~]# ss -l6
Netid State      Recv-Q Send-Q  Local Address:Port            Peer Address:Port
udp   UNCONN     0      0                  :::ipv6-icmp                 :::*
udp   UNCONN     0      0                  :::ipv6-icmp                 :::*
udp   UNCONN     0      0                  :::21581                     :::*
tcp   LISTEN     0      80                 :::mysql                     :::*
tcp   LISTEN     0      100               ::1:smtp                      :::*
tcp   LISTEN     0      128                :::entexthigh                :::*

8.只显示TCP

-t选项只显示TCP套接字。当与-l结合只打印出监听套接字时,我们可以看到所有在TCP上侦听的内容。

[root@renwolecom ~]# ss -lt
State       Recv-Q Send-Q    Local Address:Port               Peer Address:Port
LISTEN      0      128                   *:http                          *:*
LISTEN      0      100           127.0.0.1:smtp                          *:*
LISTEN      0      128                   *:entexthigh                    *:*
LISTEN      0      128       172.28.204.62:zabbix-trapper                *:*
LISTEN      0      128           127.0.0.1:cslistener                    *:*
LISTEN      0      80                   :::mysql                        :::*
LISTEN      0      100                 ::1:smtp                         :::*
LISTEN      0      128                  :::entexthigh                   :::*

9.显示UDP

-u选项可用于仅显示UDP套接字。由于UDP是一种无连接的协议,因此只运行-u选项将不显示输出,我们可以将它与-a-l选项结合使用,来查看所有侦听UDP套接字,如下所示:

[root@renwolecom ~]# ss -ul
State      Recv-Q Send-Q Local Address:Port                 Peer Address:Port
UNCONN     0      0              *:sunwebadmins                 *:*
UNCONN     0      0              *:etlservicemgr                *:*
UNCONN     0      0              *:dynamid                      *:*
UNCONN     0      0              *:9003                         *:*
UNCONN     0      0              *:9004                         *:*
UNCONN     0      0      127.0.0.1:terabase                     *:*
UNCONN     0      0              *:56803                        *:*

10. Unix套接字

-x选项只能用来显示unix域套接字。

[root@renwolecom ~]# ss -x
Netid State Recv-Q Send-Q                    Local Address:Port Peer Address:Port
u_str ESTAB 0      0 /tmp/zabbix_server_preprocessing.sock 23555           * 21093
u_str ESTAB 0      0          /tmp/zabbix_server_ipmi.sock 20155           * 19009
u_str ESTAB 0      0 /tmp/zabbix_server_preprocessing.sock 19354           * 22573
u_str ESTAB 0      0 /tmp/zabbix_server_preprocessing.sock 21844           * 19375
...

11.显示所有信息

-a选项显示所有的监听和非监听套接字,在TCP的情况下,这意味着已建立的连接。这个选项与其他的组合很有用,例如可以添加-a选项显示所有的UDP套接字,默认情况下只有-u选项我们看不到多少信息。

[root@renwolecom ~]# ss -u
Recv-Q Send-Q Local Address:Port                 Peer Address:Port
0      0      172.28.204.66:36371                    8.8.8.8:domain
[root@renwolecom ~]# ss -ua
State      Recv-Q Send-Q Local Address:Port                 Peer Address:Port
UNCONN     0      0                 *:sunwebadmins                    *:*
UNCONN     0      0                 *:etlservicemgr                   *:*
UNCONN     0      0                 *:dynamid                         *:*
UNCONN     0      0                 *:9003                            *:*
UNCONN     0      0                 *:9004                            *:*
UNCONN     0      0         127.0.0.1:terabase                        *:*
UNCONN     0      0                 *:56803                           *:*
ESTAB      0      0      172.28.204.66:36371                     8.8.8.8:domain

12.显示套接字内存使用情况

-m选项可用于显示每个套接字使用的内存量。

[root@renwolecom ~]# ss -ltm
State   Recv-Q Send-Q  Local Address:Port Peer Address:Port
LISTEN  0      128                 *:http           *:*skmem:(r0,rb87380,t0,tb16384,f0,w0,o0,bl0)
LISTEN  0      100         127.0.0.1:smtp           *:*skmem:(r0,rb87380,t0,tb16384,f0,w0,o0,bl0)
LISTEN  0      128                 *:entexthigh     *:*skmem:(r0,rb87380,t0,tb16384,f0,w0,o0,bl0)
LISTEN  0      128     172.28.204.62:zabbix-trapper *:*skmem:(r0,rb87380,t0,tb16384,f0,w0,o0,bl0)
LISTEN  0      128         127.0.0.1:cslistener     *:*skmem:(r0,rb87380,t0,tb16384,f0,w0,o0,bl0)
LISTEN  0      80                 :::mysql         :::*skmem:(r0,rb87380,t0,tb16384,f0,w0,o0,bl0)
LISTEN  0      100               ::1:smtp          :::*skmem:(r0,rb87380,t0,tb16384,f0,w0,o0,bl0)
LISTEN  0      128                :::entexthigh    :::*skmem:(r0,rb87380,t0,tb16384,f0,w0,o0,bl0)

13.显示TCP内部信息

我们可以使用-i选项请求额外的内部TCP信息。

[root@renwolecom ~]# ss -lti
State       Recv-Q Send-Q Local Address:Port         Peer Address:Port
LISTEN      0      128               *:chimera-hwm              *:* 	bbr cwnd:10
LISTEN      0      128               *:etlservicemgr            *:* 	bbr cwnd:10
LISTEN      0      128   172.28.204.66:27017                    *:* 	bbr cwnd:10
LISTEN      0      128       127.0.0.1:27017                    *:* 	bbr cwnd:10
LISTEN      0      128               *:dynamid                  *:* 	bbr cwnd:10
LISTEN      0      128               *:9003                     *:* 	bbr cwnd:10
LISTEN      0      128               *:9004                     *:* 	bbr cwnd:10
LISTEN      0      128               *:http                     *:* 	bbr cwnd:10
LISTEN      0      128               *:ssh                      *:* 	bbr cwnd:10
LISTEN      0      100       127.0.0.1:smtp                     *:* 	bbr cwnd:10
LISTEN      0      128               *:sunwebadmins             *:* 	bbr cwnd:10
LISTEN      0      128              :::ssh                     :::* 	bbr cwnd:10

在每个侦听套接字下面,我们可以看到更多信息。注意:-i选项不适用于UDP,如果您指定-u,而非-t,则不会显示这些额外的信息。

14.显示统计信息

我们可以使用-s选项快速查看统计数据。

[root@renwolecom ~]# ss -s
Total: 798 (kernel 1122)
TCP:   192 (estab 99, closed 81, orphaned 0, synrecv 0, timewait 1/0), ports 0

Transport Total     IP        IPv6
*         1122      -         -
RAW       1         0         1
UDP       0         0         0
TCP       111       59        52
INET      112       59        53
FRAG      0         0         0

这使我们能够快速看到已建立连接的总数,及各种类型的套接字的计数和IPv4或IPv6的使用情况。

15.基于状态的过滤器

我们可以指定一个套接字的状态,只打印这个状态下的套接字。例如,我们可以指定包括已建立, established, syn-sent, syn-recv, fin-wait-1, fin-wait-2, time-wait, closed, closed-wait, last-ack监听和关闭等状态。以下示例显示了所有建立的TCP连接。为了生成这个,我通过SSH连接到了服务器,并从Apache加载了一个网页。然后我们可以看到与Apache的连接迅速转变为等待时间。

[root@renwolecom ~]# ss -t state established
Recv-Q Send-Q       Local Address:Port              Peer Address:Port
0      52           172.28.204.67:ssh              123.125.71.38:49518
0      0     ::ffff:172.28.204.67:http      ::ffff:123.125.71.38:49237
[root@renwolecom ~]# ss -t state established
Recv-Q Send-Q       Local Address:Port              Peer Address:Port
0      0            172.28.204.67:ssh            103.240.143.126:55682
0      52           172.28.204.67:ssh              123.125.71.38:49518
0      0     ::ffff:172.28.204.67:http      ::ffff:123.125.71.38:49262

16.根据端口号进行过滤

可以通过过滤还可以列出小于(lt),大于(gt),等于(eq),不等于(ne),小于或等于(le),或大于或等于(ge)的所有端口。

例如,以下命令显示端口号为500或以下的所有侦听端口:

[root@renwolecom ~]# ss -ltn sport le 500
State       Recv-Q Send-Q Local Address:Port        Peer Address:Port
LISTEN      0      128                *:80                     *:*
LISTEN      0      100        127.0.0.1:25                     *:*
LISTEN      0      100              ::1:25                    :::*

为了进行比较,我们可以执行相反的操作,并查看大于500的所有端口:

[root@renwolecom ~]# ss -ltn sport gt 500
State       Recv-Q Send-Q Local Address:Port        Peer Address:Port
LISTEN      0      128                *:12002                  *:*
LISTEN      0      128    172.28.204.62:10051                  *:*
LISTEN      0      128        127.0.0.1:9000                   *:*
LISTEN      0      80                :::3306                  :::*
LISTEN      0      128               :::12002                 :::*

我们还可以根据源或目标端口等项进行筛选,例如,我们搜索具有SSH源端口运行的TCP套接字:

[root@renwolecom ~]# ss -t '( sport = :ssh )'
State       Recv-Q Send-Q    Local Address:Port     Peer Address:Port
ESTAB       0      0         172.28.204.66:ssh     123.125.71.38:50140

17.显示SELinux上下文

-Z-z选项可用于显示套接字的SELinux安全上下文。 在下面的例子中,我们使用-t和-l选项来列出侦听的TCP套接字,使用-Z选项我们也可以看到SELinux的上下文。

[root@renwolecom ~]# ss -tlZ
State  Recv-Q Send-Q  Local Address:Port        Peer Address:Port
LISTEN 0      128                 *:sunrpc                 *:*
users:(("systemd",pid=1,proc_ctx=system_u:system_r:init_t:s0,fd=71))
LISTEN 0      5       172.28.204.62:domain                 *:*
users:(("dnsmasq",pid=1810,proc_ctx=system_u:system_r:dnsmasq_t:s0-s0:c0.c1023,fd=6))
LISTEN 0      128                 *:ssh                    *:*
users:(("sshd",pid=1173,proc_ctx=system_u:system_r:sshd_t:s0-s0:c0.c1023,fd=3))
LISTEN 0      128         127.0.0.1:ipp                    *:*
users:(("cupsd",pid=1145,proc_ctx=system_u:system_r:cupsd_t:s0-s0:c0.c1023,fd=12))
LISTEN 0      100         127.0.0.1:smtp                   *:*
users:(("master",pid=1752,proc_ctx=system_u:system_r:postfix_master_t:s0,fd=13))

18.显示版本号

-v选项可用于显示ss命令的特定版本信息,在这种情况下,我们可以看到提供ssiproute包的版本。

[root@renwolecom ~]# ss -v
ss utility, iproute2-ss130716

19.显示帮助文档信息

-h选项可用于显示有关ss命令的进一步的帮助,如果需要对最常用的一些选项进行简短说明,则可以将其用作快速参考。 请注意:这里并未输入完整列表。

[root@renwolecom ~]# ss -h
Usage: ss [ OPTIONS ]

20.显示扩展信息

我们可以使用-e选项来显示扩展的详细信息,如下所示,我们可以看到附加到每条行尾的扩展信息。

[root@renwolecom ~]# ss -lte
State  Recv-Q Send-Q Local Address:Port   Peer Address:Port
LISTEN 0      128                *:sunrpc *:*      ino:16090 sk:ffff880000100000 <->
LISTEN 0      5      172.28.204.62:domain *:*      ino:23750 sk:ffff880073e70f80 <->
LISTEN 0      128                *:ssh    *:*      ino:22789 sk:ffff880073e70000 <->
LISTEN 0      128        127.0.0.1:ipp    *:*      ino:23091 sk:ffff880073e707c0 <->
LISTEN 0      100        127.0.0.1:smtp   *:*      ino:24659 sk:ffff880000100f80 <->

21.显示计时器信息

-o选项可用于显示计时器信息。该信息向我们展示了诸如重新传输计时器值、已经发生的重新传输的数量以及已发送的keepalive探测的数量。

[root@renwolecom ~]# ss -to
State      Recv-Q Send-Q Local Address:Port      Peer Address:Port
ESTAB      0      52     172.28.204.67:ssh      123.125.71.38:49518timer:(on,406ms,0)
LAST-ACK   0      1      172.28.204.67:ssh    103.240.143.126:49603timer:(on,246ms,0)

总结:

现在你应该对ss有了初步的认识。如果你想使用ss命令快速检查有关套接字的各种信息,建议你查阅ss的相关手册。

优化并修复 MariaDB(MySQL)数据库损坏的表文件

平时维护网站的时候一定会遇到数据表崩溃,这可能是MySQL没有正常关闭或断电等原因导致。这时就需要我们手动修复表文件,通常可以通过数据库管理工具,例如:phpmyadmin 进行可视化修复。下面我讲解在Linux下通过命令修复损坏的表文件。

以下操作以本博客使用的 WordPress 程序演示,如果部分表存在问题则可以修复或优化。

登录MariaDB数据库

$ mysql -u root -p
Enter password:[输入您的mysql或管理其数据库的密码]
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 84162
Server version: 10.3-MariaDB MariaDB Server

Copyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> use renwolecomdb;

查看当前所有数据表文件:

MariaDB [renwolecomdb]> show tables;
+------------------------+
| Tables_in_renwolecomdb  |
+------------------------+
| wp_baidusubmit_sitemap |
| wp_baidusubmit_urlstat |
| wp_commentmeta         |
| wp_comments            |
| wp_links               |
| wp_options             |
| wp_postmeta            |
| wp_posts               |
| wp_term_relationships  |
| wp_term_taxonomy       |
| wp_termmeta            |
| wp_terms               |
| wp_usermeta            |
| wp_users               |
+------------------------+
14 rows in set (0.00 sec)

如果感觉您的数据库某个表加载较慢,可以进行数据表优化,命令如下:

MariaDB [renwolecomdb]> OPTIMIZE TABLE wp_baidusubmit_urlstat;
+------------------------------------+----------+----------+----------+
| Table                              | Op       | Msg_type | Msg_text |
+------------------------------------+----------+----------+----------+
|renwolecomdb.wp_baidusubmit_urlstat | optimize | status   | OK       |
+------------------------------------+----------+----------+----------+
1 row in set (0.11 sec)

上面已打印出详细的分析报告。

下面将修复被破坏的表文件,命令如下:

MariaDB [renwolecomdb]> REPAIR TABLE wp_baidusubmit_sitemap;
+------------------------------------+--------+----------+----------+
| Table                              | Op     | Msg_type | Msg_text |
+------------------------------------+--------+----------+----------+
|renwolecomdb.wp_baidusubmit_sitemap | repair | status   | OK       |
+------------------------------------+--------+----------+----------+
1 row in set (0.00 sec)

修复成功。

修复 InnoDB 引擎的表文件,命令如下:

MariaDB [renwolecomdb]> REPAIR TABLE wp_commentmeta;
+----------------------------+--------+----------+---------------------------------------------------------+
| Table                      | Op     | Msg_type | Msg_text                                                |
+----------------------------+--------+----------+---------------------------------------------------------+
|renwolecomdb.wp_commentmeta | repair | note     | The storage engine for the table doesn't support repair |
+----------------------------+--------+----------+---------------------------------------------------------+
1 row in set (0.00 sec)

提示错误报告:The storage engine for the table doesn't support repair.

上述报错说明该数据库InnoDB引擎数据表不支持修复。

但需要说明的是:

InnoDB损坏表的几率非常小,因为InnoDB是先写入日志,再写入数据库,因此InnoDB引擎比MyISAM健壮很多,而且他有自我修复能力,一般情况一旦InnoDB的数据文件损坏,只能找备份恢复。

所以我们平时做运维的一定要对数据备份、备份、再备份,以防万一。