如何调整格式化为XFS文件系统的LVM分区大小

一、环境说明

如图示实例,红色箭头所指/usr空间已使用80%,对应的LVM分区为rootvg-usr。如何对rootvg-usr分区扩容?

图示实例中rootvg-usr所属的卷组为rootvg,尚有不到6GB的剩余可用空间用于扩容。

若PFree为0,如何对rootvg-usr扩容?

可通过缩减卷组rootvg下其他LVM分区大小(如rootvg-tivoli),腾出可用空间给rootvg-usr去扩容。

下面通过实验环境进行验证并给出具体操作步骤,实验环境如图示:

实验目标:缩减/tivoli空间大小(8GB->4GB),增加/usr空间大小(6GB->10GB)。

二、操作步骤

2.1缩减/tivoli空间大小(8GB->4GB)

2.1.1使用xfsdump备份/tivoli下数据

安装xfsdump:

# yum install xfsdump -y

备份数据到/app下:

# xfsdump -f /app/tivoli.dump /tivoli

提示输入label时不可忽略,过程如下:

xfsdump: using file dump (drive_simple) strategy

xfsdump: version 3.1.7 (dump format 3.0) – type ^C for status and control

 ============================= dump label dialog ==============================

please enter label for this dump session (timeout in 300 sec)

 -> tivolidump20210525

session label entered: “tivolidump20210525”

 ——————————— end dialog ———————————

xfsdump: level 0 dump of localhost.localdomain:/tivoli

xfsdump: dump date: Tue May 25 09:29:51 2021

xfsdump: session id: 50bd343c-6c09-4341-8ecc-434bea9d5006

xfsdump: session label: “tivolidump20210525”

xfsdump: ino map phase 1: constructing initial dump list

xfsdump: ino map phase 2: skipping (no pruning necessary)

xfsdump: ino map phase 3: skipping (only one dump stream)

xfsdump: ino map construction complete

xfsdump: estimated dump size: 19793664 bytes

xfsdump: /var/lib/xfsdump/inventory created

 ============================= media label dialog =============================

please enter label for media in drive 0 (timeout in 300 sec)

 -> tivolidump20210525

media label entered: “tivolidump20210525”

 ——————————— end dialog ———————————

xfsdump: creating dump session media file 0 (media 0, file 0)

xfsdump: dumping ino map

xfsdump: dumping directories

xfsdump: dumping non-directory files

xfsdump: ending media file

xfsdump: media file size 19584736 bytes

xfsdump: dump size (non-dir files) : 19409336 bytes

xfsdump: dump complete: 36 seconds elapsed

xfsdump: Dump Summary:

xfsdump:   stream 0 /app/tivoli.dump OK (success)

xfsdump: Dump Status: SUCCESS

[root@localhost /]#

2.1.2卸载分区

# umount /tivoli

2.1.3使用lvreduce收缩逻辑卷到所需的大小

# lvreduce -L 4G /dev/rootvg/tivoli

  WARNING: Reducing active logical volume to 4.00 GiB.

  THIS MAY DESTROY YOUR DATA (filesystem etc.)

Do you really want to reduce rootvg/tivoli? [y/n]: y

  Size of logical volume rootvg/tivoli changed from 8.00 GiB (2048 extents) to 4.00 GiB (1024 extents).

  Logical volume rootvg/tivoli successfully resized.

2.1.4使用xfs文件系统格式化分区

# mkfs.xfs -f /dev/rootvg/tivoli

meta-data=/dev/rootvg/tivoli     isize=512    agcount=4, agsize=262144 blks

         =                       sectsz=512   attr=2, projid32bit=1

         =                       crc=1        finobt=0, sparse=0

data     =                       bsize=4096   blocks=1048576, imaxpct=25

         =                       sunit=0      swidth=0 blks

naming   =version 2              bsize=4096   ascii-ci=0 ftype=1

log      =internal log           bsize=4096   blocks=2560, version=2

         =                       sectsz=512   sunit=0 blks, lazy-count=1

realtime =none                   extsz=4096   blocks=0, rtextents=0

2.1.5重新挂载分区

# mount /dev/rootvg/tivoli /tivoli

2.1.6使用xfsrestore恢复/tivoli下数据

# xfsrestore -f /app/tivoli.dump /tivoli

xfsrestore: using file dump (drive_simple) strategy

xfsrestore: version 3.1.7 (dump format 3.0) – type ^C for status and control

xfsrestore: searching media for dump

xfsrestore: examining media file 0

xfsrestore: dump description:

xfsrestore: hostname: localhost.localdomain

xfsrestore: mount point: /tivoli

xfsrestore: volume: /dev/mapper/rootvg-tivoli

xfsrestore: session time: Tue May 25 09:29:51 2021

xfsrestore: level: 0

xfsrestore: session label: “tivolidump20210525”

xfsrestore: media label: “tivolidump20210525”

xfsrestore: file system id: 91c5ee30-dd7e-4dbb-a336-6f3e77003f0b

xfsrestore: session id: 50bd343c-6c09-4341-8ecc-434bea9d5006

xfsrestore: media id: 81eef1ca-d96b-4701-86c1-08c8fb9c2cf6

xfsrestore: using online session inventory

xfsrestore: searching media for directory dump

xfsrestore: reading directories

xfsrestore: 84 directories and 235 entries processed

xfsrestore: directory post-processing

xfsrestore: restoring non-directory files

xfsrestore: restore complete: 0 seconds elapsed

xfsrestore: Restore Summary:

xfsrestore:   stream 0 /app/tivoli.dump OK (success)

xfsrestore: Restore Status: SUCCESS

2.1.7检查/tivoli下数据

# ls -l /tivoli

total 4

drwxr-xr-x. 7 1001 1001 4096 Jul 21  2020 zkui

经过上述操作,/tivoli空间已从8GB缩减到4GB。腾出4GB可用空间给rootvg-usr去扩容。

2.2增加/usr空间大小(6GB->10GB)

2.2.1使用lvextend增加逻辑卷到所需的大小

# lvextend -L +4G /dev/rootvg/usr -r

  Size of logical volume rootvg/usr changed from 6.00 GiB (1536 extents) to 10.00 GiB (2560 extents).

  Logical volume rootvg/usr successfully resized.

meta-data=/dev/mapper/rootvg-usr isize=512    agcount=4, agsize=393216 blks

         =                       sectsz=512   attr=2, projid32bit=1

         =                       crc=1        finobt=0 spinodes=0

data     =                       bsize=4096   blocks=1572864, imaxpct=25

         =                       sunit=0      swidth=0 blks

naming   =version 2              bsize=4096   ascii-ci=0 ftype=1

log      =internal               bsize=4096   blocks=2560, version=2

         =                       sectsz=512   sunit=0 blks, lazy-count=1

realtime =none                   extsz=4096   blocks=0, rtextents=0

data blocks changed from 1572864 to 2621440

2.2.2查看/usr空间大小

# df -Th /usr

Filesystem             Type  Size  Used Avail Use% Mounted on

/dev/mapper/rootvg-usr xfs    10G  1.5G  8.5G  16% /usr

发现/usr空间已从6GB增加到10GB。

分区调整后的空间如图示。

三、参考文章

3.1HOW TO REDUCE / SHRINK THE SIZE OF A LVM PARTITION FORMATTED WITH XFS FILESYSTEM?

