本周作业内容:

1、创建一个10G分区,并格式为ext4文件系统;

   (1) 要求其block大小为2048, 预留空间百分比为2, 卷标为MYDATA, 默认挂载属性包含acl;

   (2) 挂载至/data/mydata目录,要求挂载时禁止程序自动运行,且不更新文件的访问时间戳;

# 创建一个分区,没有10G空间,用1G代替。分区建在扩展分区上。
[root@captain ~]# fdisk /dev/sdb
WARNING: DOS-compatible mode is deprecated. It's strongly recommended to
         switch off the mode (command 'c') and change display units to
         sectors (command 'u').
Command (m for help): n
Command action
   e   extended
   p   primary partition (1-4)
e
Partition number (1-4): 1
First cylinder (1-1305, default 1): 1
Last cylinder, +cylinders or +size{K,M,G} (1-1305, default 1305):    
Using default value 1305
Command (m for help): n
Command action
   l   logical (5 or over)
   p   primary partition (1-4)
l
First cylinder (1-1305, default 1): 
Using default value 1
Last cylinder, +cylinders or +size{K,M,G} (1-1305, default 1305): +1G
Command (m for help): w
The partition table has been altered!
Calling ioctl() to re-read partition table.
Syncing disks.

# 通知内核重识分区信息
[root@captain ~]# partx  -a /dev/sdb
BLKPG: Device or resource busy
error adding partition 1
BLKPG: Device or resource busy
error adding partition 5

# 以ext4文件系统格式化分区,块大小2K,预留空间百分比为2,卷标为MYDATA
[root@captain ~]# mkfs.ext4 -b 2048 -m 2 -L MYDATA /dev/sdb5
mke2fs 1.41.12 (17-May-2010)
Filesystem label=MYDATA
OS type: Linux
Block size=2048 (log=1)
Fragment size=2048 (log=1)
Stride=0 blocks, Stripe width=0 blocks
66264 inodes, 530112 blocks
10602 blocks (2.00%) reserved for the super user
First data block=0
Maximum filesystem blocks=537919488
33 block groups
16384 blocks per group, 16384 fragments per group
2008 inodes per group
Superblock backups stored on blocks: 
        16384, 49152, 81920, 114688, 147456, 409600, 442368
Writing inode tables: done                            
Creating journal (16384 blocks): done
Writing superblocks and filesystem accounting information: done
This filesystem will be automatically checked every 26 mounts or
180 days, whichever comes first.  Use tune2fs -c or -i to override.

[root@captain ~]# mkdir -p /data/mydata

# 新建分区挂载到/data/mydata,挂载属性:acl、禁止程序自动运行、不更新文件的访问时间戳
[root@captain ~]# mount -o acl,noexec,noatime /dev/sdb5 /data/mydata/

# 查看文件系统大小
[root@captain ~]# df -hP
Filesystem                    Size  Used Avail Use% Mounted on
/dev/mapper/VolGroup-lv_root   18G  9.0G  7.4G  55% /
tmpfs                         931M     0  931M   0% /dev/shm
/dev/sda1                     477M   33M  419M   8% /boot
/dev/sdb5                     988M  8.1M  959M   1% /data/mydata

# 查看新建分区属性
[root@captain ~]# mount
/dev/mapper/VolGroup-lv_root on / type ext4 (rw)
proc on /proc type proc (rw)
sysfs on /sys type sysfs (rw)
devpts on /dev/pts type devpts (rw,gid=5,mode=620)
tmpfs on /dev/shm type tmpfs (rw,rootcontext="system_u:object_r:tmpfs_t:s0")
/dev/sda1 on /boot type ext4 (rw)
none on /proc/sys/fs/binfmt_misc type binfmt_misc (rw)
/dev/sdb5 on /data/mydata type ext4 (rw,noexec,noatime,acl)

   

2、创建一个大小为1G的swap分区,并创建好文件系统,并启用之;

# 查看当前系统swap分区大小为2G
[root@captain ~]# free -m
             total       used       free     shared    buffers     cached
Mem:          1861        808       1053          0          9        578
-/+ buffers/cache:        220       1640
Swap:         2047          0       2047

# 新建分区作swap分区使用 
[root@captain ~]# fdisk /dev/sdb
WARNING: DOS-compatible mode is deprecated. It's strongly recommended to
         switch off the mode (command 'c') and change display units to
         sectors (command 'u').
Command (m for help): n  
Command action
   l   logical (5 or over)
   p   primary partition (1-4)
