月度归档:2018年01月

CentOS 7配置Rsync数据文件同步服务器

何为Rsync?

Rsync是一个非常灵活的命令行网络同步工具,由于它在Linux和类unix系统上的普及,使它被默认包含在大多数Linux发行版中。它在同步文件或文件夹的同时,可以保持原来文件的权限、时间、软硬链接等附加信息, 它可以快速安全的传输数据,并且支持增量更新,传输数据的过程中可以实行压缩及解压缩操作,因此可以使用更少的带宽,不仅如此它还是开源软件。

环境:

RenwoleServer:10.28.204.65 服务端
RenwoleClient:10.28.204.66 客户端
OS:CentOS Linux release 7.4.1708 (Core) x64

1.分别在服务器端和客户端安装rsync

由于部分Linux发行版默认已安装rsync,但使用的版本 rsync 3.0.9-18.el7 有些旧,所以需手动安装最新版,请看以下具体操作:

2.安装rsync

如已默认安装,请卸载旧版本:

$ yum remove rsync -y

安装rsync有2种方式:

RPM方式的好处,快速、方便、节时,具体安装如下:

$ yum -y install epel-release
$ wget //mirror.ghettoforge.org/distributions/gf/gf-release-latest.gf.el7.noarch.rpm
$ rpm -Uvh gf-release*rpm
$ yum --enablerepo=gf-plus install rsync -y

rsync文件:

/etc/rsyncd.conf
/etc/sysconfig/rsyncd
/etc/xinetd.d/rsync
/usr/bin/rsync
/usr/share/doc/rsync-3.1.2/COPYING
......

源码安装(推荐)

此种安装方法的好处不但自定义方便,还可使用最新安装包。

安装依赖并下载源码包,编译安装:

$ cd /tmp
$ yum install gcc c++ -y
$ wget //download.samba.org/pub/rsync/rsync-3.1.2.tar.gz
$ tar zxvf rsync-3.1.2.tar.gz
$ cd rsync-3.1.2
$ ./configure --prefix=/usr/local/rsync
$ make -j8 && make install
$ ln -s /usr/local/rsync/bin/rsync /usr/bin/rsync

设置rsync自启动脚本

源码安装需手动将rsync默认提供的脚本拷贝到系统目录,这样才能使用systemctl管理:

$ cp /tmp/rsync-3.1.2/packaging/systemd/* /usr/lib/systemd/system

说明:源代码编译安装,没有/etc/rsyncd.conf主配置文件,需要手动创建,RPM安装方式会自动生成,但都需要根据需求重新配置。

两种安装方式不管使用哪种方法都可以安装成功。

下面将介绍rsync配置篇(以源代码编译安装配置为例)。

3.关于rsync认证方式

rsync有2种常用的认证方式,一种是rsync-daemon,另一种是SSH。在生产环境中,通常使用rsync-daemon认证模式。

认证模式说明:

1.rsync-daemon认证:默认监听TCP的873端口。前提是双方都需要安装rsync,客户端可不启动rsync服务,但需要简单的配置。服务器端需要启动且需在服务器端配置rsync。

2.SSH认证:通过系统用户认证,即在rsync上通过SSH隧道进行传输,前提是需要服务器端与客户端建立无密码登录,可参阅这里《如何在Linux中设置SSH无密码登录》。无需服务器与客户端配置rsync,也无需启动rsync服务,只需双方都安装rsync即可。

4.设置rsync服务端密码 10.28.204.65

本教程使用rsync-daemon认证方式。创建访问密码,格式为 用户名:密码,一行一个,明文。

$ echo "renwole:renwolecom"  >>/etc/rsync.password
$ chmod 600 /etc/rsync.password

5.配置rsync服务端 10.28.204.65

配置完成后的内容如下:

$ cat /etc/rsyncd.conf

uid = root               # 运行RSYNC守护进程的用户
gid = root               # 运行RSYNC守护进程的组
port = 873               # 默认端口
#address = 10.28.204.65  # 服务器IP地址
# pid file = /var/run/rsyncd.pid   # 进程启动后,进程号存放路径
lock file = /var/run/rsync.lock  # 设置锁文件名称
log file = /var/log/rsyncd.log     # 指定rsync的日志文件

use chroot = no          # 不使用chroot
read only = yes          # 只读,不让客户端上传文件到服务器
transfer logging = yes   # 将传输操作记录到传输日志文件

hosts allow=10.28.204.66           # 允许哪些主机访问(多个以空格隔开)
hosts deny=*                       # 拒绝哪些主机访问
max connections = 3                # 最大连接数
# motd file = /etc/rsyncd.motd     # 登陆欢迎信息(生产环境不建议)

log format = %t %a %m %f %b        # 指定日志记录的格式
syslog facility = local3           # 消息级别
timeout = 600                      # 会话超时时间。

[renwolecom]             # 模块的名称,可以自定义
path = /apps/www         # 需要同步的目录
list=yes                 # 是否允许用户列出文件,默认为true
ignore errors            # 忽略错误信息
# exclude = myrenwole/   # 不同步的目录(多个以空格隔开)
comment = RenwoleCombak  # 注释内容,任意
auth users = renwole     # 那些用户才允许连接该模块,多个以,隔开
secrets file = /etc/rsyncs.pass    # 认证时所需的密码文件

更多配置请参阅://www.gsp.com/cgi-bin/man.cgi?topic=rsyncd.conf

两个注意说明

注意:如果你拷贝以上配置项,请去掉注释说明,否则可能会出现未知问题。
注意:全局配置中的选项对所有模块有效;模块下定义的仅对当前模块有效;另外,模块中定义选项值优先于全局配置。

6.设置firewall防火墙

$ firewall-cmd --add-port=873/tcp --permanent
$ firewall-cmd --add-port=873/udp --permanent
$ firewall-cmd --reload

7.配置rsync客户端 10.28.204.66

客户端无需配置模块,也无需启动服务,配置文件只需简单配置即可,例如:

$ vim /etc/rsyncd.conf

uid = nobody
gid = nobody
use chroot = no
max connections = 10
pid file = /var/run/rsyncd.pid
lock file = /var/run/rsyncd.lock
log file = /var/log/rsyncd.log
port = 873
secrets file = /etc/client.pass

8.在客户端设置密码 10.28.204.66

添加密码并设置权限:

$ echo "renwolecom"  >>/etc/client.pass
$ chmod 600 /etc/client.pass

说明:只需添加服务端的密码即可,无需用户。

9.启动并加入开机自启动

$ systemctl start rsync
$ systemctl enable rsync
$ systemctl list-unit-files

10.测试rsync文件同步

rsync客户端 10.28.204.66 连接服务端测试

$ /usr/bin/rsync -avzrtopg --progress --delete --password-file=/etc/client.pass renwole@10.28.204.65::renwolecom /apps/www

客户端连接参数说明:

-avzrtopg 拆分讲解:

a # 归档模式,表示以递归方式传输文件,并保持所有文件属性,等于-rlptgoD;
v # 详细模式输出;
z # 对备份的文件在传输时进行压缩处理;
r # 对子目录以递归模式处理;
topg       # 保持原文件属性如属主、时间的参数。

--progress # 显示详细的同步进度情况。
--delete   # 若服务端端删除了这一文件,客户端也相应删除,保持文件一致。

更多参数请查看rsync帮助:

$ /usr/bin/rsync -h

最后是问题总结

可能的报错信息:

@ERROR: auth failed on module renwole

此报错有两种原因导致:

1.要么在服务端配置的用户密码不正确导致。
2.要么就是服务器和客户端的密码文件不是600权限所致。

rsync: failed to connect to 10.28.204.65 (10.28.204.65): No route to host (113)
rsync error: error in socket IO (code 10) at clientserver.c(125) [Receiver=3.1.2]

此种无法连接到rsync服务端报错只有一种情况:

1.防火墙并未放行873端口或服务未启动,解决:关闭防火墙或放行端口即可。

启动如果报错,多看看日志,就知道解决的方法了。

如果你觉得配置比较麻烦,建议您使用lsyncd,此工具更好用,请参考:

如何使用Lsyncd复制并实时同步到远程服务器

Linux 常用快捷键记录

ctrl+a     # 光标移动到命令行首
ctrl+c     # 强制终止当前命令
ctrl+e     # 光标移动到命令行尾
ctrl+l     # 清屏
ctrl+u     # 从光标所在位置删除到行首
ctrl+r     # 从历史纪录中搜索命令
ctrl+s     # 挂起
ctrl+q     # 恢复挂起
ctrl+z     # 把命令放入后台

Nginx创建密码验证保护网站目录

在生产环境中,网站需要授权访问的场景非常之多,比如数据库管理工具:phpMyAdminMysqlUpBackUp等等。有时还需要一些私有目录文件的保护,为了实现这一伟大目标,我们就需要用到Nginx location匹配规则,下面将进行讲解。

1.创建htpasswd文件

$ vim /usr/local/nginx/conf/htpasswd

添加以下内容:
renwole:xEmWnqjTJipoE

此文件的书写格式是:

用户名:密码

注意:每行一个用户和密码,这里的password不是明文,而是将password进行crypt(3)加密后的字符串。

2.密码生成

可以打开以下网址输入用户信息进行密码生成:

//tool.oschina.net/htpasswd

3.Nginx加密目录配置

在Nginx虚拟主机配置文件中的合适区域加入以下内容:

如果保护tools目录:

location ^~ /tools/ {
auth_basic            "Restricted Area";
auth_basic_user_file  conf/htpasswd;
}

说明:若不加 ^~ 只能对目录进行弹窗验证,访问此目录下的文件则无需验证。

如果保护整个网站根目录:

location / {
auth_basic            "Restricted Area";
auth_basic_user_file  conf/htpasswd;
}

添加需要保护的目录后,重载Nginx配置文件,否则不生效。

Hyper-V虚拟主机Linux Centos 7数据磁盘扩容

一直以来对Hyper-V Linux虚拟主机的磁盘扩容困扰,今天将介绍如何利用 fdiskresize2fs 进行数据磁盘扩容。

情况说明:

宿主机系统:Windwos Server 2012 R2 Hyper-V
虚拟主机:CentOS Linux release 7.4.1708 (Core)

平时接触Hyper-V较多,所以对磁盘扩容那是常有的事。Windwos磁盘扩容最简单,本文就不多介绍了。
今天我将以Centos虚拟主机进行演示,该小机分为两块磁盘(都是独立磁盘),一块是系统盘/dev/sda,另一块是数据库盘/dev/sdb,现在的需求是sdb需要在不影响数据的情况下从原来的30GB扩容为100GB

1.扩容前先查看磁盘分区及挂载情况

[root@renwole-com ~]# fdisk -l

Disk /dev/sdb: 32.2 GB, 32212254720 bytes, 62914560 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disk label type: dos
Disk identifier: 0x5f149419

   Device Boot      Start         End      Blocks   Id  System
/dev/sdb1            2048    62914559    31456256   83  Linux

Disk /dev/sda: 10.7 GB, 10737418240 bytes, 20971520 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disk label type: dos
Disk identifier: 0x00043041

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048     2099199     1048576   83  Linux
/dev/sda2         2099200    20971519     9436160   8e  Linux LVM

Disk /dev/mapper/cl-root: 8585 MB, 8585740288 bytes, 16769024 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes


Disk /dev/mapper/cl-swap: 1073 MB, 1073741824 bytes, 2097152 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
[root@renwole-com ~]# df -hT
Filesystem          Type      Size  Used Avail Use% Mounted on
/dev/mapper/cl-root xfs       8.0G  950M  7.1G  12% /
devtmpfs            devtmpfs  1.9G     0  1.9G   0% /dev
tmpfs               tmpfs     1.9G     0  1.9G   0% /dev/shm
tmpfs               tmpfs     1.9G  8.3M  1.9G   1% /run
tmpfs               tmpfs     1.9G     0  1.9G   0% /sys/fs/cgroup
/dev/sda1           xfs      1014M  138M  877M  14% /boot
tmpfs               tmpfs     379M     0  379M   0% /run/user/0
/dev/sdb1           ext4       30G   60M   28G   1% /apps

注意:橙色部分 /dev/sdb1 分区大小是30GB,挂载的也是30GB

2.卸载挂载

删除 /etc/fstab 文件中以下开机磁盘自动挂载信息:

/dev/sdb1 /apps ext4 defaults 0 0

3.开始虚拟主机磁盘扩容

Hyper-V虚机操作:

打开Hyper-V 管理器,找到需要扩容的小机并关机,然后右击设置,点击需要扩容的磁盘,(一般是数据盘)编辑 – 默认下一步 – 选择扩展下一步,这一步骤需要注意,假设你原有磁盘为30G,那么你想扩展到100G,请填写100即可,点击下一步完成。然后启动虚拟主机。

查看扩容后的磁盘分区情况:

[root@renwole-com ~]# fdisk -l

Disk /dev/sda: 10.7 GB, 10737418240 bytes, 20971520 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disk label type: dos
Disk identifier: 0x00043041

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048     2099199     1048576   83  Linux
/dev/sda2         2099200    20971519     9436160   8e  Linux LVM

Disk /dev/sdb: 107.4 GB, 107374182400 bytes, 209715200 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disk label type: dos
Disk identifier: 0x5f149419

   Device Boot      Start         End      Blocks   Id  System
/dev/sdb1            2048    62914559    31456256   83  Linux

Disk /dev/mapper/cl-root: 8585 MB, 8585740288 bytes, 16769024 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes


Disk /dev/mapper/cl-swap: 1073 MB, 1073741824 bytes, 2097152 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes

sdb分区大小由原来的30GB扩展到100GB了,但分区sdb1并没有使用扩容的70GB空间,怎么办呢?

4.删除分区

删除分区不同等删除数据,删除分区再重建:

[root@renwole-com ~]# fdisk /dev/sdb

The device presents a logical sector size that is smaller than
the physical sector size. Aligning to a physical sector (or optimal
I/O) size boundary is recommended, or performance may be impacted.
Welcome to fdisk (util-linux 2.23.2).

Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.


Command (m for help): d                 # 删除sdb1分区
Selected partition 1
Partition 1 is deleted

Command (m for help): n			# 新建分区
Partition type:
   p   primary (0 primary, 0 extended, 4 free)
   e   extended
Select (default p): p
Partition number (1-4, default 1): 1	# 指定分区号
First sector (2048-209715199, default 2048):
Using default value 2048
Last sector, +sectors or +size{K,M,G} (2048-209715199, default 209715199):
Using default value 209715199
Partition 1 of type Linux and of size 100 GiB is set

Command (m for help): w                 # 输入w保存
The partition table has been altered!

Calling ioctl() to re-read partition table.
Syncing disks.

再次查看磁盘分区情况

[root@renwole-com ~]# fdisk -l
...
Disk /dev/sdb: 107.4 GB, 107374182400 bytes, 209715200 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disk label type: dos
Disk identifier: 0x5f149419

   Device Boot      Start         End      Blocks   Id  System
/dev/sdb1            2048   209715199   104856576   83  Linux
...

已经从原来的30G扩展成100G了,但现在还不能使用,需要进行如下操作才算真正扩容成功:

[root@renwole-com ~]# resize2fs -f /dev/sdb1
resize2fs 1.42.9 (28-Dec-2013)
Resizing the filesystem on /dev/sdb1 to 26214144 (4k) blocks.
The filesystem on /dev/sdb1 is now 26214144 blocks long.

扩容成功。

5.挂载磁盘

[root@renwole-com ~]# mount /dev/sdb1 /apps/
[root@renwole-com ~]# df -hT
Filesystem          Type      Size  Used Avail Use% Mounted on
/dev/mapper/cl-root xfs       8.0G  950M  7.1G  12% /
devtmpfs            devtmpfs  1.9G     0  1.9G   0% /dev
tmpfs               tmpfs     1.9G     0  1.9G   0% /dev/shm
tmpfs               tmpfs     1.9G  8.3M  1.9G   1% /run
tmpfs               tmpfs     1.9G     0  1.9G   0% /sys/fs/cgroup
/dev/sda1           xfs      1014M  138M  877M  14% /boot
tmpfs               tmpfs     379M     0  379M   0% /run/user/0
/dev/sdb1           ext4       99G   60M   94G   1% /apps
[root@renwole-com ~]# ls /apps/
web  mysql

如上所示,Linux虚拟主机数据盘已经成功扩容,查看数据并无丢失。

另外再次将你的磁盘信息写入到 /etc/fstab 文件中,不然重启后磁盘还需要手动挂载。

注意:还是那句话,操作任何数据之前,一定要先备份,养成良好的习惯,以防止数据丢失。

CentOS 7配置使用SFTP服务器

何为SFTP?

SFTP,即 SSH 文件传输协议( SSH File Transfer Protocol ),或者说是安全文件传输协议( Secure File Transfer Protocol )。SFTP 是一个独立的 SSH 封装协议包,通过安全连接以相似的方式工作。它的优势在于可以利用安全的连接传输文件,还能浏览本地和远程系统上的文件系统。

在很多情况下,SFTP都比FTP更可取,因为它具有最基本的安全特性和能利用 SSH 连接的能力,FTP是一种不安全的协议,只能在有限的情况下或在您信任的网络上使用。

先决条件:

服务器 OpenSSH-Server 版本最低4.8p1,因为配置权限需要版本添加的新配置项 ChrootDirectory 来完成。

如何查看OpenSSH版本,命令如下:

$ ssh -V
OpenSSH_6.6.1p1, OpenSSL 1.0.1e-fips 11 Feb 2013

1.创建用户信息

添加用户组:

$ groupadd sftp

添加用户:

$ useradd -g sftp -s /sbin/nologin -M userrenwolecom

参数注解:

-g              # 加入用户组
-s              # 指定用户登入后所使用的shell
/sbin/nologin   # 用户不允许登录
-M              # 不要自动建立用户的登入目录

设置用户密码:

$ passwd userrenwolecom

2.创建用户目录并设置权限

创建sftp主目录:

$ mkdir /data/sftp

设置sftp主目录权限:

$ chown root:sftp /data/sftp

文件夹所有者必须是root,用户组可以不是root。

$ chmod 744 /data/sftp

权限不能超过755但不包括755,否则会导致登录报错。

3.创建上传目录并设置权限

/data/sftp/主目录下创建uploads资料夹,并设置所有者是:userrenwolecom,用户组隶属:sftp,这样新增的帐号才能有上传编辑的权限。

$ mkdir -p /data/sftp/uploads
$ chown userrenwolecom:sftp /data/sftp/uploads

4.修改sshd_config配置文件

$ vim /etc/ssh/sshd_config

将此行注释掉,例如:

#Subsystem sftp /usr/libexec/openssh/sftp-server

在此行下面添加如下内容:

Subsystem sftp internal-sftp       # 指定使用sftp服务使用系统自带的internal-sftp
Match Group sftp                   # 匹配sftp组的用户,若要匹配多个组,可用逗号分开
ChrootDirectory /data/sftp/        # 限制用户的根目录
ForceCommand internal-sftp         # 只能用于sftp登录
AllowTcpForwarding no              # 禁止用户使用端口转发
X11Forwarding no                   # 禁止用户使用端口转发

5.重启SSH服务

$ systemctl restart sshd

6.测试是否能够登录、上传、下载等操作

10.28.204.61服务器执行以下命令登录:

$ sftp -P 12012 userrenwolecom@10.28.204.62
userrenwolecom@10.28.204.62's password:
packet_write_wait: Connection to 10.28.204.62 port 12012: Broken pipe
Couldn't read packet: Connection reset by peer

报错,此问题是由于/data/sftp 目录权限分配不当所致,将此目录的所有者更改为root即可,用户组可root/sftp

再次测试连接:

$ sftp -P 12012 userrenwolecom@10.28.204.62
The authenticity of host '[10.28.204.62]:12012 ([10.28.204.62]:12012)' 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
Warning: Permanently added '[10.28.204.62]:12012' (ECDSA) to the list of known hosts.
userrenwolecom@10.28.204.62's password:【输入userrenwolecom用户密码回车】
Connected to 10.28.204.62.
sftp>

连接成功,现在测试上传一个文件到10.28.204.62服务器

上传

sftp> put /tmp/nginx_log_stat /uploads
Uploading /tmp/nginx_log_stat to /uploads/nginx_log_stat
/tmp/nginx_log_stat

下载

sftp> get uploads/nginx_log_stat /mnt
Fetching /uploads/nginx_log_stat to /mnt/nginx_log_stat
/uploads/nginx_log_stat   100%    7   1.1KB/s   00:00
sftp>

删除

sftp> rm /uploads/nginx_log_stat
Removing /uploads/nginx_log_stat

更多命令请参阅:

sftp> help

小结:

在配置过程中遇到比较奇怪的问题,我将 sshd_config 配置文件中的 Match Group sftp 修改为 Match User userrenwolecom ,重启sshd后,当前终端不会断开,新建终端输入正确密码后会出现SSH登录闪退(自动关闭终端)问题,不管是用PUTTY还是Xshell均是如此,后来我将用户修改成组后就正常了,具体原因尚未可知,不过修改为组效果是一样的。如果你知道什么原因还请指教。

如何在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仓库的内容。