https://yallalabs.com/linux/how-to-reduce-shrink-the-size-of-a-lvm-partition-formatted-with-xfs-filesystem/

3.2How to Extend a Logical Volume in LVM – for XFS, ext4 and swap filesystem

https://www.thegeeksearch.com/how-to-extend-a-logical-volume-in-lvm-for-xfs-ext4-and-swap-filesystem/

redhat 7.4下使用vsftpd搭建FTP服务器

环境版本

# cat /etc/redhat-release

Red Hat Enterprise Linux Server release 7.4 (Maipo)

# rpm -qa | grep vsftpd

vsftpd-3.0.2-22.el7.x86_64

1.安装并运行vsftpd

安装vsftpd:

# yum -y install vsftpd

启动服务:

# systemctl start vsftpd.service

设置开机自启:

# systemctl enable vsftpd.service

2.有关vsftpd默认设置及匿名访问FTP的说明

安装并运行vsftpd后,默认允许匿名用户访问并提供下载功能,但从安全性的角度考虑,匿名用户默认无法上传。

vsftpd中的匿名用户有两个:anonymous和ftp,在客户端可以用这两个匿名用户中的任意一个访问服务器。

vsftpd的默认主目录是/var/ftp,其中已有一个默认的子目录pub,可以把要共享的文件放在/var/ftp/pub目录中。

vsftpd的主配置文件是/etc/vsftpd/vsftpd.conf。

vsftpd的默认设置如下:

# egrep -v ‘^#|^$’ /etc/vsftpd/vsftpd.conf

anonymous_enable=YES

local_enable=YES

write_enable=YES

local_umask=022

dirmessage_enable=YES

xferlog_enable=YES

connect_from_port_20=YES

xferlog_std_format=YES

listen=NO

listen_ipv6=YES

pam_service_name=vsftpd

userlist_enable=YES

tcp_wrappers=YES

注:为避免干扰,关闭防火墙及禁用selinux

# systemctl stop firewalld && systemctl disable firewalld

# setenforce 0

# sed -i “s#SELINUX=enforcing#SELINUX=disabled#g” /etc/sysconfig/selinux

3.ftp需求及配置步骤

需求

ftpserver工作于被动模式,侦听端口:4200,ftp被动模式数据连接端口范围10300-10310,新建系统用户ftpuser1,ftpuser2用于ftp连接(用户只用于ftp连接,不能shell登录),新建目录/ftp用于ftp上传下载。

所有ftp用户都可以上传下载文件,并能更新删除ftp目录中的所有文件(自己上传的以及他人上传的)。

不允许匿名访问。

配置步骤如下:

3.1建立FTP目录/ftp及FTP账号ftpuser1,ftpuser2

建立FTP目录:

# mkdir /ftp

建立FTP账号(设置账号家目录为/ftp):

# useradd -d /ftp -s /sbin/nologin ftpuser1

# useradd -d /ftp -s /sbin/nologin ftpuser2

设置FTP账号密码(示例密码为password):

# echo password | passwd –stdin ftpuser1

# echo password | passwd –stdin ftpuser2

3.2备份默认配置文件:

mv /etc/vsftpd/vsftpd.conf /etc/vsftpd/vsftpd.conf.bak