l
First cylinder (133-1305, default 133): 
Using default value 133
Last cylinder, +cylinders or +size{K,M,G} (133-1305, default 1305): +1G
Command (m for help): w
The partition table has been altered!
Calling ioctl() to re-read partition table.
WARNING: Re-reading the partition table failed with error 16: Device or resource busy.
The kernel still uses the old table. The new table will be used at
the next reboot or after you run partprobe(8) or kpartx(8)
Syncing disks.

# 通知内核重识分区信息
[root@captain ~]# partx  -a /dev/sdb
BLKPG: Device or resource busy
error adding partition 1
BLKPG: Device or resource busy
error adding partition 5

# 格式化分区为swap分区
[root@captain ~]# mkswap /dev/sdb6
Setting up swapspace version 1, size = 1060252 KiB
no label, UUID=7c945208-4731-4c4e-91e0-9335db59bcab

# 启动/dev/sdb6作为交换分区
[root@captain ~]# swapon /dev/sdb6

# 查看现在的swap分区大小
[root@captain ~]# free -m
             total       used       free     shared    buffers     cached
Mem:          1861        810       1051          0         10        578
-/+ buffers/cache:        221       1640
Swap:         3083          0       3083


3、写一个脚本

   (1)、获取并列出当前系统上的所有磁盘设备;

   (2)、显示每个磁盘设备上每个分区相关的空间使用信息;

[root@captain shell]# cat diskusage.sh 
#!/bin/bash

declare -a partitions
declare -i idx=0

echo && echo "disks list:"
for disk in /dev/[sh]d*
do
    if [[ "$disk" =~ [0-9]$ ]]; then
        echo -n "    ├"
        echo -e "────$disk"
        partitions[idx]="$disk"
        let idx++
    else
        echo $disk
    fi
done

echo && echo "show the usage of partitions"
echo "----------------------------"

echo -e "partitions\tSize\tUsed\tUse%"
arrlen=$[${#partitions[*]}-1]
for i in `seq 0 1 $arrlen`
do
    echo -n ${partitions[$i]}
    df -hP ${partitions[$i]} |\
        awk '{printf("\t%s\t%s\t%s\n", $2,$3,$5)}' |\
        tail -1
done

[root@captain shell]# sh diskusage.sh 

disks list:
/dev/sda
    ├────/dev/sda1
    ├────/dev/sda2
/dev/sdb
    ├────/dev/sdb1
    ├────/dev/sdb5
    ├────/dev/sdb6
    
show the usage of partitions
----------------------------
partitions      Size    Used    Use%
/dev/sda1       477M    33M     8%
/dev/sda2       920M    268K    1%
/dev/sdb1       920M    268K    1%
/dev/sdb5       920M    268K    1%
/dev/sdb6       920M    268K    1%

   

4、总结RAID的各个级别及其组合方式和性能的不同;

RAID:冗余磁盘阵列,是用来提高整个磁盘系统IO能力、冗余能力和可用空间的技术。根据RAID级别不同,提供不同的功能。常用的RAID级别有0,1,10,5

RAID级别功能描述
可用容量优缺点性能
RAID0条带化存储,由数个较小的硬盘组成一个大的磁盘空间。数据分散存储在阵列中的各个磁盘中n * m(单盘容量)

优点:结构简单,成本较低,可用容量大


缺点:无冗余,一块盘坏,整个阵列的数据都有可能丢失

读写性能高
RAID1镜像存储。同一份数据分别分别写入到阵列中同为镜像的磁盘中

最少需要2 * n块磁盘

n / 2

优点:有冗余备份,支持坏一块磁盘


缺点:成本稍高,可用容量只有硬盘总数的一半

读性能高,写性能可能会稍低于单盘
RAID10镜像条带。提供RAID1级别的冗余性,同时拥有RAID0级别的读写性能

最少需要4* n块磁盘

其容量为n / 2

优点:兼顾RAID1和RAID0优点,数据安全级别高


缺点:成本昂贵

读写性能高
RAID5分布奇偶检验。数据与其相对应的奇偶检验位分散存储于各个磁盘中

最少需要3块磁盘

其容量为n - 1

优点:兼顾数据安全与存储容量,空间利用率高,同时成本低于RAID10。支持坏一块硬盘


缺点:磁盘故障会影响IO,控制器设计也比较复杂

读性能好,写性能一般


5、创建一个大小为10G的RAID1,要求有一个空闲盘,而且CHUNK大小为128k;

# RAID1至少需要两块盘,要求有一个空白盘,这里使用3块盘做RAID1。
# 因磁盘空间所限,这里2G的盘做RAID1。

# 查看磁盘大小
root@CentOS7 ~]# fdisk -l /dev/sdb /dev/sdc /dev/sdd  | grep '^Disk /dev/sd[a-z]'
Disk /dev/sdb: 2147 MB, 2147483648 bytes, 4194304 sectors
Disk /dev/sdc: 2147 MB, 2147483648 bytes, 4194304 sectors
Disk /dev/sdd: 2147 MB, 2147483648 bytes, 4194304 sectors

# 创建软件RAID,级别为1,1个空闲盘,chunk size为128K
[root@CentOS7 ~]# mdadm -C /dev/md0 -l 1 -n 2 -x 1 -c 128K /dev/sdb /dev/sdc /dev/sdd
mdadm: /dev/sdb appears to be part of a raid array:
       level=raid1 devices=2 ctime=Sat Sep 17 09:42:10 2016
mdadm: partition table exists on /dev/sdb but will be lost or
       meaningless after creating array
mdadm: Note: this array has metadata at the start and
    may not be suitable as a boot device.  If you plan to
    store '/boot' on this device please ensure that
    your boot-loader understands md/v1.x metadata, or use
    --metadata=0.90
mdadm: /dev/sdc appears to be part of a raid array:
       level=raid1 devices=2 ctime=Sat Sep 17 09:42:10 2016
mdadm: partition table exists on /dev/sdc but will be lost or
       meaningless after creating array
mdadm: /dev/sdd appears to be part of a raid array:
       level=raid1 devices=2 ctime=Sat Sep 17 09:42:10 2016
mdadm: partition table exists on /dev/sdd but will be lost or
       meaningless after creating array
Continue creating array? y
mdadm: Defaulting to version 1.2 metadata
mdadm: array /dev/md0 started.

# 查看RAID1详细信息
[root@CentOS7 ~]# mdadm -D /dev/md0 
/dev/md0:
        Version : 1.2
  Creation Time : Sat Sep 17 09:43:19 2016
     Raid Level : raid1
     Array Size : 2095104 (2046.34 MiB 2145.39 MB)
  Used Dev Size : 2095104 (2046.34 MiB 2145.39 MB)
   Raid Devices : 2
  Total Devices : 3
    Persistence : Superblock is persistent
    Update Time : Sat Sep 17 09:43:29 2016
          State : clean 
 Active Devices : 2
Working Devices : 3
 Failed Devices : 0
  Spare Devices : 1
           Name : CentOS7:0  (local to host CentOS7)
           UUID : 8a013467:568c165a:d2f181f5:511d7d12
         Events : 17
    Number   Major   Minor   RaidDevice State
       0       8       16        0      active sync   /dev/sdb
       1       8       32        1      active sync   /dev/sdc
       2       8       48        -      spare   /dev/sdd

       [root@CentOS7 ~]# cat /proc/mdstat 
Personalities : [raid1] 
md0 : active raid1 sdd[2](S) sdc[1] sdb[0]
      2095104 blocks super 1.2 [2/2] [UU]
      
unused devices: <none>


6、创建一个大小为4G的RAID5设备,chunk大小为256k,格式化ext4文件系统,要求可开机自动挂载至/backup目录,而且不更新访问时间戳,且支持acl功能;

# RAID5至少需要三块磁盘。
# 创建RAID5,chunk size为256K
[root@CentOS7 ~]#  mdadm -C /dev/md0 -l 5 -n 3 -c 256K /dev/sdb /dev/sdc /dev/sdd
mdadm: /dev/sdb appears to be part of a raid array:
       level=raid1 devices=2 ctime=Sat Sep 17 09:43:19 2016
mdadm: partition table exists on /dev/sdb but will be lost or
       meaningless after creating array
mdadm: /dev/sdc appears to be part of a raid array:
       level=raid1 devices=2 ctime=Sat Sep 17 09:43:19 2016
mdadm: partition table exists on /dev/sdc but will be lost or
       meaningless after creating array
mdadm: /dev/sdd appears to be part of a raid array:
       level=raid1 devices=2 ctime=Sat Sep 17 09:43:19 2016
mdadm: partition table exists on /dev/sdd but will be lost or
       meaningless after creating array
Continue creating array? y
mdadm: Defaulting to version 1.2 metadata
mdadm: array /dev/md0 started.

# 查看RAID5详细信息
[root@CentOS7 ~]# mdadm -D /dev/md0 
/dev/md0:
        Version : 1.2
  Creation Time : Sat Sep 17 10:02:52 2016
     Raid Level : raid5
     Array Size : 4190208 (4.00 GiB 4.29 GB)
  Used Dev Size : 2095104 (2046.34 MiB 2145.39 MB)
   Raid Devices : 3
  Total Devices : 3
    Persistence : Superblock is persistent
    Update Time : Sat Sep 17 10:03:03 2016
          State : clean 
 Active Devices : 3
Working Devices : 3
 Failed Devices : 0
  Spare Devices : 0
         Layout : left-symmetric
     Chunk Size : 256K
           Name : CentOS7:0  (local to host CentOS7)
           UUID : 516e7995:65813193:22ab7a44:1ca10114
         Events : 18
    Number   Major   Minor   RaidDevice State
       0       8       16        0      active sync   /dev/sdb
       1       8       32        1      active sync   /dev/sdc
       3       8       48        2      active sync   /dev/sdd
 
[root@CentOS7 ~]# cat /proc/mdstat 
Personalities : [raid1] [raid6] [raid5] [raid4] 
md0 : active raid5 sdd[3] sdc[1] sdb[0]
      4190208 blocks super 1.2 level 5, 256k chunk, algorithm 2 [3/3] [UUU]
      
unused devices: <none>

# 格式化为ext4文件系统
[root@CentOS7 ~]# mkfs.ext4  /dev/md0 
mke2fs 1.42.9 (28-Dec-2013)
Filesystem label=
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
Stride=64 blocks, Stripe width=128 blocks
262144 inodes, 1047552 blocks
52377 blocks (5.00%) reserved for the super user
First data block=0
Maximum filesystem blocks=1073741824
32 block groups
32768 blocks per group, 32768 fragments per group
8192 inodes per group
Superblock backups stored on blocks: 
        32768, 98304, 163840, 229376, 294912, 819200, 884736
Allocating group tables: done                            
Writing inode tables: done                            
Creating journal (16384 blocks): done
Writing superblocks and filesystem accounting information: done 

# 在/etc/fstab中追加一行:
/dev/md0 /backup    ext4    noatime,acl      0 0

# 或者使用UUID
[root@CentOS7 ~]# blkid | grep '/dev/md0'
/dev/md0: UUID="5cb8f207-c230-444f-af91-df04498dca80" TYPE="ext4"
# 在/etc/fstab/追加一行
UUID=5cb8f207-c230-444f-af91-df04498dca80 /backup   ext4   noatime,acl   0 0

# 挂载该分区,并查看分区挂载属性
[root@CentOS7 ~]# mount -a
[root@CentOS7 ~]# mount | grep '/dev/md0'
/dev/md0 on /backup type ext4 (rw,noatime,seclabel,stripe=128,data=ordered)


7、写一个脚本

   (1) 接受一个以上文件路径作为参数;

   (2) 显示每个文件拥有的行数;

   (3) 总结说明本次共为几个文件统计了其行数;

[root@captain shell]# cat practice7_7.sh 
#!/bin/bash

declare -i args="$#"
declare -A files
declare -i lines=0
declare -i ttfile=0
declare -i maxlen=0

if [ "$#" -eq 0 ]; then
    echo "must have a parameter!"
    echo -e "\tUsage: `basename $0` file1 [file2] ..."
    exit 1
fi

while [ "$args" -gt 0 ]
do
    files["$1"]=0
    let "maxlen = maxlen > ${#1} ? maxlen : ${#1}"
    let args--
    shift
done

for file in ${!files[*]}
do
    if [ -f "$file" ]; then
        cnt=$(wc -l $file | cut -d' ' -f1)
        files[$file]=$cnt
        let "lines += $cnt"
        let ttfile++
    elif [ -d "$file" ]; then
        files[$file]="Directory"
    elif [ -p "$file" ]; then
        files[$file]="Named pipe file"
    elif [ -b "$file" ]; then
        files[$file]="Block device"
    elif [ -c "$file" ]; then
        files[$file]="Character device"
    elif [ -S "$file" ]; then
        files[$file]="Socket"
    else
        files[$file]="Unknown file"
    fi
done

for file in ${!files[*]}
do
    printf "%-${maxlen}s\t%s\n" $file "${files[$file]}"
done
printf "============================================\n"
printf "%d files processed, and total lines is: %d\n" $ttfile $lines

[root@captain shell]# sh practice7_7.sh  /etc/passwd  /etc /etc/init.d/functions  /etc  /dev/sda /dev/tty /etc/fstab 
/dev/sda                Block device
/dev/tty                Character device
/etc                    Directory
/etc/passwd             58
/etc/init.d/functions   815
/etc/fstab              15
============================================
3 files processed, and total lines is: 888


8、写一个脚本

   (1) 传递两个以上字符串当作用户名;

   (2) 创建这些用户;且密码同用户名;

   (3) 总结说明共创建了几个用户;

[root@captain shell]# cat practice7_8.sh 
#!/bin/bash

. /etc/init.d/functions

declare -i args=$#
declare -i cntsuccess=0
declare -i cntfailure=0

if [ "$#" -eq 0 ]; then
    echo "at least one parameter, try again!"
    echo -e "\tUsage: `basename $0` user1 [user2] ..."
    exit 1
fi

while [ $args -gt 0 ]
do
    useradd $1 >/dev/null 2>&1
    ret=$?
    if [ "$ret" -eq 0 ]; then
        action "add user $1" /bin/true
        echo "$1" | passwd --stdin $1 2>&1 >/dev/null
        let cntsuccess++
    else
        action "add user $1" /bin/false
        let cntfailure++
    fi
    
    let args--
    shift
done

echo "$cntsuccess user(s) added, $cntfailure fails"

[root@captain shell]# sh practice7_8.sh tom jerry jack
add user tom [  OK  ]
add user jerry [  OK  ]
add user jack [  OK  ]
3 user(s) added, 0 fails

[root@captain shell]# sh practice7_8.sh tom 
add user tom [FAILED]
0 user(s) added, 1 fails

   

9、写一个脚本,新建20个用户,visitor1-visitor20;计算他们的ID之和;

[root@captain shell]# cat practice7_9.sh 
#!/bin/bash

if [ `id -u` -ne 0 ]; then
    echo "only root can execute this script"
    exit 1
fi

. /etc/init.d/functions

declare -i total=0

echo "add users: visitor1-visitor20"
for user in visitor{1..20}
do
    useradd $user >/dev/null 2>&1
    ret=$?
    if [ "$ret" -eq 0 ]; then
        action "add user $user" /bin/true
        let "total += `id -u $user`"
    else
        action "add user $user" /bin/false
    fi
done
#or: awk -F':' '/^\<visitor1\>/,/^\<visitor20\>/{t+=$3}END{print t}' /etc/passwd 

echo "The sum of user's ID: $total"

[root@captain shell]# sh practice7_9.sh
add users: visitor1-visitor20
add user visitor1 [  OK  ]
add user visitor2 [  OK  ]
add user visitor3 [  OK  ]
add user visitor4 [  OK  ]
add user visitor5 [  OK  ]
add user visitor6 [  OK  ]
add user visitor7 [  OK  ]
add user visitor8 [  OK  ]
add user visitor9 [  OK  ]
add user visitor10 [  OK  ]
add user visitor11 [  OK  ]
add user visitor12 [  OK  ]
add user visitor13 [  OK  ]
add user visitor14 [  OK  ]
add user visitor15 [  OK  ]
add user visitor16 [  OK  ]
add user visitor17 [  OK  ]
add user visitor18 [  OK  ]
add user visitor19 [  OK  ]
add user visitor20 [  OK  ]
The sum of user's ID: 60670


10、写一脚本,分别统计/etc/rc.d/rc.sysinit、/etc/rc.d/init.d/functions和/etc/fstab文件中以#号开头的行数之和,以及总的空白行数;

[root@captain shell]# cat practice7_10.sh 
#!/bin/bash

declare -r files=(/etc/rc.d/rc.sysinit /etc/rc.d/init.d/functions /etc/fstab)
declare -i totalsharpline=0
declare -i totalblankline=0

function sharpline()
{
    grep '^#' $1 | wc -l
}

function blankline()
{
    grep '^$' $1 | wc -l
}

for file in ${files[*]}
do
    let "totalsharpline += `sharpline $file`"
    let "totalblankline += `blankline $file`"
done

echo "Total starts with sharp line: $totalsharpline"
echo "Total blank line: $totalblankline"

[root@captain shell]# sh practice7_10.sh 
Total starts with sharp line: 91
Total blank line: 173


11、写一个脚本,显示当前系统上所有默认shell为bash的用户的用户名、UID以及此类所有用户的UID之和;

# 简单实现
# awk -F':' '/bash$/{sum+=$3; print $1,$3}END{print sum}' /etc/passwd

[root@captain shell]# cat count.awk 
BEGIN{
    FS=":";
    sum=0;
    printf("username\tUID\n");
}
/bash$/{sum += $3;
    printf("%-10s\t%5d\n", $1, $3);
}
END{
    printf("=========================\n");
    printf("the sum of UID: %d\n", sum);
}

[root@captain shell]# awk -f count.awk /etc/passwd
username        UID
root                0
oracle            500
icheck            501
mageia           1100
openstack        3003
testuser         3004
test1            3005
captain          3006
hadoop           1001
bash             3007
testbash         3008
basher           3009
user10           3011
user11           3012
user12           3013
user13           3014
user14           3015
user15           3016
user16           3017
user17           3018
user18           3019
user19           3020
tom              3021
jerry            3022
jack             3023
visitor1         3024
visitor2         3025
visitor3         3026
visitor4         3027
visitor5         3028
visitor6         3029
visitor7         3030
visitor8         3031
visitor9         3032
visitor10        3033
visitor11        3034
visitor12        3035
visitor13        3036
visitor14        3037
visitor15        3038
visitor16        3039
visitor17        3040
visitor18        3041
visitor19        3042
visitor20        3043
=========================
the sum of UID: 124035


12、写一个脚本,显示当前系统上所有,拥有附加组的用户的用户名;并说明共有多少个此类用户;

[root@captain shell]# cat practice7_12.sh
#!/bin/bash

declare -i usercnt=0
declare -a users=(`cut -d':' -f1 /etc/passwd`)

echo -n "the selected users: "
for user in ${users[*]}
do
    set $(id -G $user)
    [ "$#" -gt 1 ] && echo -n "$user " && let usercnt++
done

echo && echo "$usercnt users selected"

[root@captain shell]# sh practice7_12.sh 
the selected users: bin daemon adm postfix slackware openstack 
6 users selected


13、创建一个由至少两个物理卷组成的大小为20G的卷组;要求,PE大小为8M;而在卷组中创建一个大小为5G的逻辑卷mylv1,格式化为ext4文件系统,开机自动挂载至/users目录,支持acl;

# 初始化物理卷,/dev/sdb7,/dev/sdb8都是1G大小的分区
# 所以创建的卷组大小为2G
[root@captain ~]# pvcreate /dev/sdb7 /dev/sdb8
  Physical volume "/dev/sdb7" successfully created
  Physical volume "/dev/sdb8" successfully created
[root@captain ~]# pvs
  PV         VG       Fmt  Attr PSize  PFree
  /dev/sda2  VolGroup lvm2 a--  19.51g    0 
  /dev/sdb7           lvm2 ---   1.01g 1.01g
  /dev/sdb8           lvm2 ---   1.01g 1.01g
  
# 创建卷组,卷组名称为data,PE大小为8M
[root@captain ~]# vgcreate -s 8M data /dev/sdb7 /dev/sdb8
  Volume group "data" successfully created
[root@captain ~]# vgs
  VG       #PV #LV #SN Attr   VSize  VFree
  VolGroup   1   2   0 wz--n- 19.51g    0 
  data       2   0   0 wz--n-  2.02g 2.02g

# 查看卷组详细信息,大小为2G
[root@captain ~]# vgdisplay data
  --- Volume group ---
  VG Name               data
  System ID             
  Format                lvm2
  Metadata Areas        2
  Metadata Sequence No  1
  VG Access             read/write
  VG Status             resizable
  MAX LV                0
  Cur LV                0
  Open LV               0
  Max PV                0
  Cur PV                2
  Act PV                2
  VG Size               2.02 GiB
  PE Size               8.00 MiB
  Total PE              258
  Alloc PE / Size       0 / 0   
  Free  PE / Size       258 / 2.02 GiB
  VG UUID               bKsHig-SYQG-hqcw-vLGG-BAi7-llJG-vSR1x3

# 磁盘容量比较小,这里创建500M的逻辑卷
# 创建500M大小的逻辑卷mylv1
[root@captain ~]# lvcreate -L 500M -n mylv1 data
  Rounding up size to full physical extent 504.00 MiB
  Logical volume "mylv1" created

# 格式化逻辑卷为ext4分区
[root@captain ~]# mkfs.ext4 /dev/data/mylv1 
mke2fs 1.41.12 (17-May-2010)
Filesystem label=
OS type: Linux
Block size=1024 (log=0)
Fragment size=1024 (log=0)
Stride=0 blocks, Stripe width=0 blocks
129024 inodes, 516096 blocks
25804 blocks (5.00%) reserved for the super user
First data block=1
Maximum filesystem blocks=67633152
63 block groups
8192 blocks per group, 8192 fragments per group
2048 inodes per group
Superblock backups stored on blocks: 
        8193, 24577, 40961, 57345, 73729, 204801, 221185, 401409
Writing inode tables: done                            
Creating journal (8192 blocks): done
Writing superblocks and filesystem accounting information: done
This filesystem will be automatically checked every 32 mounts or
180 days, whichever comes first.  Use tune2fs -c or -i to override.

# 在/etc/fstab/文件中追加一行 
/dev/data/mylv1     /users  ext4    acl 0   0

# 挂载该分区
[root@captain ~]# mount -a
[root@captain ~]# mount
/dev/mapper/VolGroup-lv_root on / type ext4 (rw)
proc on /proc type proc (rw)
sysfs on /sys type sysfs (rw)
devpts on /dev/pts type devpts (rw,gid=5,mode=620)
tmpfs on /dev/shm type tmpfs (rw,rootcontext="system_u:object_r:tmpfs_t:s0")
/dev/sda1 on /boot type ext4 (rw)
none on /proc/sys/fs/binfmt_misc type binfmt_misc (rw)
/dev/mapper/data-mylv1 on /users type ext4 (rw,acl)


14、新建用户magedu;其家目录为/users/magedu,而后su切换至此用户,复制多个文件至家目录;

[root@captain ~]# useradd -d /users/magedu magedu
[root@captain ~]# su - magedu

[magedu@captain ~]$ pwd
/users/magedu
[magedu@captain ~]$ cp -a /etc/* .
cp: cannot open `/etc/anacrontab' for reading: Permission denied
cp: cannot access `/etc/audisp': Permission denied
cp: cannot access `/etc/audit': Permission denied
### ommited ###


15、扩展mylv1至9G,确保扩展完成后原有数据完全可用;

# 因磁盘空间不够,扩展到1G代替
# 查看扩展前分区大小为500M
[root@captain ~]# df -hP /users/
Filesystem              Size  Used Avail Use% Mounted on
/dev/mapper/data-mylv1  481M   18M  438M   4% /users

# 保存所有文件的md5值备用
[magedu@captain ~]$ find . -type f -exec md5sum {} \; > /tmp/md5_old.list

# 扩展逻辑卷,mylv1增加500M
[root@captain ~]# lvresize -L +500M /dev/data/mylv1 
  Rounding size to boundary between physical extents: 504.00 MiB
  Size of logical volume data/mylv1 changed from 504.00 MiB (63 extents) to 1008.00 MiB (126 extents).
  Logical volume mylv1 successfully resized
# 扩展文件系统
[root@captain ~]# resize2fs /dev/data/mylv1 
resize2fs 1.41.12 (17-May-2010)
Filesystem at /dev/data/mylv1 is mounted on /users; on-line resizing required
old desc_blocks = 2, new_desc_blocks = 4
Performing an on-line resize of /dev/data/mylv1 to 1032192 (1k) blocks.
The filesystem on /dev/data/mylv1 is now 1032192 blocks long.

# 查看扩展后分区大小
[root@captain ~]# df -hP /users/
Filesystem              Size  Used Avail Use% Mounted on
/dev/mapper/data-mylv1  969M   18M  901M   2% /users

# 保存扩展后所有文件的md5值
[magedu@captain ~]$ find . -type f -exec md5sum {} \; > /tmp/md5_new.list

# 比较扩展前后文件的md5值,其它文件都相同。
# .bash_history保存历史记录命令,所有md5会不一样
[magedu@captain ~]$ diff /tmp/md5_old.list /tmp/md5_new.list 
528c528
< 1fba9bc2ce4d95677dea06b210940160  ./.bash_history
---
> b3d9d06c6222d3655e8ee38d483c61a6  ./.bash_history


16、缩减mylv1至7G,确保缩减完成后原有数据完全可用;

# 查看缩减前分区大小。这里缩减到700M
[root@captain ~]# df -hP /users
Filesystem              Size  Used Avail Use% Mounted on
/dev/mapper/data-mylv1  969M   18M  901M   2% /users

# 1. 先umount分区
[root@captain ~]# umount /users/

# 2. 强制检查文件系统
[root@captain ~]# e2fsck -f /dev/data/mylv1 
e2fsck 1.41.12 (17-May-2010)
Pass 1: Checking inodes, blocks, and sizes
Pass 2: Checking directory structure
Pass 3: Checking directory connectivity
Pass 4: Checking reference counts
Pass 5: Checking group summary information
/dev/data/mylv1: 1690/258048 files (0.2% non-contiguous), 58650/1032192 blocks

# 3. 缩减文件系统至700M
[root@captain ~]# resize2fs /dev/data/mylv1 700M
resize2fs 1.41.12 (17-May-2010)
Resizing the filesystem on /dev/data/mylv1 to 716800 (1k) blocks.
The filesystem on /dev/data/mylv1 is now 716800 blocks long.

# 4. 缩减逻辑卷至700M
[root@captain ~]# lvresize -L 700M /dev/data/mylv1 
  Rounding size to boundary between physical extents: 704.00 MiB
  WARNING: Reducing active logical volume to 704.00 MiB
  THIS MAY DESTROY YOUR DATA (filesystem etc.)
Do you really want to reduce mylv1? [y/n]: y
  Size of logical volume data/mylv1 changed from 1008.00 MiB (126 extents) to 704.00 MiB (88 extents).
  Logical volume mylv1 successfully resized

# 查看缩减后分区大小
[root@captain ~]# mount -a
[root@captain ~]# df -hP /users
Filesystem              Size  Used Avail Use% Mounted on
/dev/mapper/data-mylv1  670M   18M  618M   3% /users

# 保存缩减后所有文件md5值
[magedu@captain ~]$ find . -type f -exec md5sum {} \; > /tmp/md5_new1.list

# 比较缩减前后文件的md5值,其它文件都相同。
# .bash_history保存历史记录命令,所有md5会不一样
[magedu@captain ~]$ diff /tmp/md5_old.list /tmp/md5_new1.list 
528c528
< 1fba9bc2ce4d95677dea06b210940160  ./.bash_history
---
> c6dae571df1da598b802e39cf6eba830  ./.bash_history


17、对mylv1创建快照,并通过备份数据;要求保留原有的属主属组等信息;

# 创建mylv1的快照,命名为snap_lv
[root@captain ~]# lvcreate -L 500M -n snap_lv -s /dev/data/mylv1 
  Rounding up size to full physical extent 504.00 MiB
  Logical volume "snap_lv" created

# 查看快照详细信息  
[root@captain users]# lvdisplay /dev/mapper/data-snap_lv
  --- Logical volume ---
  LV Path                /dev/data/snap_lv
  LV Name                snap_lv
  VG Name                data
  LV UUID                8GE4Tv-34Mp-ojXy-hh7T-P5DM-fuiS-RcRZT2
  LV Write Access        read/write
  LV Creation host, time captain, 2016-09-16 14:09:20 +0800
  LV snapshot status     active destination for mylv1
  LV Status              available
  # open                 1
  LV Size                704.00 MiB
  Current LE             88
  COW-table size         504.00 MiB
  COW-table LE           63
  Allocated to snapshot  20.02%
  Snapshot chunk size    4.00 KiB
  Segments               1
  Allocation             inherit
  Read ahead sectors     auto
  - currently set to     256
  Block device           253:3

# 挂载快照逻辑卷,查看其大小
[root@captain ~]# mount /dev/data/snap_lv /snapdir/
[root@captain ~]# df -hP
Filesystem                    Size  Used Avail Use% Mounted on
/dev/mapper/VolGroup-lv_root   18G  7.4G  9.0G  46% /
tmpfs                         931M     0  931M   0% /dev/shm
/dev/sda1                     477M   33M  419M   8% /boot
/dev/mapper/data-mylv1        670M   18M  618M   3% /users
/dev/mapper/data-snap_lv      670M   18M  618M   3% /snapdir

# 查看原逻辑卷与快照逻辑卷属主与属组同为magedu的文件数量,是相同的。
[root@captain users]# find /users \( -user magedu -a -group magedu \) -ls | wc -l
1679
[root@captain users]# find /snapdir \( -user magedu -a -group magedu \) -ls | wc -l
1679

# 原逻辑卷复制一个100M大小的文件。
[root@captain users]# dd if=/dev/zero of=zero.dat bs=1024K count=100
100+0 records in
100+0 records out
104857600 bytes (105 MB) copied, 0.399605 s, 262 MB/s

# 查看/users和/snapdir分区情况
[root@captain users]# ll -h
total 101M
drwx------.   2 root   root    12K Sep 16 10:50 lost+found
drwx------. 113 magedu magedu 9.0K Sep 16 14:14 magedu
-rw-r--r--.   1 root   root   100M Sep 16 14:17 zero.dat
[root@captain snapdir]# ll -h
total 23K
drwx------.   2 root   root    12K Sep 16 10:50 lost+found
drwx------. 113 magedu magedu 9.0K Sep 16 13:18 magedu

# 查看原分区与快照逻辑卷分区使用情况,原分区已用空间增加100M,快照逻辑卷空间使用率不变
[root@captain users]# df -hP
Filesystem                    Size  Used Avail Use% Mounted on
/dev/mapper/VolGroup-lv_root   18G  7.4G  9.0G  46% /
tmpfs                         931M     0  931M   0% /dev/shm
/dev/sda1                     477M   33M  419M   8% /boot
/dev/mapper/data-mylv1        670M  119M  517M  19% /users
/dev/mapper/data-snap_lv      670M   18M  618M   3% /snapdir