3.3根据上述需求,新建配置文件,内容如下(配置项上一行标#为新增项或修改项,没标#为默认配置文件自带配置项):

# vi /etc/vsftpd/vsftpd.conf

#默认设置为YES,修改为NO,不允许匿名访问

anonymous_enable=NO

local_enable=YES

write_enable=YES

#默认设置为022,修改为000,确保所有ftp用户能更新删除ftp目录中的所有文件

local_umask=000

dirmessage_enable=YES

xferlog_enable=YES

connect_from_port_20=YES

xferlog_std_format=YES

listen=NO

listen_ipv6=YES

pam_service_name=vsftpd

userlist_enable=YES

tcp_wrappers=YES

#新增配置项,设置为NO,仅允许user_list列表中的用户账户登录

userlist_deny=NO

#新增配置项,让系统用户在登录FTP时也是访问FTP的主目录/ftp

local_root=/ftp

#新增配置项将用户禁锢在自己的家目录中

chroot_local_user=YES

#新增配置项

allow_writeable_chroot=YES

#新增配置项

listen_port=4200

#新增配置项

pasv_enable=YES

#新增配置项

pasv_min_port=10300

#新增配置项

pasv_max_port=10310

保存配置文件,并重启vsftpd服务:

# systemctl restart vsftpd

3.4在/etc/vsftpd/user_list文件中添加FTP账号ftpuser1 、ftpuser2

echo ftpuser1 >> /etc/vsftpd/user_list

echo ftpuser2 >> /etc/vsftpd/user_list

(同时注意检查/etc/vsftpd/ftpusers文件中不能存在FTP账号ftpuser1 、ftpuser2,否则FTP账号ftpuser1 、ftpuser2无法ftp连接。此文件中默认不会存在新建的账号)

3.5设置FTP目录权限

# setfacl -m u:ftpuser1:rwx /ftp

# setfacl -m u:ftpuser2:rwx /ftp

(不作此设置,ftpuser1、ftpuser2无法上传文件)

配置完毕,此时可使用ftp客户端进行ftp连接(端口:4200)

附录1:若需求中无此要求:ftpserver工作于被动模式,侦听端口:4200,ftp被动模式数据连接端口范围10300-10310。可以去掉如下配置项:

listen_port=4200

pasv_enable=YES

pasv_min_port=10300

pasv_max_port=10310

附录2:若需求中只需要使用一个FTP账号ftpuser1,则上述配置步骤可作如下调整(建议):

主要调整之处:

(1)local_umask无需设置为000,保持默认配置022即可:local_umask=022

(2)建FTP账号时,设置FTP账号的家目录为/ftp(前提是/ftp原先不存在):# useradd -d /ftp/ -s /sbin/nologin ftpuser1

(3)因(2)设置原因,无需作如下设置:setfacl -m u:ftpuser1:rwx /ftp

附录3:若需求中无此要求:所有ftp用户都能更新删除ftp目录中的所有文件(自己上传的以及他人上传的)。则上述配置步骤可作如下调整(建议):

主要调整之处:

(1)local_umask无需设置为000,保持默认配置022即可:local_umask=022

这样配置后,ftp用户只能更新删除自己上传的目录/文件,但可以查看下载所有文件。

附录4:若需要临时禁止ftpuse1或ftpuser2连接,user_list文件中注释或删除此账号即可。(无需重启vsftpd服务)

附录5:有关Chroot jail的说明

You may specify an explicit list of local users to chroot() to their home directory. If chroot_local_user is YES, then this list becomes a list of users to NOT chroot().

(Warning! chroot’ing can be very dangerous. If using chroot, make sure that the user does not have write access to the top level directory within the chroot)

chroot_local_user=YES

chroot_list_enable=YES

# (default follows)

chroot_list_file=/etc/vsftpd.chroot_list

设置之前,需手动添加vsftpd.chroot_list文件,此文件内存储ftp用户,其代表的含义根据chroot_local_user和chroot_list_enable不同而不同。

 chroot_local_user=YESchroot_local_user=NO
chroot_list_enable=YES仅允许vsftpd.chroot_list内用户离开默认目录仅拒绝vsftpd.chroot_list内用户离开默认目录,其他ftp用户可以访问其它目录
chroot_list_enable=NOvsftpd.chroot_list无效,拒绝所有ftp用户离开默认目录vsftpd.chroot_list无效,所有ftp用户均可访问其它目录

附录6:有关阻止用户登陆

可以通过如下设置阻止部分用户访问ftp服务器。

userlist_enable=YES

userlist_file=/etc/vsftpd.user_list

userlist_deny=NO

手动添加此三项到配置文件,同时创建vsftpd.user_list。与chroot jail配置参数相似,不同的设置导致不同的效果。

 userlist_deny=YESuserlist_deny=NO
userlist_enable=YES仅拒绝vsftpd.user_list内用户访问ftp仅允许vsftpd.user_list内用户访问ftp
userlist_enable=NOvsftpd.user_list无效vsftpd.user_list无效

Nginx版本升级

因低版本Nginx 1.10.3存在安全相关漏洞,现升级到当前最新稳定版本Nginx 1.16.1。

环境:

Red Hat Enterprise Linux Server release 7.4

Nginx 1.10.3 

升级步骤:

1. 查看并记录当前Nginx版本及编译参数

/app/nginx/sbin/nginx -V

2. 解压新版本Nginx 1.16.1并编译

tar xf nginx-1.16.1.tar.gz

cd nginx-1.16.1

./configure –without-http-cache –prefix=/app/nginx –sbin-path=/app/nginx/sbin/nginx –conf-path=/app/nginx/conf/nginx.conf –error-log-path=/app/nginx/log/error.log –http-log-path=/app/nginx/log/access.log –pid-path=/var/run/nginx.pid –lock-path=/var/run/nginx.lock –http-client-body-temp-path=/var/cache/nginx/client_temp –http-proxy-temp-path=/var/cache/nginx/proxy_temp –http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp –http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp –http-scgi-temp-path=/var/cache/nginx/scgi_temp –user=nginx –group=nginx –with-http_ssl_module –with-http_realip_module –with-http_addition_module –with-http_sub_module –with-http_dav_module –with-http_flv_module –with-http_mp4_module –with-http_gunzip_module –with-http_gzip_static_module –with-http_random_index_module –with-http_secure_link_module –with-http_stub_status_module –with-mail –with-mail_ssl_module –with-file-aio –with-ipv6 –with-cc-opt=’-O2 -g -pipe -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector –param=ssp-buffer-size=4 -m64 -mtune=generic’ –user=nginx –with-stream_ssl_module –with-http_realip_module –with-stream –with-http_auth_request_module –add-module=/app/headers-more-nginx-module-0.33

make

注:使用以前版本的编译参数,编译结束不要执行make install 安装。编译结束会在安装目录下生成一个objs目录且在该目录下有一个nginx执行文件。

3.替换旧的程序并重启

3.1备份旧的执行程序

mv /app/nginx/sbin/nginx /app/nginx/sbin/nginx.bak

3.2复制新的执行程序(使用objs目录下的nginx)

cp objs/nginx /app/nginx/sbin/

3.3使用新的执行程序检查nginx配置文件是否正常

/app/nginx/sbin/nginx -t

3.4平滑重启

Kill -USR2 `cat /path/nginx.pid`

kill -QUIT `cat /path/nginx.pid.oldbin`

注:上述path代表pid文件所在目录路径

3.5升级完成检查下nginx版本及编译参数

/app/nginx/sbin/nginx -V

至此Nginx版本升级完毕。

附录1:如何回滚到以前版本

将备份的nginx还原并重启即可,步骤如下:

mv -f /app/nginx/sbin/nginx.bak /app/nginx/sbin/nginx

/app/nginx/sbin/nginx -s reload


附录2:nginx支持的信号以及nginx升降级

以下几种是主进程可以接收的信号,注意worker进程也可以接收一些信号,但和主进程的信号处理机制有些不一样,且主进程支持的信号worker进程不一定支持。具体可见man nginx。

SIGINT, SIGTERM  立即杀掉nginx主(即所有进程)

SIGQUIT          graceful stop主进程

SIGWINCH         graceful stop所有的worker进程

SIGHUP           reload配置文件,并使老的worker进程graceful stop

SIGUSR1          重新打开日志文件(Reopen log files)

SIGUSR2          在线切换nginx可执行程序(Upgrade the nginx executable on the fly)
1. 升级

如果想对一个已运行的nginx实例进行版本升级,或者因为重新编译了一个版本而替换旧版本,可以考虑按照以下一系列过程来平稳、安全地升级。当然,如果直接停止服务不会产生多大影响,直接停掉再启动新版本nginx实例更方便简单。

(1)将新版本的nginx命令路径替换掉旧的nginx命令。

通常,对于编译安装的nginx来说,采用软链接的方式比较便捷。例如旧版本的安装路径为/usr/local/nginx-1.12.0,为其建立一个软链接/usr/local/nginx,如果有新版本/usr/local/nginx-1.12.1,只需修改软链接/usr/local/nginx的指向目标为/usr/local/nginx-1.12.1即可。这样/usr/local/nginx/sbin/nginx就会随着软链接的指向改变而指向新nginx程序。

(2)对旧nginx实例的主进程发送USR2信号。

kill -USR2 `cat /var/run/nginx/nginx.pid`

该信号提示nginx旧的主进程要升级,并执行新的nginx程序。例如步骤1中,旧的nginx主进程为/usr/local/nginx/sbin/nginx,但其指向的是/usr/local/nginx-1.12.0/sbin/nginx,发送该信号后仍将执行/usr/local/nginx/sbin/nginx,但此时因为软链接目标已改变,使得此时启动的nginx已经是/usr/local/nginx-1.12.1/sbin/nginx程序。

 此外,发送该信号后将会切换pid文件,旧的pid文件被重命名为nginx.pid.oldbin,记录的是旧的nginx主进程pid值,新的pid文件为nginx.pid,记录的是新启动的nginx的主进程pid值。

# ls /var/run/nginx*     

/var/run/nginx.pid  /var/run/nginx.pid.oldbin

(3)graceful stop旧的主进程号。

kill -QUIT `cat /var/run/nginx/nginx.pid.oldbin`

向旧的主进程号发送QUIT信号,该信号将使得主进程以graceful的方式关闭。这将使得旧的主进程、旧的worker进程不再接受任何新请求,但却会把正在处理过程中的请求处理完毕,然后被销毁退出。

(4)更稳妥的方式是先让worker进程graceful stop,在新版本的nginx实例运行一小段时间后如果正常工作,再graceful stop旧的主进程。

kill -WINCH `cat /var/run/nginx/nginx.pid.oldbin` 

# a periodoftime goes, graceful stopoldmaster nginx

kill -QUIT `cat /var/run/nginx/nginx.pid.oldbin`

在发送WINCH信号给旧的主进程后,旧的worker进程将逐渐退出,但旧的主进程却会保留不退出。

如果发现新版本的nginx实例不满意,可以直接向旧主进程号发送HUP信号,这样旧的主进程就会重新读取配置文件并fork新的worker进程,再将新的主进程号杀掉(可以graceful stop),就可以还原为旧版本的nginx实例。

2.降级

上面第4步其实就是最安全的降级方式。即:

kill -HUP `cat /var/run/nginx/nginx.pid.oldbin`

kill -QUIT `cat /var/run/nginx/nginx.pid`

但如果旧的主进程号已经被杀掉了,目前只有新版本的nginx实例在运行,那么只需以升级的步骤进行降级即可。即:

kill -USR2 `cat /var/run/nginx/nginx.pid`

kill -QUIT `cat /var/run/nginx/nginx.pid.oldbin`

VMware_ESX Server常用命令

1.查看esx版本

vmware –v

2.查看显示ESX硬件,内核,存储,网络等信息

esxcfg-info -a (显示所有相关的信息)

esxcfg-info -w (显示esx上硬件信息)

3.列出esx里知道的服务

esxcfg-firewall –s

4.查看具体服务的情况

esxcfg-firewall -q sshclinet

5.重新启动vmware服务

service mgmt-vmware restart

6.修改root的密码

passwd root

7.设置kernel高级选项

esxcfg-advcfg -d (将系统内核恢复默认值)

8.管理资源组

esxcfg-resgrp -l (显示所有资源组)

9.列出你当前的虚拟交换机

esxcfg-vswitch -l

esxcfg-vswitch -v 10 -p “Service Console” vSwitch0 (将vSwitch0上的Service Console划分到vLan 10上,如果vLan号为0则不设置vLan)

10.查看控制台的设置

esxcfg-vswif -l   (列出已添加的网卡)

esxcfg-vswif -a (添加网卡)

11.列出系统的网卡

esxcfg-nics –l

12.添加一个虚拟交换机,名字叫(internal)连接到两块物理网卡,(重新启动服务,vi就能看见了)

esxcfg-vswitch -a vSwitch1

esxcfg-vswitch -A internal vSwitch1

esxcfg-vswitch -L vmnic1 vSwitch1

esxcfg-vswitch -L vmnic2 vSwitch1

13.删除交换机,(注意,别把控制台的交换机也删了)

esxcfg-vswitch -D vSwitch1

14.删除交换机上的网卡

esxcfg-vswitch -u vmnic1 vswitch2

15.删除portgroup

esxcfg-vswitch -D internel vswitch1

16.创建 vmkernel switch ,如果你希望使用vmotion,iscsi的这些功能,你必须创建( 通常是不需要添加网关的)

esxcfg-vswitch -l

esxcfg-vswitch -a vswitch2

esxcfg-vswitch -A “vm kernel” vswitch2

esxcfg-vswitch -L vmnic3 vswitch2

esxcfg-vmknic -a “vm kernel” -i 172.16.1.141 -n 255.255.252.0 (添加一个vmkernel)

17.防火墙设置esxcfg-firewall -e sshclient (打开防火墙ssh端口)

esxcfg-firewall -d sshclient (关闭防火墙ssh端口)

esxcfg-firewall -e veritasNetBackup (允许Veritas Netbackup服务)

esxcfg-firewall -o 123,udp,out,ntp (为ntp服务打开UDP协议中的123端口的输出)

18.路由管理

esxcfg-route (VM生成网卡的路由管理)

esxcfg-route(显示路由表)

esxcfg-route 172.16.0.254 (设置vmkernel网关)

19.创建控制台

esxcfg-vswitch -a vSwitch0

esxcfg-vswitch -A “service console” vSwitch0

esxcfg-vswitch -L vmnic0 vSwitch0

esxcfg-vswif -a vswif0 -p “service console” -i 172.16.1.140 -n 255.255.252.0

20.添加nas设备(a 添加标签,-o,是nas服务器的名字或ip,-s 是nas输入的共享名字)

esxcfg-nas -a isos -o nas.vmwar.cn -s isos

21.nas连接管理

esxcfg-nas -r (强迫esx去连接nas服务器)

esxcfg-nas -l    (用esxcfg-nas -l 来看看结果)

esxcfg-nas -a(添加NAS文件系统到/vmfs目录下)

esxcfg-nas -d (删除NAS文件系统)

22.扫描SCSI设备上的LUN信息

esxcfg-rescan <vmkernel SCSI adapter name>

23.连接iscsi 设备(e:enable q:查询 d, disable s:强迫搜索)

esxcfg-swiscsi -e

24.设置targetip

vmkiscsi-tool -D -a 172.16.1.133 vmhba40

25.列出和target的连接

vmkiscsi-tool -l -T vmhba40

26.列出当前的磁盘

ls -l /vmfs/devices/disks

27.内核dump管理工具

esxcfg-dumppart -l (显示当前dump分区配置信息)

28.路径管理

esxcfg-mpath -l (显示所有路径)

esxcfg-mpath -a (显示所有HBA卡)

29.ESX授权管理配置

esxcfg-authesxcfg-auth –enablenis (运行NIS验证)

30.管理启动设备

esxcfg-bootesxcfg-boot -b (更新启动设备)

31.执行initrd的初始化设置

esxcfg-initesxcfg-init (初始化设备)

32.esxcfg-linuxnet (在linux debug模式中,转换vswif设备命名为linux自带的eth命名规则)

esxcfg-linuxnet –setup

33.升级

esxcfg-upgrade (ESX2.X升级到ESX3.X)

删除文件的空白行

空白行分两类:

1.整个行什么都没有,用正则表达式表示是/^$/。

2.有空格而没有字符,用正则表达式表示是/^\s\+$/。

两个通用的正则表达式是/^\s\*$/。

删除1的命令如下。命令:/^$/d           

### 注释:前面的^指行首$指行尾,最后的d指删除的意思。

删除2的命令如下。命令:/^\s\+$/d             

### 注释:\s\+指1~无穷大个空格,给+加反斜杠是为了转义。

同时删除1、2的命令如下。命令:/^\s\*/d           

### 注释:\s\* 指0~无穷大个空格,给*加反斜杠是为了转义。

示例:

删1的命令:     sed -i ‘/^$/d’ test.txt

删2的命令:     sed -i ‘/^\s\+$/d’ test.txt

删1、2的命令:sed -i ‘/^\s*$/d’ test.txt

CentOS7.4设置NFS

说明:操作系统版本不同,设置步骤可能有所差异,文档仅供参考。

环境:

ROLEIPOS
NFS server 192.168.188.199最小化安装RHEL7.4
NFS client192.168.188.207最小化安装RHEL7.4

步骤:

一、NFS服务器端设置(192.168.188.199)

1.1安装nfs-utils:

yum install nfs-utils

1.2创建NFS共享目录:

mkdir /var/nfsshare

1.3设置NFS共享目录权限:

chmod -R 755 /var/nfsshare
chown nfsnobody:nfsnobody /var/nfsshare

1.4设置并启动nfs服务:

systemctl enable nfs-server

systemctl start nfs-server

1.5NFS共享配置:

vi /etc/exports,添加如下配置:

/var/nfsshare    192.168.188.207(rw,all_squash)

设置完毕保存,运行exportfs -rv重新加载配置。

1.6防火墙设置:

firewall-cmd –permanent –zone=public –add-service=nfs

firewall-cmd –reload

至此NFS服务器设置完毕。

二、NFS客户端设置( 192.168.188.207)

2.1安装nfs-utils:

yum install nfs-utils

2.2创建NFS目录挂载点:

mkdir -p /mnt/nfs/var/nfsshare

2.3挂载NFS目录:

mount -t nfs 192.168.188.199:/var/nfsshare /mnt/nfs/var/nfsshare/

2.4检查并测试:

df -h

touch /mnt/nfs/var/nfsshare/test_nfs

三、客户端自动挂载NFS目录

可编辑fstab实现自动挂载:

vi /etc/fstab,添加如下配置:

192.168.188.199:/var/nfsshare    /mnt/nfs/var/nfsshare   nfs defaults 0 0

设置完毕保存即可。

附录1:服务器端常用命令

1.Show the NFS server’s export list:

# showmount -e 192.168.188.199

Export list for 192.168.188.199:

/var/nfsshare 192.168.188.207

2.Show current export list and options:

# exportfs -v

/var/nfsshare 192.168.188.207(rw,sync,wdelay,hide,no_subtree_check,sec=sys,secure,root_squash,all_squash)

3.停止共享:exportfs -av -u

重新共享:exportfs -av或exportfs -rv

附录2:NFS参考文档

1.https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/storage_administration_guide/ch-nfs

2.https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/storage_administration_guide/nfs-serverconfig

3.http://linux-nfs.org/wiki/index.php/Main_Page

脚本_监视主机磁盘使用情况

需求:

使用脚本监视网络中多台主机磁盘使用情况,如使用率超过80%,标记为ALERT,否则标记为SAFE。

实施:

设置一个共用账户(如monitor),用于脚本登录多台主机使用,并为这个共用账户配置SSH自动登录。

示例脚本内容如下:

#!/bin/bash

#filename:diskusage.sh

#function:monitor disk usage

logfile=”diskusage.log”

if [[ -n $1 ]]

then

 logfile=$1

fi

if [ ! -e $logfile ]

then

 printf “%-8s %-14s %-8s %-8s %-6s %-6s %-6s %s\n” “Date” “IP address” “Device” “Capacity” “Used” “Free” “Percent” “Status” > $logfile

fi

IP_LIST=”172.16.0.120 172.16.0.121″

(

for ip in $IP_LIST;

do

 ssh monitor@$ip ‘df -H’ | grep ^/dev/ > /tmp/$$.df

 while read line;

 do

  cur_date=$(date +%D)

  printf “%-8s %-14s” $cur_date $ip

  echo $line | awk ‘{ printf(“%-9s %-8s %-6s %-6s %-8s”,$1,$2,$3,$4,$5); }’

 pusg=$(echo $line | egrep -o “[0-9]+%”)

  pusg=${pusg/\%/};

  if [ $pusg -lt 80 ];

  then

   echo SAFE

  else

   echo ALERT

  fi

  done < /tmp/$$.df

done

) >> $logfile

脚本运行效果:

说明:

1.脚本也可以提供日志文件路径作为命令行参数,否则脚本使用默认的日志文件diskusage.log,如:

./diskusage.sh logfilename

2.可用crontab定时执行脚本,如每天上午9点运行脚本:

00 09 * * * /path/diskusage.sh

3.示例脚本并未删除临时文件$$.df,若要删除,可在脚本末尾添加rm -rf $$.df

4.示例脚本中只列出两台主机172.16.0.120、172.16.0.121 ,可根据实际情况作相关调整。

脚本_从网页上抓取并下载图片

需求:

从网页上抓取并下载图片

脚本内容如下:

#!/bin/bash

#filename:img_donwloader.sh

#function:download picture file

if [ $# -ne 3 ];

then

 echo “usage: $0 URL -d DIRECTORY”

 exit -1

fi

for i in {1..4}

do

 case $1 in

 -d) shift; directory=$1; shift;;

 *) url=${url:-$1}; shift;;

esac

done

mkdir -p $directory

baseurl=$(echo $url | egrep -o “https?://[a-z.]+”)

curl -s $url | egrep -o “<img src=[^>]*>” |

sed ‘s/<img src=\”\([^”]*\).*/\1/g’ > /tmp/$$.list

sed -i “s|^/|$baseurl/|” /tmp/$$.list

cd $directory;

while read filename;

do

 curl -s -O “$filename” –silent

done < /tmp/$$.list

使用方法:

./img_downloader.sh URL -d DIR

示例:

./img_downloader.sh http://www.betterit360.com/?p=171 -d images

查看下载的图片文件:

ll images

某电商APP 项目安全框架方案 (草稿)

一、方案简介

某电商APP系统目前部署在阿里云平台系统上,使用了阿里云平台系统的基础设施。

安全防护一般涉及如下方面:物理安全、网络安全、主机安全、应用安全、数据安全。

除了上述安全技术防护外,安全管理亦不容忽视,大的分类一般涉及:安全管理制度、安全管理机构、人员安全管理、系统建设管理、系统运维管理。

可以通过自有力量或委托第三方专业安全评测机构定期对系统进行测评,对测评过程中发现的主要安全问题进行处置。

二、方案详述

2.1安全防护需要考虑的层面及控制点

上述简介中提及的安全技术/安全管理分类一般涉及到如下安全控制点,需要对这些点分别作测评,具体操作可参考相关国标、行业规范、以及最佳实践。

安全层面安全控制点
物理安全物理位置的选择
物理访问控制
防盗窃和防破坏
防雷击
防火
防水和防潮
防静电
温湿度控制
电力供应
电磁防护
网络安全结构安全
访问控制
边界完整性检查
入侵防范
恶意代码防护
安全审计
网络设备防护
主机安全访问控制
入侵防范
恶意代码防范
资源控制
身份鉴别
安全审计
剩余信息保护
应用安全身份鉴别
访问控制
安全审计
剩余信息保护
资源控制
通信完整性
通信保密性
抗抵赖
软件容错
安全管理制度管理制度
制度和发布
评审和修订
安全管理机构岗位设置
人员配备
授权和审批
沟通和合作
审核和检查
人员安全管理人员录用
人员离岗
人员考核
安全意识教育和培训
外部人员访问管理
系统建设管理系统定级
安全方案设计
产品采购和使用
自行软件开发
外包软件开发
工程实施
测试验收
系统交付
系统备案
等级测评
安全服务商选择
系统运维管理环境管理
资产管理
介质管理
设备管理
监控管理和安全管理中心
网络安全管理
系统安全管理
恶意代码防范管理
密码管理
变更管理
备份与恢复管理
安全事件处置
应急预案管理

说明:鉴于信息系统的复杂性和特殊性,上述某些安全控制点及相关要求可能不适用于所有信息系统,应对其做必要的梳理、裁剪或补充(参见:四、互联网应用安全)。

2.2系统安全测试方式及要点

信息系统安全测评的方式主要有访谈、核查、测试及综合风险分析。现对其要点简述如下:

访谈:应注意广度和深度,广度上访谈应覆盖不同类型的人员,包括系统负责人、开发人员、系统管理人员等。深度上访谈应包含通用和高级的问题以及一些有难度和探索性的问题。

核查:包括文档核查及配置核查。

测试:包括案例验证测试、漏洞扫描测试、渗透测试。

风险分析方法:根据安全事件可能性和安全事件后果对系统面临的风险进行分析。

2.3对标阿里云产品及服务选型

上述安全控制点及相关要求对标阿里云产品及服务,建议的选型如下:

阿里云产品/服务功能说明
态势感知
(企业版)
安全事件分析:发生安全事件后,通过日志证据进行调查,评估资产受损范围和影响
操作审计:对主机服务器的操作日志进行审计,对高危操作和严重问题进行细粒度排查
业务流量统计:对web访问日志进行统计和分析,追踪来访者的环境和状态,对业务和服务响应进行筛选
安骑士
(企业版)
入侵防御以及病毒防控功能。
云堡垒机
(企业版)
对所有设备进行集中管理,具有三员管理机制,对管理人员行为进行审核。支持令牌
数据库审计数据库安全审计
高防IP1、包括但不限于以下攻击类型 ICMP Flood、UDP Flood、TCP Flood、SYN Flood、ACK Flood、CC攻击等;
2、DDoS防护服务可随时更换防护的IP,自由配置 高级别防护;
3、DDoS防护阈值弹性调整,随时升级更高级别的防护,整个过程服务无中断;
4、提供实时精准的流量报表及攻击详情,及时准确获得当前服务详情;
Web应用
防火墙
应用攻击防护:强大的内置防护规则可以防护诸如SQL注入,XSS跨站脚本,远程文件包含、木马上传隔离以及其他OWASP的Top威胁攻击,支持HTTP/HTTPS应用接入;
精准防护:根据网站实际防护场景需求,实现HTTP/HTTPS的常见字段的细粒度访问控制,过滤针对网站的恶意流量;支持IP、URL、Referer、User-Agent等HTTP常见字段的自定义防护规则匹配,可支持盗链防护、网站后台保护等防护场景;
CC攻击防护:充分利用阿里云大数据安全优势、建立威胁情报与可信访问分析模型、快速识别恶意流量;多种防护算法结合防御、包括对单一源IP的访问频率控制、重定向跳转验证、人机识别等;针对海量慢速请求攻击、采用高级防护算法、统计响应码、URL请求分布、异常Referer及User-Agent特征识别,可结合精准防护进行综合防护;
业务风控:实时解决垃圾注册、刷库撞库、活动作弊、论坛灌水等严重业务风险,无需网站修改源码/调用API接口等繁琐操作即可实现快速上线防护;
快速更新:在云盾的安全专家发现了新型的漏洞威胁后,能够立刻将对应的安全补丁同步到云盾Web应用防火墙中,保障您的网站业务不被侵害受损;

三、方案可借鉴的最佳实践

3.1安全不能停留在制度上。

3.2预防为主、持续改进。

3.3安全方案的设计通常应遵循以下原则:(1)木桶原则:木桶的最大容积取决于最短的一块木板;(2)整体性原则:综合考虑安全防护、监测和应急恢复;(3)有效性与实用性原则:不能影响系统的正常运行和合法用户的操作;(4)等级性原则:区分安全层次和安全级别,包括对信息保密程度分级、对用户操作权限分级、对信息系统安全程度分级、对系统实现结构的分级等;(5)动态化原则:安全只是相对的和暂时的。

四、互联网应用安全

互联网应用不同于传统应用,突出表现在以下两点:(1)用户群体、使用时间、使用习惯存在不确定性;(2)应用更新迭代频繁。

一个百万用户量级以上的互联网应用,其很多问题已经不能就事论事来研究和解决,需要系统性的方法和战略性的眼光。

基于上述特点,互联网应用必须做顶层规划和详细设计,从安全角度出发,每个层面需考虑和解决三高问题:高可用、高性能、高扩展。

高可用架构一般表现在以下几方面:冗余备份、失效转移、模块解耦、降级限流、异步处理、异地多活、自动化运维。

高性能一般表现在以下两个方面:时间性能(系统执行的时间)和空间性能(系统占用的空间)。提高性能通常从代码优化、工具优化、系统优化三个方面入手。

高扩展:分垂直扩展和水平扩展,互联网应用系统一定要能水平扩展。

上述三高涉及许多技术及细节,不能生搬硬套,需要基于业务需求做架构设计、数据设计、实现细节详细设计。

五、安全工作如何落地

前面提及更多的是理论,如何落地需要智慧,如技术实现维度场景、一题多解场景、跨时间轴的场景、风险和影响的平衡等。不同发展阶段的安全建设应有所区别,举例如下:

5.1中小型(初创期):保障最基本的部分,追求最高性价比,不求大而全。映射到技术实现,具体工作如下:

  • 基本的补丁管理
  • 漏洞管理
  • L3-L7的基本的访问控制
  • 没有弱密码,管好密码。
  • 账号认证鉴权不求各种基于条件的实时风控,但求基本功能到位。
  • 参考开发语言的安全编程规范
  • 参考系统加固最佳实践文档

以上工作部分可以借助于云平台提供的安全能力,或者第三方安全厂商提供的安全能力。

5.2大中型(发展、成熟期):典型特征是业务营收的持续性需要安全来保障,配备专职安全人员或安全团队,具备初步的纵深防御能力。映射到技术实现,具体工作如下:

  • L2-L7中的每一层拥有完整的安全设计。
  • 对所有的服务器、PC终端、移动设备,具有统一集中的状态感知、安全检测及防护能力。
  • 应用层面细粒度控制
  • 全流量入侵检测能力
  • 无死角1天漏洞发现能力
  • 在安全等级较高的区域建立纵深防御和一定的0天发现能力
  • 初具规模的安全专职团队
  • 对应用交付有自主的评估和修补能力
  • 从IT服务层面建立必要的流程、业务持续性以及风控应急措施。
  • 对业务安全形成自己的风控及安全管理方法论
  • 将难以自己实现的部分外包

这个层级的安全需求有些难以具体量化。

根据经验,企业在安全方面的预算,应该等分成三部分(根据实际情况和不同阶段动态调整):1/3投入到外部情报收集,包括众测和SRC的建设;1/3投入到安全感知系统建设,只有先看到,才能实施有效防御;1/3投入到防御系统的建设。第一个1/3可以理解为红军,第二个1/3和第三个1/3可以理解为蓝军。加强蓝军自身的安全能力,并通过红军来验证自身安全能力的强弱和可靠性,基于上述思路,风险就逐渐收敛了。

Set Up and Configure an OpenVPN Server on CentOS 7

Installing OpenVPN

# yum install epel-release

# yum install openvpn

Building CA with EasyRSA

# cd /usr/local/src

# wget https://github.com/OpenVPN/easy-rsa/releases/download/v3.0.5/EasyRSA-nix-3.0.5.tgz

# tar xzf EasyRSA-nix-3.0.5.tgz -C /usr/local

# cd /usr/local/EasyRSA-3.0.5/

# cp vars.example vars

uncomment and update the following entries to match your information:

# vi vars

set_var EASYRSA_REQ_COUNTRY    “CN”

set_var EASYRSA_REQ_PROVINCE   “Jiangsu”

set_var EASYRSA_REQ_CITY       “Suzhou”

set_var EASYRSA_REQ_ORG        “Betterit”

set_var EASYRSA_REQ_EMAIL      “admin@betterit.info”

set_var EASYRSA_REQ_OU         “IT”

Save and close the file.

Before generating a CA keypair first we need to initialize a new PKI with:

# ./easyrsa init-pki

The next step is to build the CA:

# ./easyrsa build-ca

You’ll be asked to set a password for the CA key and enter a common name for your CA.

Once completed, the script will create two files — CA public certificate ca.crt and CA private key ca.key.

Now that the Certificate Authority (CA) is created, you can use it to sign certificate requests for one or multiple OpenVPN servers and clients.

Note:If you don’t want to be prompted for a password each time you sign your certificates, run the build-ca command using the nopass option: ./easyrsa build-ca nopass.

Creating Diffie-Hellman and HMAC keys

[root@iZbp16cdvzk4ribfwjca03Z EasyRSA-3.0.5]# ./easyrsa gen-dh

Note: using Easy-RSA configuration from: ./vars

Using SSL: openssl OpenSSL 1.0.2k-fips  26 Jan 2017

Generating DH parameters, 2048 bit long safe prime, generator 2

This is going to take a long time

……………………………………………………..+………………………..

……………………….+………………….+…………………………………………………………………………………….++*++*

DH parameters of size 2048 created at /usr/local/EasyRSA-3.0.5/pki/dh.pem

[root@iZbp16cdvzk4ribfwjca03Z EasyRSA-3.0.5]#

Copy the dh.pem file to the /etc/openvpn directory:

# cp pki/dh.pem /etc/openvpn/

generate a HMAC signature using the openvpn binary:

# openvpn –genkey –secret ta.key

Once completed copy the ta.key file to the /etc/openvpn directory:

# cp ta.key /etc/openvpn/

Creating Server Certificate and Private Key

./easyrsa gen-req vpnsvr01 nopass

We are using the nopass argument because we want to start the OpenVPN server without a password input. Also in this example, we are using vpnsvr01 as a server name (entity) identifier. If you choose a different name for your server don’t forget to adjust the instructions below where the server name is used.

The command will create two files, a private key (vpnsvr01.key) and a certificate request file (vpnsvr01.req).

Copy the private key to the /etc/openvpn directory:

# cp pki/private/vpnsvr01.key /etc/openvpn/

run the following command to sign the request:

./easyrsa sign-req server vpnsvr01

The first argument can either be server or client and the second one is the server short (entity) name.

# cp pki/ca.crt /etc/openvpn/

# cp pki/issued/vpnsvr01.crt /etc/openvpn/

Upon completing the steps outlined in this section, you should have the following new files on your OpenVPN server:

/etc/openvpn/ca.crt

/etc/openvpn/dh.pem

/etc/openvpn/ta.key

/etc/openvpn/vpnsvr01.crt

/etc/openvpn/vpnsvr01.key

Configuring the OpenVPN Service

We will use the sample configuration file provided with OpenVPN installation package as a starting point and then add our own custom configuration options to it.

# cp /usr/share/doc/openvpn-*/sample/sample-config-files/server.conf /etc/openvpn/vpnsvr01.conf

Open the file and Find the Certificate, Key and DH parameters directives and change the file names:

# vi /etc/openvpn/vpnsvr01.conf

cert vpnsvr01.crt

key vpnsvr01.key

dh dh.pem

To redirect the clients traffic through the VPN find and uncomment the redirect-gateway and dhcp-option options:

push “redirect-gateway def1 bypass-dhcp”

push “dhcp-option DNS 208.67.222.222”

push “dhcp-option DNS 208.67.220.220”

By default OpenDNS resolvers are used. You can change it and use Google or any other DNS resolvers you want.

Find the user and group directives and uncomment these settings by removing the “;” at the beginning of each line:

user nobody

group nogroup

Append the following line at the end of the file. This directive will change the message authentication algorithm (HMAC) from SHA1 to SHA256

auth SHA256

Once you are done, the server configuration file (excluding comments) should look something like this:

port 1194

proto udp

dev tun

ca ca.crt

cert vpnsvr01.crt

key vpnsvr01.key  # This file should be kept secret

dh dh.pem

server 10.8.0.0 255.255.255.0

ifconfig-pool-persist ipp.txt

push “dhcp-option DNS 208.67.222.222”

push “dhcp-option DNS 208.67.220.220”

keepalive 10 120

tls-auth ta.key 0 # This file is secret

cipher AES-256-CBC

user nobody

group nobody

persist-key

persist-tun

status openvpn-status.log

verb 3

explicit-exit-notify 1

auth SHA256

Starting OpenVPN Service

# systemctl start openvpn@vpnsvr01

Verify whether the service has started successfully by typing:

# systemctl status openvpn@vpnsvr01

Enable the service to automatically start on boot with:

# systemctl enable openvpn@vpnsvr01

When starting, the OpenVPN Server creates a tun device tun0. To check if the device is available, type:

# ip a show tun0

Firewall and Server Networking Configuration

In order to forward network packets properly, we need to enable IP forwarding.

Open the /etc/sysctl.conf file and add the following line:

net.ipv4.ip_forward = 1

Apply the new settings by running the following command:

sysctl -p

Now we need to add firewall rules open OpenVPN port and to enable masquerading.

Start by adding the tun0 interface to the trusted zone:

firewall-cmd –permanent –zone=trusted –add-interface=tun0

Open the default openvpn port 1194 by adding the openvpn service to the list of services allowed by firewalld :

firewall-cmd –permanent –add-service openvpn

Set IP masquerading on trusted zone:

firewall-cmd –permanent –zone=trusted –add-masquerade

Before adding the nat rule you need to know the public network interface of your CentOS OpenVPN Server. You can easily find the interface by running the following command:

ip -o -4 route show to default | awk ‘{print $5}’

In our case, the interface is named eth0 as shown on the output below. Your interface may have a different name.

The following command will allow the traffic to leave the VPN, giving your VPN clients access to the Internet. Don’t forget to replace eth0 to match the name of public network interface you found in the previous command.

firewall-cmd –permanent –direct –passthrough ipv4 -t nat -A POSTROUTING -s  10.8.0.0/24 -o eth0 -j MASQUERADE

Finally reload the firewall rules for changes to take effect:

firewall-cmd –reload

Creating the Client Configuration Infrastructure

The whole process of generating the client certificate and configuration file is as follows:

  1. Generate a private key and certificate request on the OpenVPN server.
  2. Send the request to the CA machine to be signed.
  3. Copy the signed SSL certificate to the OpenVPN server and generate a configuration file.
  4. Send the configuration file to the VPN client’s machine.

Start by creating a set of directories to store the clients files:

# cd /etc/openvpn

# mkdir -p openvpn-clients/{configs,base,files}

  • base directory will store the base files and configuration that will be shared across all client files.
  • configs directory will store the generated client configuration.
  • files directory will store client-specific certificate/key pair.

Copy the ca.crt and ta.key files to the openvpn-clients/base directory:

# cp ta.key openvpn-clients/base

# cp ca.crt openvpn-clients/base

Next copy the sample VPN client configuration file into the client-~/openvpn-clients/base directory. We will use this file as a base configuration:

# cp /usr/share/doc/openvpn-*/sample/sample-config-files/client.conf openvpn-clients/base

Now we need to edit the file to match our server settings and configuration.

# vi openvpn-clients/base/client.conf

Find the remote directive and change the default placeholder with the public IP address of your OpenVPN server:

# The hostname/IP and port of the server.

# You can have multiple remote entries

# to load balance between the servers.

remote YOUR_SERVER_IP 1194

Locate and comment the ca, cert, and key directives. The certs and keys will be added within the configuration file:

# SSL/TLS parms.

# See the server config file for more

# description.  It’s best to use

# a separate .crt/.key file pair

# for each client.  A single ca

# file can be used for all clients.

# ca ca.crt

# cert client.crt

# key client.key

Append the following lines at the end of the file to match the server settings:

auth SHA256

key-direction 1

Once you are done, the server configuration file should look something like this:

client

dev tun

proto udp

remote 118.31.38.47 1194

resolv-retry infinite

nobind

persist-key

persist-tun

remote-cert-tls server

tls-auth ta.key 1

cipher AES-256-CBC

verb 3

auth SHA256

key-direction 1

Next, create a simple bash script that will merge the base configuration and files with the client certificate and key, and store the generated configuration in the openvpn-clients/configs directory.

vi openvpn-clients/gen_config.sh

#!/bin/bash

FILES_DIR=/etc/openvpn/openvpn-clients/files

BASE_DIR=/etc/openvpn/openvpn-clients/base

CONFIGS_DIR=/etc/openvpn/openvpn-clients/configs

BASE_CONF=${BASE_DIR}/client.conf

CA_FILE=${BASE_DIR}/ca.crt

TA_FILE=${BASE_DIR}/ta.key

CLIENT_CERT=${FILES_DIR}/${1}.crt

CLIENT_KEY=${FILES_DIR}/${1}.key

# Test for files

for i in “$BASE_CONF” “$CA_FILE” “$TA_FILE” “$CLIENT_CERT” “$CLIENT_KEY”; do

    if [[ ! -f $i ]]; then

        echo ” The file $i does not exist”

        exit 1

    fi

    if [[ ! -r $i ]]; then

        echo ” The file $i is not readable.”

        exit 1

    fi

done

# Generate client config

cat > ${CONFIGS_DIR}/${1}.ovpn <<EOF

$(cat ${BASE_CONF})

<key>

$(cat ${CLIENT_KEY})

</key>

<cert>

$(cat ${CLIENT_CERT})

</cert>

<ca>

$(cat ${CA_FILE})

</ca>

<tls-auth>

$(cat ${TA_FILE})

</tls-auth>

EOF

Save the file and make it executable by running:

chmod u+x openvpn-clients/gen_config.sh

Creating Client Certificate Private Key and Configuration

In this example the name of the first VPN client will be david.

# cd /usr/local/EasyRSA-3.0.5/

# ./easyrsa gen-req david nopass

The command will create two files, a private key (david.key) and a certificate request file (david.req).

Copy the private key david.key to the /etc/openvpn/openvpn-clients/files directory you created in the previous section:

# cp pki/private/david.key /etc/openvpn/openvpn-clients/files/

run the following command to sign the request:

# ./easyrsa sign-req client david

Copy the david.crt file to the /etc/openvpn/openvpn-clients/files directory

# cp pki/issued/david.crt /etc/openvpn/openvpn-clients/files/

The final step is to generate a client configuration using the gen_config.sh script:

# cd /etc/openvpn/openvpn-clients/

# ./gen_config.sh david

The script will create a file named david.ovpn in the configs directory.

At this point the client configuration is created. You can now transfer the configuration file to the device you intend to use as a client.

Revoking Client Certificates

Revoking a certificate means to invalidate a signed certificate so that it can no longer be used for accessing the OpenVPN server.

Run the easyrsa script using the revoke argument, followed by the client name you want to revoke:

# ./easyrsa revoke david

Use the gen-crl option to generate a certificate revocation list (CRL):

# ./easyrsa gen-crl

Copy the file crl.pem to the /etc/openvpn directory:

# cp pki/crl.pem /etc/openvpn/

Open the OpenVPN server configuration file,Paste the following line at the end of the file:

# vi /etc/openvpn/vpnsvr01.conf

crl-verify crl.pem

Restart the OpenVPN service for the revocation directive to take effect:

# systemctl restart openvpn@vpnsvr01

注意事项:

1.openvpn服务器防火墙必须开启,并配置相关规则。不开启防火墙,openvpn客户端连接后无法连通openvpn服务器所在网段及其它网段IP。

2.openvpn客户端要连通openvpn服务器所在网段及其它网段IP,还需在openvpn服务器配置文件中添加类似如下配置项:

push “route 192.168.50.0 255.255.255.0”  //openvpn服务器所在网段IP

push “route 192.168.30.0 255.255.255.0”  //其它网段IP

3.openvpn客户端连接后,要利用openvpn服务器上网,即openvpn客户端连接后的公网IP与openvpn服务器的公网IP相同,需要在openvpn服务器配置文件中开启如下配置项:

push “redirect-gateway def1 bypass-dhcp”

4.通过./easyrsa gen-req david nopass创建生成的配置文件(ovpn)连接服务器时无需输入密码,若连接时需要输入密码,则使用./easyrsa gen-req david并设置密码。

5.默认情况下日志消息写入/var/log/messages,openvpn服务器配置文件中取消如下配置项前的注释可将日志消息写入openvpn.log。

;log-append openvpn.log

6.若openvpn服务器配置文件中去掉配置项crl-verify crl.pem并重启openvpn,则吊销证书的用户仍可连接。

附录:创建用户证书、创建用户VPN配置文件、吊销用户证书操作都可通过脚本简化操作。

脚本内容参考如下:

创建用户证书:

# cat create_client_cert.sh

#!/bin/bash

echo “Please input a client name for the client certificate.”

read -p “Client name: ” -e CLIENT

cd /usr/local/EasyRSA-3.0.5/

./easyrsa gen-req $CLIENT

cp pki/private/$CLIENT.key /etc/openvpn/openvpn-clients/files/

./easyrsa sign-req client $CLIENT

cp pki/issued/$CLIENT.crt /etc/openvpn/openvpn-clients/files/

echo “Client $CLIENT cert created”

exit

创建用户VPN配置文件:

# cat gen_client_ovpn.sh

#!/bin/bash

echo “Please input a client cert name for the client ovpn.”

read -p “Client name: ” -e CLIENT

FILES_DIR=/etc/openvpn/openvpn-clients/files

BASE_DIR=/etc/openvpn/openvpn-clients/base

CONFIGS_DIR=/etc/openvpn/openvpn-clients/configs

BASE_CONF=${BASE_DIR}/client.conf

CA_FILE=${BASE_DIR}/ca.crt

TA_FILE=${BASE_DIR}/ta.key

CLIENT_CERT=${FILES_DIR}/$CLIENT.crt

CLIENT_KEY=${FILES_DIR}/$CLIENT.key

cat > ${CONFIGS_DIR}/$CLIENT.ovpn <<EOF

$(cat ${BASE_CONF})

<key>

$(cat ${CLIENT_KEY})

</key>

<cert>

$(cat ${CLIENT_CERT})

</cert>

<ca>

$(cat ${CA_FILE})

</ca>

<tls-auth>

$(cat ${TA_FILE})

</tls-auth>

EOF

echo “Client $CLIENT ovpn created”

exit

注:VPN配置文件存放路径:/etc/openvpn/openvpn-clients/configs,用户使用生成的ovpn文件及创建用户证书时设置的密钥即可连接VPN服务器。

吊销用户证书:

# cat revoke_client_cert.sh

#!/bin/bash

echo “Please input a client cert name for revoke.”

read -p “Client name: ” -e CLIENT

cd /usr/local/EasyRSA-3.0.5/

./easyrsa revoke $CLIENT

./easyrsa gen-crl

\cp -f pki/crl.pem /etc/openvpn/

systemctl restart openvpn@vpnsvr

echo “Client $CLIENT cert revoked”

exit

注:运行此脚本吊销用户证书后,用户即无法连接VPN服务器。若需要恢复使用,需再次创建用户证书及VPN配置文件。