练习题 1、将PATH中的路径单独显示一行 echo $PATH | tr ':' '\n' 2、将文件中的每个单词(由字母组成),显示在独立的一行,且无空行 cat /etc/profile | tr -dc '[:alpha:] ' | tr -s ' ' '\n' # 删除字母和空格以外的所有字符,然后去重复空格,并换成换行符 3、创建用户gentoo,附加组为bin和root,默认shell为/bin/csh,注释信息为"Gentoo Distribution" useradd -s /bin/csh -c "Gentoo DIstribution" -G bin,root gentoo 4、创建下面用户、组和组成员关系:名字为admins的组;用户test1使用admins组作为附属组,用户test2也使用admins组作为附属组,用户test3 不可交互登录,且不是admins成员,这些用户的密码都是centos groupadd admins useradd -G admins test1 useradd -G admins test2 useradd -s /bin/nologin test3 5、当用户xiaoming 对/testdir 目录无执行权限时,意味着无法做哪些操作? xiaoming用户无法进入该目录 6、当用户xiaoqiang 对/testdir 目录无读权限时,意味着无法做哪些操作? xiaoqiang用户无法看到该目录下的文件 7、当用户wangcai 对/testdir 目录无写权限时,该目录下的只读文件file1是否可修改和删除? 不能修改,也不权限删除 8、复制/etc/fstab 文件到/var/tmp 下,设置文件所有者为wangcai 读写权限,所属组为sysadmins 组有读写权限,其他人无权限 groupadd sysadmins useradd wangcai cp /etc/fstab /var/tmp/ chown wangcai.sysadmins fstab chmod u=rw,g=rw,0= fstab 9、误删除了用户wangcai 的家目录,请重建并恢复该用户家目录及相应的权限属性 cp -r /etc/skel /home/wangcai chown -R wangcai.wangcai wangcai/ chmod 0700 wangcai/ 10、设置某个用户test新建文件默认权限为rw-r----- 要求默认权限是640,文件的最大权限是666,则umask值为026 11、在/testdir/dir 里创建的新文件自动属于g1 组,组g2 的成员如:alice 能对这些新文件有读写权限,组g3的成员如:tom 只能对新文件有读权限,其它用户(不属于g1,g2,g3 )不能访问这个文件夹 groupadd -g 2048 g1 chgrp g1 dir chmod g+w dir/ chmod g+s dir/ useradd -g g1 g1-user1 su g1-user1 setfacl -m d:g:g2:rw dir/ useradd -g g2 alice touch /testdir/dir/file-test su alice echo > file-test groupadd g3 useradd -g g3 tom setfacl -m d:g:g3:r dir/ su tom chmod o-x dir/ 备份/testdir/dir 里所有文件的ACL 权限到/root/acl.txt 中,清除/testdir/dir 中所有ACL 权限,最后还原ACL getfacl -R /testdir/dir > acl.txt # 备份 setfacl -R -b /testdir/dir # 删除原有acl权限 setfacl -R --set-file=acl.txt /testdir/dir或者setfacl --restore acl.txt # 恢复 12、任务后台执行 tail -f /var/log/message & yum install httpd & 不占用终端资源,后台执行 13、显示十天前是星期几 date -d "10 day ago" "+%A" date -d "10 day ago" "+%w" 14、今天18 :30自动关机,并提示用户 shutdown -h 18:30 "you can go!" shutdown -c 15、在本机字符终端登录时,除显示原有信息外,再显示当前登录终端号,主机名和当前时间 \S Kernel \r on an \m Terminal number \l hostname \n current time \t 16、设置当前日期为.....,显示当前日期为...... date -s "07/17/2017 19:33:00" 17、找出ifconfig ” “网卡名” 命令结果中本机的IPv4 地址 ifconfig ens33 | head -2 | tail -1 | tr -s ' ' | cut -d ' ' -f 3 18、查出分区空间使用率的最大百分比值 df | tr -s ' ' '%' | cut -d '%' -f 5 19、查出用户UID 最大值的用户名、UID 及shell 类型 cat /etc/passwd | sort -k 3 -t ':' -n | tail -1 | cut -d: -f1,3,7 20、查出/tmp 的权限,以数字方式显示 stat /tmp/ | head -4 | tail -1 | cut -d/ -f1 | cut -d '(' -f 2 21、找出ifconfig ” “网卡名” 命令结果中本机的IPv4 地址 22、显示/proc/meminfo S开头的行( 要求:使用两种方法) 方法一:cat /proc/meminfo | grep -i "^S.*" 方法二:cat /proc/meminfo | grep "^[Ss].*" 23、显示/etc/passwd 文件中不以/bin/bash 结尾的行 cat /etc/passwd | grep -v ".*/bin/bash$" 24、显示用户rpc 默认的shell 程序 cat /etc/passwd | grep "^rpc\>" | cut -d: -f7 25、找出/etc/passwd 中的两位或三位数 cat /etc/passwd | grep "\<[0-9]\{2,3\}\>" 26、显示CentOS7 的/etc/grub2.cfg 文件中,至少以一个空白字符开头的且后面存在非空白字符的行 cat /etc/grub2.cfg | grep "^[[:space:]]\+[^[:space:]]" 27、找出“netstat -tan” 命令的结果中以‘LISTEN’ 后跟任意多个空白字符结尾的行 netstat -tan | grep "\.*\<\1$" 方法二:cat /etc/passwd | grep "^\(.*\)\>.*\/\1$" 方法三:cat /etc/passwd | egrep "^(.*)\>.*/\1$" 30、利用df 和grep ,取出磁盘各分区利用率,并从大到小排序 df | grep "^/dev/sd" | grep -o "\<[0-9]\{1,3\}%" | sort -t% -k1 -nr 扩展正则表达式:df | egrep "\<([1-9][0-9]|[0-9])\>%" -o df | grep "^/dev/sd" | tr -s " " "%" | cut -d% -f5 | sort -nr df | grep -E "\<([0-9]|[1-9][0-9]){1,2}\>%" 31、判断CentOS发行版本号 cat /etc/redhat-release | grep "[[:space:]]\<[567]\>" -o | cut -d ' ' -f 2 31、显示三个用户root 、mage 、wang 的UID 和默认shell cat /etc/passwd | egrep "^(root|mage|wang)\>" | cut -d: -f3,7 42、找出/etc/rc.d/init.d/functions 文件中行首为某单词(包括下划线) 后面跟一个小括号的行 1、cat /etc/rc.d/init.d/functions | grep -E "^\<[0-9a-zA-Z_].*\>\(\).*" 2、cat /etc/rc.d/init.d/functions | egrep "^\<[0-9a-zA-Z_].*\>[(][)]" -o 33、使用egrep 取出/etc/rc.d/init.d/functions中其基名 1、echo /etc/rc.d/init.d/functions | egrep "[[:alnum:]]+$" -o # 注意:考虑grep的贪婪模式的影响 2、echo /etc/rc.d/init.d/functions | egrep "[^/]+$" -o 3、echo /etc/rc.d/init.d/functions | egrep "[^/]+/?$" -o # 处理目录(通用) 34、使用egrep取出上面路径的目录名 方法一:echo /etc/rc.d/init.d/functions | egrep "^/.*/\<" -o 方法二:echo /etc/rc.d/init.d/functions | egrep "/.*/\<" -o 35、统计last命令中以root登录的每个主机IP地址登录次数 last | egrep "^root\>" | tr -s ' ' | cut -d ' ' -f 1,3 | sort | uniq -c | tr -s ' ' | sort -t ' ' -k 1 -n 36、利用扩展正则表达式分别表示0-9 、10-99 、100-199、200-249 、250-255 "\b[0-9]\b" "\b[1-9][0-9]\b" "\b1[0-9][0-9]\b" "\b1[0-9]{2}\b" "\b2[0-4][0-9]\b" "\b25[0-5]\b" \b[0-9]\b|\b[1-9][0-9]\b|\b1[0-9][0-9]\b|\b2[0-4][0-9]\b|\b25[0-5]\b 37、显示ifconfig 命令结果中所有IPv4 地址 ifconfig | egrep "(\<([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\>\.){3}\<([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\>" -o 38、将此字符串:welcome to magedu linux 中的每个字符去重并排序,重复次数多的排到前面 cat 2.txt | grep "." -o | sort | uniq -c | tr -s ' ' | cut -d ' ' -f 2,3 | sort -nr | cut -d ' ' -f 2 | tr -d '\n' 39、显示/var 目录下所有以l 开头,以一个小写字母结尾,且中间出现至少一位数字的文件或目录 ll /var/l*[0-9]*[[:lower:]] 40、显示/etc 目录下以任意一位数字开头,且以非数字结尾的文件或目录 ll /etc/[0-9]*[^0-9] 41、显示/etc/目录下以非字母开头,后面跟了一个字母及其它任意长度任意字符的文件或目录 ll /etc/[^[:alpha:]][[:alpha:]]* 42、显示/etc/ 目录下所有以rc 开头,并后面是0-6 之间的数字,其它为任意字符的文件或目录 ll -d /etc/rc[0-6]* 43、显示/etc 目录下,所有以.d 结尾的文件或目录 ll -d /etc/*.d 44、显示/etc 目录下,所有.conf 结尾,且以m,n,r,p 开头的文件或目录 ll /etc/[m,n,r,p]*.conf 45、只显示/root 下的隐藏文件和目录 ll -d /root/.* 46、只显示/etc下的非隐藏目录 ls -d /etc/*/ 47、在vim 中设置tab 缩进为4 个字符 set tp=4 48、复制/etc/rc.d/init.d/functions 文件至/tmp 目录,替换/tmp/functions 文件中的/etc/sysconfig/init 为/var/log :%s@/etc/sysconfig/init@/var/log/g 49、删除/tmp/functions 文件中所有以# 开头,且# 后面至少有一个空白字符的行的行首的#号 :%s/^#\b\+/ 50、复制/etc/profile 至/tmp/ 目录,用查找替换命令删除/tmp/profile 文件中的行首的空白字符 :%s/^[[:space:]]*[^[:space:]]// 51、复制/etc/rc.d/init.d/functions 文件至/tmp 目录,用查找替换命令为/tmp/functions的每行开头为空白字符的行的行首添加一个#号 :%s/^[[:space:]]/#/g shell脚本 52、编写脚本/root/bin/sumid.sh ,计算/etc/passwd 文件中的第10 个用户和第20 用户的ID 之和 #!/bin/bash # To determine whether there are 20 users useramount=$(wc -l /etc/passwd | cut -d ' ' -f 1) if [ "$useramount" -lt '20' ];then echo -e "\033[31mThe number of users is less than 20\033[0m" exit 1 fi # Get uid userid10=$(cat -n /etc/passwd | head -10 | tail -1 | cut -d ':' -f 3) userid20=$(cat -n /etc/passwd | head -20 | tail -1 | cut -d ':' -f 3) # Count let sum=$userid10+$userid20 echo -e "\033[32muser$userid10 and user$userid20 sum is $sum.\033[0m" 53、编写脚本/root/bin/sumspace.sh ,传递两个文件路径作为参数给脚本,计算这两个文件中所有空白行之和 #!/bin/bash if [ ! $# -eq 2 ];then echo -e "\033[31mToo few parameters.\033[0m" exit 1 else for File in $@; do if [ ! -f $File ]; then echo "The file does not..." fi done fi blank1=$(cat $1 | grep "^[[:space:]]*$" | wc -l) blank2=$(cat $2 | grep "^[[:space:]]*$" | wc -l) let blanklines=$blank1+$blank2 echo -e "\033[32mFile $1 and File $2 Total Blank Behavior $blanklines\033[0m." 54、编写脚本/root/bin/sumfile.sh, 统计/etc, /var, /usr目录中共有多少个一级子目录和文件 #!/bin/bash dfetc=$(ls -1 /etc/ | wc -l) dfvar=$(ls -1 /var/ | wc -l) dfusr=$(ls -1 /usr/ | wc -l) let total=$dfetc+$dfvar+$dfusr echo -e "\033[32m total:$total.\033[0m" 55、编写脚本/root/bin/argsnum.sh ,接受一个文件路径作为参数;如果参数个数小于1 ,则提示用户“至少应该给一个参数”,并立即退出;如果 参数个数不小于1 ,则显示第一个参数所指向的文件中的空白行数 ColorDisplay(){ if [ $1 == GREEN ];then echo -e "\033[1;32m$2\033[0m" fi if [ $1 == RED ];then echo -e "\033[1;31m$2\033[0m" fi } if [ $# -lt 1 ]; then ColorDisplay RED "At least one." exit 1 else if [ -f "$1" ]; then BlankLine=`grep "^[[:space:]]*$" $1 | wc -l` ColorDisplay GREEN "There are ${BlankLine} blank lines." else ColorDisplay RED "file done not exist." exit 2 fi fi 56、编写脚本/root/bin/hostping.sh ,接受一个主机的IPv4地址做为参数,测试是否可连通。如果能ping 通,则提示用户“该IP 地址可访问” ; 如果不可ping 通,则提示用户“该IP地 地址不可访问” #!/bin/bash if [ -z $1 ];then echo "Usage:ping 172.18.0.1" exit 1 else ping -c 1 $1 &> /dev/null if [ $? -eq 0 ];then echo "The ip address is accessible." else echo "The ip address is inaccessible." fi fi 57、编写脚本/root/bin/checkdisk.sh ,检查磁盘分区空间和inode 使用率,如果超过80%就发广播警告空间将满 ColorDisplay(){ if [ $1 == GREEN ];then echo -e "\033[1;32m$2\033[0m" fi if [ $1 == RED ];then echo -e "\033[1;31m$2\033[0m" fi } DiskUse=`df | grep "^/dev/sd" | grep -o "\<[0-9]\{1,3\}\>%" | tr -d '%' | sort -nr | head -1` Inode=`df -i | grep "^/dev/sd" | grep -o "\<[0-9]\{1,3\}\>%" | tr -d '%' | sort -nr | head -1` ColorDisplay GREEN "Check disk utilization and inode:" if [ $DiskUse -gt 10 ];then ColorDisplay RED "Warning: Disk usage is too high!" wall "Warning: Disk usage is too high!" fi if [ $Inode -gt 10 ];then ColorDisplay RED "Warning: Inode usage is too high!" wall "Warning: Inode usage is too high!" exit 2 fi 58、编写脚本/bin/per.sh, 判断当前用户对指定的参数文件,是否不可读并且不可写 ColorDisplay(){ if [ $1 == GREEN ]; then echo -e "\033[1;32m$2\033[0m" fi if [ $1 == RED ];then echo -e "\033[1;31m$2\033[0m" fi } if [ -e $1 ]; then if [[ ! -r $1 && ! -w $1 ]]; then ColorDisplay GREEN "$1 File unreadable and unwritable." else ColorDisplay GREEN "$1 is not unreadable and can not be written." fi else ColorDisplay GREEN "file does not exist." fi 59、编写脚本/root/bin/excute.sh ,判断参数文件是否为sh后缀的普通文件,如果是,添加所有人可执行权限,否则提示用户非脚本文件 ColorDisplay(){ if [ $1 == GREEN ]; then echo -e "\033[1;32m$2\033[0m" fi if [ $1 == RED ]; then echo -e "\033[1;31m$2\033[0m" fi } if [[ -f $1 && `echo $1 | grep -o "\.sh$"` == ".sh" ]]; then if [ -x $1 ]; then ColorDisplay GREEN "Execute permission already exists." exit 1 else chmod +x $1 ColorDisplay GREEN "Add executable permissions." fi else ColorDisplay GREEN "Non-script file" fi 60、编写脚本/root/bin/nologin.sh 和login.sh, 实现禁止和允许普通用户登录系统 login.sh: ColorDisplay(){ if [ $1 == GREEN ];then echo -e "\033[1;32m$2\033[0m" fi if [ $1 == RED ];then echo -e "\033[1;31m$2\033[0m" fi } UserId=`id -u $1` if [ $UserId -lt 1000 ]; then ColorDisplay GREEN "Not ordinary users." else chsh -s `which bash` $1 &> /dev/null ColorDisplay GREEN "User login is enabled." fi nologin.sh: ColorDisplay(){ if [ $1 == GREEN ];then echo -e "\033[1;32m$2\033[0m" fi if [ $1 == RED ];then echo -e "\033[1;31m$2\033[0m" fi } UserId=`id -u $1` if [ $UserId -lt 1000 ]; then ColorDisplay GREEN "Not ordinary users." else chsh -s `which nologin` $1 &> /dev/null ColorDisplay GREEN "User login is disabled." fi 61、任意用户登录系统时,显示红色字体的警示提醒信息“ “Hi,dangerous !” vim /etc/profile.d/usermessage.sh echo -e "\033[1;31mHi,dangerous.\033[0m" 62、编写生成脚本基本格式的脚本,包括作者,联系方式,版本,时间,描述等 #/bin/bash if [ -z $1 ];then echo -e "\033[1;31mMissing file name.\033[0m" exit 1 else cat > $1 << EOF #!/bin/bash # # ********************************************** # Author: xuekaixin # Mail: jinweiayy@gmail.com # Website: www.xuejinwei.com # Date: `date +%Y-%m-%d` # Filename: `basename $1` # Description: $2 # Applicable: # ********************************************** EOF chmod +x $1 vim +$ $1 fi 63、编写脚本/root/bin/createuser.sh ,实现如下功能:使用一个用户名做为参数,如果指定参数的用户存在,就显示其存在,否则添加之;显示添 加的用户的id号等信息 ColorDisplay(){ if [ $1 == GREEN ];then echo -e "\033[1;32m$2\033[0m" fi if [ $1 == RED ];then echo -e "\033[1;31m$2\033[0m" fi } if id $1 &> /dev/null; then ColorDisplay GREEN "The user exists." else useradd -u 1024 $1 ColorDisplay GREEN "useradd user $1." id $1 fi 64、编写脚本/root/bin/yesorno.sh ,提示用户输入yes或no,并判断用户输入的是yes 还是no, 或是其它信息 ColorDisplay(){ if [ $1 == GREEN ];then echo -e "\033[1;32m$2\033[0m" fi if [ $1 == RED ];then echo -e "\033[1;31m$2\033[0m" fi } read -p "Make sure you enter(yes/no):" User case $User in "yes") ColorDisplay GREEN "Your input is yes." ;; "no") ColorDisplay GREEN "Your input is no." ;; "") read -p "Make sure you enter(yes/no):" User ;; "*") ColorDisplay GREEN "Other." ;; esac 65、编写脚本/root/bin/filetype.sh, 判断用户输入文件路径,显示其文件类型(普通,目录,链接,其它文件类型) #!/bin/bash read -p "Please enter the path(q):" userpath if [[ $userpath == q ]];then exit 1 fi while [[ $userpath = '' ]] do read -p "Please enter the path(q):" userpath if [[ $userpath == q ]];then exit 1 fi done if [[ ! -e $userpath ]];then echo "文件不存在." exit 2 fi filetype=`ls -l $userpath | grep "^.\{1\}" -o` if [[ $filetype == - ]];then echo "Ordinary file." elif [[ $filetype == d ]];then echo "directory." elif [[ $filetype == l ]];then echo "Link file." else echo "Other files." fi 66、编写脚本/root/bin/checkint.sh, 判断用户输入的参数是否为正整数 [[ "$num" =~ ^[0-9]+$ ]] && echo yes || echo no 67、判断/var/ 目录下所有文件的类型 注意:应该先检测链接文件, #!/bin/bash if [ ! -e /var ];then echo "The directory does not exist." exit 1 fi for filename in `ls /var/`;do if [ -h /var/$filename ]; then echo "Link file." elif [ -d /var/$filename ]; then echo "directory." elif [ -f /var/$filename ]; then echo "Ordinary file." else echo "other file." fi done 68、添加10 个用户user1-user10 ,密码为8位随机字符 #!/bin/bash # Add 10 users for userid in `echo user{1..10}` do if id $userid &> /dev/null;then echo "$userid already exists." else useradd $userid echo "$userid users to create." openssl rand -base64 6 | passwd --stdin $userid &> /dev/null echo "$userid Passwd settings successful." fi done 86、/etc/rc.d/rc3.d 目录下分别有多个以K开头和以S开头的文件;分别读取每个文件,以K开头的输出为文件加stop ,以S开头的输出为文件 名加start ,如K34filename stop S66filename start #!/bin/bash for filename in /etc/rc.d/rc3.d/*;do filenamenew=`basename $filename | cut -c 1` if [[ $filenamenew == K ]];then echo "$filename stop." fi if [[ $filenamenew == S ]];then echo "$filename start" fi done 69、编写脚本,提示输入正整数n的值,计算1+2+…+n 的总和 方法1 #!/bin/bash if [ -z $1 ]; then echo "usage:./count.sh 10" exit 1 fi declare -i sun=0 declare -i i=0 while [ $i -le $1 ]; do let sum+=$i let i++ done echo "$sum" 方法2 71、计算100 以内所有能被3整除的整数之和 ColorDisplay(){ if [ $1 == GREEN ];then echo -e "\033[1;32m$2\033[0m" fi if [ $1 == RED ];then echo -e "\033[1;31m$2\033[0m" fi } declare -i i=0 declare -i Sum=0 while [ $i -le 100 ]; do let i++ if [ $(($i%3)) -eq 0 ]; then let Sum+=i else continue fi done ColorDisplay GREEN "Sum:$Sum" 72、打印九九乘法表 1、for循环 ColorDisplay(){ if [ $1 == GREEN ];then echo -e "\033[1;32m$2\033[0m" fi if [ $1 == RED ];then echo -e "\033[1;31m$2\033[0m" fi } for i in `seq 1 9`;do for j in `seq 1 $i`;do let mul=i*j ColorDisplay GREEN "${j}x${i}=${mul} \c" let j++ done let i++ let j=1 echo " " done 2、while循环 ColorDisplay(){ if [ $1 == GREEN ];then echo -e "\033[1;32m$2\033[0m" fi if [ $1 == RED ];then echo -e "\033[1;31m$2\033[0m" fi } declare -i i=1 declare -i j=1 declare -i mul=1 while [ $i -le 9 ];do while [ $j -le $i ];do let mul=i*j ColorDisplay GREEN "${j}x${i}=${mul} \c" let j++ done let i++ let j=1 echo " " done 73、在/testdir 目录下创建10个html 文件, 文件名格式为数字N (从1 到10 )加随机8 个字母,如:1AbCdeFgH.html ColorDisplay(){ if [ $1 == GREEN ];then echo -e "\033[1;32m$2\033[0m" fi if [ $1 == RED ];then echo -e "\033[1;31m$2\033[0m" fi } for i in {1..10} do #mktemp ./${i}XXXXXXXX.html &> /dev/null rand=`openssl rand -base64 100 | grep -o "[A-Za-z]" | head -8 | tr -d "\n"` touch ./${i}${rand}.html done 74、打印等腰三角形 ColorDisplay(){ if [ $1 == GREEN ];then echo -e "\033[1;32m$2\033[0m" fi if [ $1 == RED ];then echo -e "\033[1;31m$2\033[0m" fi } for ((i=1;i<=${1};i++)); do for ((j=${1}-i;j>=1;j--)); do #echo -e ' \c' ColorDisplay GREEN ' \c' done for ((k=1;k<=2*i-1;++k)); do echo -e '*\c' if [ $k -eq $( expr $i \* 2 - 1 ) ]; then echo fi done done 75、编写脚本,求100以内所有正奇数之和 ColorDisplay(){ if [ $1 == GREEN ];then echo -e "\033[1;32m$2\033[0m" fi if [ $1 == RED ];then echo -e "\033[1;31m$2\033[0m" fi } declare -i i=1 declare -i Sum=0 declare -i a until [ $i -gt 99 ];do let i++ let a=$i%2 if [ $a -eq 0 ];then continue fi let Sun=$Sun+$i done ColorDisplay GREEN "$Sun" 76、编写脚本, 提示请输入网络地址,如192.168.0.0 ,判断输入的网段中主机在线状态,并统计在线和离线主机各多少 ColorDisplay() { if [ $1 == GREEN ]; then echo -e "\033[1;32m$2\033[0m" fi if [ $1 == RED ]; then echo -e "\033[1;31m$2\033[0m" fi } TestIp() { while true; do read -p "please input internet add: " IP echo "$IP" | egrep -o "(\<([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\>\.){3}\<([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\>" &> /dev/null Ipyesno=$? if [[ -n "$IP" && "$Ipyesno" -eq "0" ]]; then if [[ `echo "$IP" | cut -d "." -f 2-4` == "0.0.0" || `echo "$IP" | cut -d "." -f 3-4` == "0.0" || `echo "$IP" | cut -d "." -f 4` == "0" ]]; then break fi else ColorDisplay RED "not net addr!" continue fi done } NetOne() { NetId=`echo $IP | cut -d '.' -f 1` a=`echo $IP | cut -d '.' -f 2` b=`echo $IP | cut -d '.' -f 3` c=`echo $IP | cut -d '.' -f 4` declare -i i=1 for a in {1..254}; do for b in {1..254}; do for c in {1..254}; do { PingIp=${NetId}.${a}.${b}.${c} ping -c 1 -W 1 $PingIp &> /dev/null && ColorDisplay GREEN "$PingIp up." || ColorDisplay GREEN "$PingIp down." } & done done done wait } NetTwo() { NetId=`echo $IP | cut -d '.' -f 1` a=`echo $IP | cut -d '.' -f 2` b=`echo $IP | cut -d '.' -f 3` c=`echo $IP | cut -d '.' -f 4` declare -i i=1 for b in {1..254}; do for c in {1..254}; do { PingIp=${NetId}.${a}.${b}.${c} ping -c 1 -W 1 $PingIp &> /dev/null && ColorDisplay GREEN "$PingIp up." || ColorDisplay GREEN "$PingIp down." } & done done wait } NetThree() { NetId=`echo $IP | cut -d '.' -f 1` a=`echo $IP | cut -d '.' -f 2` b=`echo $IP | cut -d '.' -f 3` c=`echo $IP | cut -d '.' -f 4` declare -i i=1 for c in {1..254}; do { PingIp=${NetId}.${a}.${b}.${c} ping -c 1 -W 1 $PingIp &> /dev/null && ColorDisplay GREEN "$PingIp up." || ColorDisplay GREEN "$PingIp down." } & done wait } TestIp if [[ `echo "$IP" | cut -d "." -f 2-4` == "0.0.0" ]]; then NetOne elif [[ `echo "$IP" | cut -d "." -f 3-4` == "0.0" ]]; then NetTwo elif [[ `echo "$IP" | cut -d "." -f 4` == "0" ]]; then NetThree fi 77、编写脚本,利用变量RANDOM 生成10个随机数字,输出这个10 数字,并显示其中的最大值和最小值 ColorDisplay(){ if [ $1 == GREEN ];then echo -e "\033[1;32m$2\033[0m" fi if [ $1 == RED ];then echo -e "\033[1;31m$2\033[0m" fi } Max=$RANDOM Min=$Max ColorDisplay GREEN "$Max" for i in {1..9};do Tmp=$RANDOM ColorDisplay GREEN "$Tmp" if [ $Tmp -gt $Max ];then Max=$Tmp fi if [ $Tmp -lt $Min ];then Min=$Tmp fi done ColorDisplay GREEN "Max:$Max" ColorDisplay GREEN "Min:$Min" 78、每隔3 秒钟到系统上获取已经登录的用户的信息;如果发现用户dacker 登录,则将登录时间和主机记录于日志/var/log/login.log 中, 并退出脚本 ColorDisplay(){ if [ $1 == GREEN ];then echo -e "\033[1;32m$2\033[0m" fi if [ $1 == RED ];then echo -e "\033[1;31m$2\033[0m" fi } while true;do if [[ `who | egrep "^docker\>" -o` == docker ]];then ColorDisplay GREEN "docker user login." echo "`date '+%Y-%m-%d %H:%m'` docker user login." >> /var/log/login.log break fi ColorDisplay GREEN "Being detected....." sleep 3 done 79、随机生成10以内的数字,实现猜字游戏,提示比较大或小,相等则退出 ColorDisplay(){ if [ $1 == GREEN ];then echo -e "\033[1;32m$2\033[0m" fi if [ $1 == RED ];then echo -e "\033[1;31m$2\033[0m" fi } #Random=$[$RANDOM%10+1] Random=8 while true; do read -p "Enter a number(1-9): " random if [ "$random" -lt "$Random" ]; then ColorDisplay RED "smlall." continue fi if [ "$random" -gt "$Random" ]; then ColorDisplay RED "great." continue fi if [ "$random" -eq "$Random" ]; then ColorDisplay RED "equal." break fi done 80、用文件名做为参数,统计所有参数文件的总行数 ColorDisplay(){ if [ $1 == GREEN ];then echo -e "\033[1;32m$2\033[0m" fi if [ $1 == RED ];then echo -e "\033[1;31m$2\033[0m" fi } declare -i total=0 for i in $@; do row=`cat $i | wc -l` let total=$total+$row done ColorDisplay GREEN "$* \n Number of rows: $total" 81、用二个以上的数字为参数,显示其中的最大值和最小值 ColorDisplay(){ if [ $1 == GREEN ];then echo -e "\033[1;32m$2\033[0m" fi if [ $1 == RED ];then echo -e "\033[1;31m$2\033[0m" fi } if [ $# -eq 0 ];then ColorDisplay GREEN "No arguments." exit 1 fi declare -i Num=$# declare -i i declare -i j Arr=($@) for ((i=0;i<$Num-1;i++)); do for ((j=0;j<$Num-1-$i;j++)); do if [ ${Arr[$j]} -lt ${Arr[$j+1]} ]; then Tmp=${Arr[$j]} Arr[$j]=${Arr[$j+1]} Arr[$j+1]=$Tmp fi done done ColorDisplay GREEN "MAX:${Arr}" ColorDisplay GREEN "MIN:${Arr[$#-1]}" 82、输入若干个数值存入数组中,采用冒泡算法进行升序或降序排序 ColorDisplay(){ if [ $1 == GREEN ];then echo -e "\033[1;32m$2\033[0m" fi if [ $1 == RED ];then echo -e "\033[1;31m$2\033[0m" fi } if [ $# -eq 0 ];then ColorDisplay GREEN "No arguments." exit 1 fi declare -i Num=$# declare -i i declare -i j Arr=($@) for ((i=0;i<$Num-1;i++)); do for ((j=0;j<$Num-1-$i;j++)); do if [ ${Arr[$j]} -lt ${Arr[$j+1]} ]; then Tmp=${Arr[$j]} Arr[$j]=${Arr[$j+1]} Arr[$j+1]=$Tmp fi done done ColorDisplay GREEN "${Arr[*]}" 83、扫描/etc/passwd文件每一行,如发现GECOS字段为空,则填充用户名和单位电话为62985600,并提示该用户的GECOS信息修改成功。 while read Row; do UserName=$(echo "$Row" | cut -d ':' -f 1) Gecos=$(echo "$Row" | cut -d ':' -f 5) if [ ! -n "$Gecos" ]; then chfn -f "$UserName" -p "62985600" $UserName &> /dev/null echo "modify GECOS." | mail -s "modify GECOS." $UserName && wall "$UserName modify GECOS." fi done < /etc/passwd 84、编写脚本/root/bin/copycmd.sh 1.提示用户输入一个可执行命令名称 2.获取此命令所依赖到的所有库文件列表 3.复制命令至某目标目录( 例如/mnt/sysroot) 下的对应路径下如:/bin/bash ==> /mnt/sysroot/bin/bash/usr/bin/passwd ==> /mnt/sysroot/usr/bin/passwd 4.复制此命令依赖到的所有库文件至目标目录下的对应路径下如:/lib64/ld-linux-x86-64.so.2 ==>/mnt/sysroot/lib64/ld-linux-x86-64.so.2 5.每次复制完成一个命令后,不要退出,而是提示用户键入新的要复制的命令,并重复完成上述功能;直到用户输入quit ColorDisplay() { String=`echo $2 | wc -L` Columns=`stty -a | grep -o "columns [0-9]\+" | grep -o "[0-9]\+"` Gchar=$[(Columns-Srting-6)/2] #Gchar=$[Columns-Srting-6] case $1 in "OK") echo -e "\033[1;32m$2\033[0m\033[${Gchar}G [\033[1;32m OK \033[0m]\033[0m" ;; "35OK") echo -e "\033[1;35m$2\033[0m\033[${Gchar}G [\033[1;32m OK \033[0m]\033[0m" ;; "NO") echo -e "\033[1;31m$2\033[0m\033[${Gchar}G [\033[1;31m NO \033[0m]\033[0m" ;; "PO") for ((i=1;i<=50;i++)); do echo -e "\033[1;36m——\c\033[0m" [ $i -eq 50 ] && echo done ;; "DIR") echo -e "\033[1;34m$2\033[0m\033[${Gchar}G [\033[1;32m OK \033[0m]\033[0m" esac } while true; do ColorDisplay PO read -p "Enter the Root directory(Example->/mnt/sysroot)[q]: " TargetDir if [ "$TargetDir" == "q" ]; then exit 255 fi if [ ! -d "$TargetDir" ]; then ColorDisplay NO "Root directory does not exist!" continue else break fi done while true; do ColorDisplay PO read -p "Please enter the command(q): " COMD if [ "$COMD" == "q" ];then exit 2 fi which --skip-alias "$COMD" &> /dev/null if [[ "$?" -ne 0 || ! -n "$COMD" ]];then ColorDisplay NO "The command does not exist!" continue else for Shared in $(ldd `which --skip-alias $COMD` | grep -E "(/usr)?/lib64/.*[[:space:]]" -o); do SharedPath=$(echo "$Shared" | sed -r 's#(/.*/)[^/]+/?$#\1#') if [ ! -e ${TargetDir}$SharedPath ]; then mkdir -p "${TargetDir}$SharedPath" ColorDisplay DIR "create Directory ${TargetDir}$SharedPath." fi if [ -e ${TargetDir}$Shared ]; then ColorDisplay 35OK "${TargetDir}$Shared Shared File exists!" continue else cp $Shared "${TargetDir}${SharedPath}" ColorDisplay OK "copy $Shared to ${TargetDir}${SharedPath} success." fi done fi Program=$(which --skip-alias "$COMD") ProgramPath=$(echo "$Program" | sed -r 's#(/.*/)[^/]+/?$#\1#') if [ ! -e ${TargetDir}$ProgramPath ]; then mkdir -p "${TargetDir}$ProgramPath" ColorDisplay DIR "create directory ${TargetDir}$ProgramPath." fi cp $Program "${TargetDir}$ProgramPath" ColorDisplay DIR "copy program $Program to ${TargetDir}$ProgramPath." done 85、编写函数实现两个数字做为参数,返回最大值 DigitalComparison() { if [[ -n "$1" && -n "$2" && "$1" =~ ^[0-9]+.?[0-9]+$ && "$2" =~ ^[0-9]+.?[0-9]+$ ]]; then if [[ "$1" =~ "$2" ]]; then echo "$1 equal $2." elif [[ $(echo "$1 > $2" | bc) -eq 1 ]]; then echo -e "Max:$1\nMin:$2" else echo -e "Max:$2\nMin:$1" fi else echo "Invalid input!" exit 1 fi } DigitalComparison 7.9999 7.999999 86、编写函数实现数字的加减乘除运算,例如输入 1 + 2 将得出正确结果 DigitalComparison() { if [[ -n "$1" && -n "$2" && "$1" =~ ^[0-9]+.?[0-9]+$ && "$2" =~ ^[0-9]+.?[0-9]+$ ]]; then echo "$1+$2=`echo $1+$2 | bc`" echo "$1-$2=`echo $1-$2 | bc`" echo "$1*$2=`echo $1*$2 | bc`" if [ "$2" == 0 ]; then echo "$1/$2=..Invalid divisor." else Tmp=$(echo "scale=5;$1/$2" | bc) echo "$1/$2=${Tmp}" fi else echo "Invalid input!" exit 1 fi } DigitalComparison 20.43 10.123 文件查找 87、查找/var 目录下属主为root ,且属组为mail 的所有文件 find /var/ \( -user root -a -group mail \) 88、查找/var 目录下不属于root 、lp 、gdm 的所有文件 find /var/ \( -not -user root -a -not -user lp -a -not -user gdm \) 89、查找/var 目录下最近一周内其内容修改过,同时属主不为root ,也不是postfix 的文件 find /var/ \( -mtime -7 -a -not -user root -a -not -user postfix\) 90、查找当前系统上没有属主或属组,且最近一个周内曾被访问过的文件 find / \( \( -nouser -o -nogroup \) -a -atime -7 \) 91、查找/etc 目录下大于1M 且类型为普通文件的所有文件 find /etc/ \( -size +1M -a -type f \) 92、查找/etc 目录下所有用户都没有写权限的文件 find /etc/ -maxdepth 1 \( -not -perm /222 \) -ls 93、查找/etc 目录下至少有一类用户没有执行权限的文件 find /etc/ -maxdepth 8 \( -not \( -not -perm /222 \) \) -ls 94、查找/etc/init.d 目录下,所有用户都有执行权限,且其它用户有写权限的文件 find /etc/init.d/ \( -perm -111 -a -perm -002 \) -ls find /etc/init.d/ -perm -113 -ls 程序包管理 95、查询命令java 来自于哪个rpm包 rpm -q --whatprovides java 96、yum 的配置和使用, 包括yum仓库的创建 [repo-name] name= baseurl= enable= gpgcheck= gpgkey= cost= 97、编写系统初始化脚本reset.sh ,包括别名,提示符颜色,yum 仓库配置文件, 安装tree,ftp,lftp,telnet等包 ColorDisplay(){ if [ $1 == GREEN ];then echo -e "\033[1;32m$2\033[0m" fi if [ $1 == RED ];then echo -e "\033[1;31m$2\033[0m" fi } # Detection tag files if [ -f /tmp/systeminit ];then ColorDisplay RED "The system has been initialized." exit 1 fi # Detects the current user if [ ! $USER == root ];then ColorDisplay RED "Non-administrator." exit 2 fi # config .bashrc ColorDisplay GREEN "Alias and PS1 are being set." cp /root/.bashrc{,.bashrc.bak} if [ ! $? -eq 0 ];then ColorDisplay RED "Profile backup failed" exit 3 fi cat >> /root/.bashrc << EOF alias cl='clear' PS1="\[\e[1;31m\][\[\e[0m\] \[\e[1;33m\]\u@\h\[\e[0m\] \[\e[1;36m\]\w\[\e[0m\]\[\e[1;31m\] ]\[\e[0m\]\[\e[1;32m\]\\$\[\e[0m\] " EOF # Detect system network status NetCode=`curl -I -s --connect-timeout 5 www.baidu.com -w %{http_code} | tail -n1` if [ $NetCode == 200 ];then ColorDisplay GREEN "Network OK." else ColorDisplay RED "NO Network." exit 4 fi # Configure the yum repository ColorDisplay GREEN "Configure the yum repository." mkdir /etc/yum.repos.d/repo.bak mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/repo.bak cd /etc/yum.repos.d/;curl -O http://ohz3haotv.bkt.clouddn.com/epel.repo &> /dev/null cd /etc/yum.repos.d/;curl -O http://ohz3haotv.bkt.clouddn.com/CentOS-Base.repo &> /dev/null cd /etc/yum.repos.d/;curl -O http://ohz3haotv.bkt.clouddn.com/CentOS-local.repo &> /dev/null ColorDisplay GREEN "Yum cache is being generated." yum makecache &> /dev/null ColorDisplay GREEN "Yum Warehouse configuration is successful." # install tree yum -y install tree &> /dev/null ColorDisplay GREEN "Installing tree..." if [ ! $? -eq 0 ];then ColorDisplay RED "tree install failed." exit 5 else ColorDisplay GREEN "tree install success." fi yum -y install lftp &> /dev/null ColorDisplay GREEN "Installing lftp..." if [ ! $? -eq 0 ];then ColorDisplay RED "lftp install failed" exit 6 else ColorDisplay GREEN "lftp install success." fi yum -y install telnet &> /dev/null ColorDisplay GREEN "Installing telnet..." if [ ! $? -eq 0 ];then ColorDisplay RED "telnet install failed" exit 7 else ColorDisplay GREEN "telnet install success." fi touch /tmp/systeminit chattr +i /tmp/systeminit ColorDisplay GREEN "Configure the system environment success,please login again." 98、创建一个2G 的文件系统,块大小为2048byte,预留1%可用空间, 文件系统ext4 ,卷标为TEST ,要求此分区开机后自动 挂载至/test目录,且默认有acl挂载选项 mkfs -t ext4 -L TEST -m 1 -b 2048 -c /dev/sdb1 mkdir /test/ mount -o defaults,acl -L TEST /works/test vim /etc/fatab LABEL=TEST /works/test ext4 defaults,acl 0 0 mount -a 99、写一个脚本,完成如下功能: (1)列出当前系统识别到的所有磁盘设备 (2)如磁盘数量为1 ,则显示其空间使用信息,否则显示最后一个磁盘上的空间使用信息 ColorDisplay(){ if [ $1 == GREEN ];then echo -e "\033[1;32m$2\033[0m" fi if [ $1 == RED ];then echo -e "\033[1;31m$2\033[0m" fi } ColorDisplay RED "Current system disk:" Disk=`lsblk -d -o NAME,SIZE | tr -s " " | grep "[s,h]d[a-z]"` ColorDisplay GREEN "${Disk}" echo "***************************************************************" Show=`echo "$Disk" | cut -d ' ' -f 1 | tail -1` fdisk -l /dev/$Show | grep -v "^$" echo "***************************************************************" 100、将CentOS6 的CentOS-6.8-x86_64-bin-DVD1.iso和CentOS-6.8-x86_64-bin-DVD2.iso 两个文件合并成一个 createrepo /data/CentOS-6.9-x86_64-bin-Everthing-DVD mkisofs -r -o CentOS-6.9-x86_64-bin-Everthing-DVD.iso /data/CentOS-6.9-x86_64-bin-Everthing-DVD 挂载使用 101、创建一个可用空间为1G 的RAID1 设备,文件系统为ext4有一个空闲盘,开机可自动挂载至/backup目录 1、准备三块1G的硬盘,并创建raid mdadm -C /dev/md0 -a yes -l1 -n2 /dev/sdb[1-2] -x1 /dev/sdb3 2、查看raid阵列信息 mdadm -D /dev/md0 3、 查看raid容量信息 fdisk -l /dev/md0 4、格式化文件系统 mkfs -t ext4 -c -F -m 3 /dev/md0 5、挂载 mount /dev/md0 /backup/ 6、修改/etc/fstab UUID=728881c8-0773-4c96-acd9-a9d02c273b19 /backup ext4 defaults 0 0 7、创建好的raid设备还可以创建分区分别挂载 102、创建由三块硬盘组成的可用空间为2G 的RAID5 设备,要求其chunk 大小为256k ,文件系统为ext4 ,开机可自动挂载至/mydata 目录 1、mdadm -C /dev/md0 -a yes -c 256 -l 5 -n 3 /dev/sdb[1-3] 2、UUID=728881c8-0773-4c96-acd9-a9d02c273b19 /mydata ext4 defaults 0 0 3、mount -a 103、创建一个至少有两个PV组成的大小为20G的名为testvg的VG,要求PE大小为16MB, 而后在卷组中创建大小为5G的逻辑卷testlv ; 挂载至/users 目录 新建用户archlinux ,要求其家目录为/users/archlinux,而后su 切换至archlinux 用户,复制/etc/pam.d 目录至自己的家目录 扩展testlv 至7G ,要求archlinux 用户的文件不能丢失 收缩testlv 至3G ,要求archlinux 用户的文件不能丢失 对testlv 创建快照,并尝试基于快照备份数据,验正快照的功能 1、创建三个分区sdb1、sdb2、sdb3 2、创建PV 物理卷 pvcreate /dev/sdb{1,2,3} 3、创建卷组 vgcreate -v -s 16M VG /dev/sdb1 /dev/sdb2 4、扩展卷组 vgextend -v VG /dev/sdb3 5、创建逻辑卷 lvcreate -L 5G -n LV-archlinux VG 6、创建用户家目录、创建用户 mkdir /archlinux useradd -d /users/archlinux archlinux 7、格式化逻辑分区 mkfs -t ext4 /dev/VG/LV-archlinux 7、挂载逻辑卷到archlinux用户的家目录 mount /dev/VG/LV-archlinux /users/archlinux/ (恢复用户家目录文件) 8、复制文件 cp -a /etc/pam.d/ . 9、扩展逻辑卷LV-archlinux lvextend -L +2G /dev/VG/LV-archlinux -v 10、缩减文件系统 resize2fs /dev/VG/LV-archlinux 3G 11、收缩逻辑卷 lvreduce -L 3G /dev/VG/LV-archlinux -v 11、重新挂载查看文件是否存在 12、制作逻辑卷快照 lvcreate -L 1G -p r -s /dev/VG/LV-archlinux -n LV-archlinux-snap 104、删除centos7 系统/etc/grub2.cfg 文件中所有以空白开头的行行首的空白字符 cat /etc/grub2.cfg | sed 's/^[[:space:]]+//' sed -r 's/^ +//' /etc/grub2.cfg 105、删除/etc/fstab 文件中所有以#开头,后面至少跟一个空白字符的行的行首的# 和空白字符 # cat /etc/fstab | sed -r 's/^#[[:space:]]+//' 106、在centos6 系统/root/install.log 每一行行首增加#号 # cat /root/anaconda-ks.cfg | sed '/^/ s//#/' cat anaconda-ks.cfg | sed 's/^/#/' 107、在/etc/fstab 文件中不以# 开头的行的行首增加#号 # cat /etc/fstab | sed '/^[^#]/ s//#/' cat /etc/fstab | sed -r 's/^[^#]/#/' ============================================================================================================================================== 108、处理/etc/fstab 路径, 使用sed 命令取出其目录名和基名 echo "/etc/sysconfig/funtion/" | sed -r 's#^/.*/([^/]+/?)#\1#' # 基名 echo "/etc/sysconfig/funtion/" | sed -r 's#(/.*/)[^/]+/?$#\1#' # 目录名 ============================================================================================================================================== 109、利用sed 取出ifconfig 命令中本机的IPv4 地址 ifconfig | sed -rn '/(\<([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-4])\>\.){3}\<([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-4])\>/p' | sed -r 's@\<[a-zA-Z]+\>@@g' ============================================================================================================================================== 110、统计centos 安装光盘中Package 目录下的所有rpm 文件的以.分隔倒数第二个字段的重复次数 ls -1 | grep ".rpm" | rev | cut -d. -f2 | sort | uniq -c ls -1 | grep ".rpm$" | grep -Eo "[^\.]*.rpm$" | sed 's/.rpm//' | sort | uniq -c ============================================================================================================================================== 111、统计/etc/init.d/functions 文件中每个单词的出现次数,并排序(用grep 和sed 两种方法分别实现) cat /etc/init.d/functions | grep -Eo "[a-zA-Z]+" | sort | uniq -c | sort -n echo "/etc/sysconfig/funtion/" | sed 's#[^a-zA-Z]#\n#g' | sed '/^$/d' | ============================================================================================================================================== 112、将文本文件的n 和n+1 行合并为一行,n奇数行 cat /etc/services | sed -n 100,101p | sed 'N;s/\n//' ============================================================================================================================================== 113、配置三个路由器连接4个网络,使得两个机器通信 路由器接受到目的地是未知网络的报文,将报文转发给离它最近的路由的靠近它的一个接口上去。 ============================================================================================================================================== 114、两台主机不同网段,没有路由器使之通信 在两台主机物理连接的前提下,将两台主机的默认网关设置为自己当前的IP地址,则可以进行通信。 ============================================================================================================================================== 115、每天的2 点和12 点整,将/etc 备份至/testdir/backup目录中,保存的文件名称格式为“etcbak-yyyy-mm-dd-HH.tar.xz” 0 2,12 * * * /bin/tar -cJf /testdir/backup/etcbak-`date +\%Y-\%m-\%d-\%H`.tar.xz /etc &> /dev/null ============================================================================================================================================== 116、每周2, 4, 7 备份/var/log/messages 文件至/logs目录中,文件名形如“messages-yyyymmdd” 0 0 * * 2,4,7 cp -a /var/log/message /logs/message-`date +%Y%m%d` ============================================================================================================================================== 117、每两小时取出当前系统/proc/meminfo 文件中以S 或M开头的信息追加至/tmp/meminfo.txt 文件中 0 */2 * * * grep "^[SM]" /proc/meminfo >> /tmp/meminfo.txt 118、工作日时间,每10分钟执行一次磁盘空间检查,一旦发现任何分区利用率高于80% ,就执行wall */10 * * * 1-5 bash /works/scripts/checkdisk.sh 119、破解root口令,并为grub 设置保护功能 1、开机今如grub引导界面,给内核传递参数1或者s或者S进入单用户模式 2、执行passwd指令修改root密码 3、打开/etc/grub.conf passwd --md5 sdfjasldvnasdfjasd passwd asdlkjsdklf 120、打印国际象棋 for ((k=1;k<=4;k++)); do for (( a=1;a<=4;a++)); do for ((i=1;i<=8;i++)); do if [ $(($i%2)) -ne 0 ]; then echo -ne "\033[41m \033[0m" else echo -ne "\033[47m \033[0m" fi if [ $i -eq 8 ]; then echo fi done done for (( b=1;b<=4;b++)); do for ((j=1;j<=8;j++)); do if [ $(($j%2)) -ne 0 ]; then echo -ne "\033[47m \033[0m" else echo -ne "\033[41m \033[0m" fi if [ $j -eq 8 ]; then echo fi done done done 121、后续六个字符串:efbaf275cd、4be9c40b8b、 44b2395c46、f8c8873ce0、b902c16c8b、ad865d2f63 是通过对随机数变量RANDOM随机执行命令, echo $RANDOM|md5sum|cut –c1-10 后的结果,请破解这些字符串对应的RANDOM值 for ((i=0;i<=32767;i++)); do { Random=`echo $i | md5sum | cut -c1-10` case $Ramdom in "efbaf275cd") echo "$RAMDOM md5sum is $Ramdom" break ;; "4be9c40b8b") echo "$RAMDOM md5sum is $Ramdom" break ;; "44b2395c46") echo "$RAMDOM md5sum is $Ramdom" break ;; "f8c8873ce0") echo "$RAMDOM md5sum is $Ramdom" break ;; "b902c16c8b") echo "$RAMDOM md5sum is $Ramdom" break ;; "ad865d2f63") echo "$RAMDOM md5sum is $Ramdom" break ;; esac } & done 122、删除vmlinuz 和 initramfs 文件后无法启动, 两种方法恢复之 方法一: # 如果机器重启 1、挂载光盘调整启动顺序进入救援模式 2、取得shell环境 3、切换根文件 chroot /mnt/sysimage 4、将光盘挂载至某个目录下 mount /dev/sr0 /media 6、进入光盘在Package目录安装 kernel 包 rpm -inh kernel-$(uname -r).rpm --force 将光盘作为yum仓库,利用 yum 安装kernel 注:利用yum安装内核时将自动生成 initramfs 文件,如果 rpm 工具安装的内核,则需要手动生成 dracut /boot/initramfs.$(uname -r).img $(uname -r) 7、生成 grub2 配置文件 grub2-mkconfig -o /boot/grub2/grub.cfg /dev/sda1 8、退出 exit 9、重启 reboot # 如果机器未重启 1、yum reinstall kernel 注:这个过程会慢,因为会自动生成 initramfs 文件 2、安装grub2 grub2-install --root-directory=/ /dev/sda 3、生成grub2配置文件 grub2-mkconfig -o /boot/grub2/grub.cfg 123、斐波那契数列又称黄金分割数列,因数学家列昂纳多· 斐波那契以兔子繁殖为例子而引入,故又称为“兔子数列”,指的是这样一个数列:0 、1、1 2 、3 、5 、8 、13 、21 、34 、…… ,斐波纳契数列以如下被以递归的方法定义:F (0)=0 ,F (1)=1 ,F (n)=F(n-1)+F(n-2) (n≥2)利用函数,求n阶斐波那契数列 fib.sh fib() { if [ "$1" -eq 1 ]; then echo "0" elif [ "$1" -eq 2 ]; then echo "1" else echo "$[$(fib $[$1-1])+$(fib $[$1-1])]" fi } fib 10 124、在CentOS6编写httpd服务脚本 #!/bin/bash # # httpd Startup script for the Apache HTTP Server # # chkconfig: - 85 15 # 加入 service 服务,指明启动级别 # description: The Apache HTTP Server # 描述信息 # processname: httpd # 进程名称 # . /etc/rc.d/init.d/functions # 载入functions函数 apachectl=/usr/local/httpd24/bin/apachectl httpd=/usr/local/httpd24/bin/httpd # 定义变量。httpd 程序路径 prog=httpd pidfile=/var/run/httpd.pid # 定义变量。pid文件的路径,此处pid文件的路径要和httpd配置文件中的PidFile配置段一致 lockfile=/var/lock/subsys/httpd # 定义变量。锁文件路径 RETVAL=0 STOP_TIMEOUT=10 # 关闭进程超时时长 start() { echo -n $"Starting $prog: " daemon --pidfile=${pidfile} $httpd # 调用 functions 文件中的 daemon函数 启动httpd程序, 给daemon传递的参数为 [pid文件路径] 和 [httpd程序的路径] RETVAL=$? echo [ $RETVAL = 0 ] && touch ${lockfile} # 如果启动成功,则创建锁文件。 return $RETVAL } stop() { status -p ${pidfile} $httpd > /dev/null # 调用 functions 文件中的 status 函数,传递 pid 路径和程序路径,检测httpd的状态 if [[ $? = 0 ]]; then echo -n $"Stopping $prog: " killproc -p ${pidfile} -d ${STOP_TIMEOUT} $httpd else echo -n $"Stopping $prog: " success fi RETVAL=$? echo [ $RETVAL = 0 ] && rm -f ${lockfile} ${pidfile} # 如果关闭进程成功,则删除锁文件和pid文件 } reload() { echo -n $"Reloading $prog: " if ! LANG=$HTTPD_LANG $httpd $OPTIONS -t >&/dev/null; then RETVAL=6 echo $"not reloading due to configuration syntax error" failure $"not reloading $httpd due to configuration syntax error" else # Force LSB behaviour from killproc LSB=1 killproc -p ${pidfile} $httpd -HUP RETVAL=$? if [ $RETVAL -eq 7 ]; then failure $"httpd shutdown" fi fi echo } # See how we were called. case "$1" in start) start ;; stop) stop ;; status) status -p ${pidfile} $httpd RETVAL=$? ;; restart) stop start ;; condrestart|try-restart) # 尝试重启,重启之前先对进程状态进行检测,如果是开启状态,则进行重启操作。否则不做任何操作 if status -p ${pidfile} $httpd >&/dev/null; then stop start fi ;; force-reload|reload) reload ;; graceful|help|configtest|fullstatus) $apachectl $@ RETVAL=$? ;; *) # 如果用户输出错误,则输出提示信息 echo $"Usage: $prog {start|stop|restart|condrestart|try-restart|force-reload|reload|status|fullstatus|graceful|help|configtest}" RETVAL=2 esac exit $RETVA —————————————————————————————————————————————————————————————————————————————————————————————————————— 总结:进程启动,脚本在 /var/lock/subsys/ 创建一个锁文件,同时进程本身会生成一个 pid 文件。 如果锁文件存在,则输出进程已经启动。 (利用所文件存在与否,判断进程是否在停止状态或者启动状态) 如果文件不存在,则启动,如果存在,则不做任何操作。 —————————————————————————————————————————————————————————————————————————————————————————————————————— 124、在 grub 第二个阶段加载 boot 分区的 vmlinux 和 ramdisk ,然后切换到真正的根文件系统。在哪里触发了系统第一个程序 init 运行? 在 ramdisk 中有一个 init 程序,ramdisk 中的 init 程序负责加载相应的装载挂载根文件系统所需要的文件系统驱动模块及切换根文件系统, 根文件系统挂载之后,内核负责调用系统启动的第一个进程 init 进程。 1 2 3 1 4 7 126、将图所示,实现转置矩阵matrix.sh 4 5 6 ===> 2 5 8 7 8 9 3 6 9 Mat0=("1" "2" "3") Mat1=("4" "5" "6") Mat2=("7" "8" "9") echo -e "${Mat0[*]}\n${Mat1[*]}\n${Mat2[*]}" declare -i i for ((i=0;i<3;i++)); do H0="$H0 ${Mat0[$i]}" H0="$H0 ${Mat1[$i]}" H0="$H0 ${Mat2[$i]}" done for ((i=0;i<=10;i++)); do echo -e "=\c" [ $i -eq 10 ] && echo done echo $H0 | awk -F " " '{i=1;while (i<=9) {printf "%d %d %d\n",$i,$(i+1),$(i+2);i+=3}}' 127、统计/etc/fstab 文件中每个文件系统类型出现的次数 cat /etc/fstab | awk '/^UUID/{fstype[$3]++}END{for (A in fstype) {printf "%s %d\n",A,fstype[A]}}' 128、统计/etc/fstab 文件中每个单词出现的次数 cat /etc/fstab | awk -F " " '{i=1; while (i<=NF) {word[$i]++;i++;} }END{ for (i in word) {printf "%-42s %d\n",i,word[i]} }' 129、dd 命令损坏 grub 第一阶段并恢复 1、模拟损坏 dd if=/dev/zero of=/dev/sda bs=446 count=1 2、查看前512字节 hexdump -C -n 512 /dev/sda -v 3、启动机器,进入救援模式 4、重新安装grub grub-install --root-directory=/ /dev/sda 5、重启 130、删除/etc/fstab 和/boot目录的所有文件,并恢复之 注意:initrd文件使用mkinitrd命令生成 131、根文件系统在在逻辑卷分区,删除 /etc/fstab 和 /boot 目录下的所有文件,恢复 注意: vgchage -ay # 激活卷组 保证 boot 分区也已经挂载,否则在安装 grub ,找不到设备 132、提取出字符串Yd$C@M05MB%9&Bdh7dq+YVixp3vpw中的所有数字 echo "Yd$C@M05MB%9&Bdh7dq+YVixp3vpw" | awk -F "" '{ for(i=1;i<=NF;i++) {if ($i ~ /[0-9]/) printf "%d",$i}}' 133、解决DOS 攻击生产案例:根据web日志或者或者网络连接数,监控当某个IP 并发连接数或者短时内 PV 达到100 ,即调用防火墙命令 封掉对应的IP ,监控频率每隔5分钟。防火墙命令为:iptables -A INPUT -s IP -j REJECT #!/bin/bash IP=$(netstat -tnp | awk '/^tcp.*\/{split($5,array,":");status[array[1]]++}END{for(i in status) {printf "%-13s %d\n",i,status[i]}}' | awk '{if ($2>100) {print $1}}') if [ -z "$IP" ]; then echo "No DOS attack." >> /root/DOS.log fi for a in `echo "$IP"`; do iptables -A INPUT -s "$a" -j REJECT echo "$a Add to the firewall!" >> /root/DOS.log done * * * * * for i in {1..2}; do /works/scripts/DOS-NO.sh >> /root/DOS.log; sleep 30;done 134、启用SELinux 策略并安装httpd 服务,改变网站的默认主目录为/website, 添加SELinux 文件标签规则,使网站可访问 1、设定 SElinux 为 enforcing setenforce 1 2、修改 httpd 的家目录为 /web 3、访问目录下的资源,权限被拒绝 4、修改目录的类型标签为 httpd_sys_content_t chcon -R -t httpd_sys_content_t web/ 5、再次访问目录下的资源,可以访问 135、修改上述网站的http 端口为9527 ,增加 SELinux 端口标签使网站可访问 1、添加端口 semanage port -a -t http_port_t -p tcp 9527 2、查看是否添加 semanage port -l | grep http 3、通过端口访问站点资源 136、编写脚本selinux.sh ,实现开启或禁用SELinux 方法1:修改 /etc/selinux/config 或者 /etc/sysconfig/selinux 文件中的 SELINUX 字段为 SELINUX=disabled 方法2:修改 /boot/grub{2}/grub.conf{grub.cfg} 文件,给内核传递参数 selinux=0 sed 用法:添加内核参数 [ root@node0 /etc/sysconfig ]# cat /etc/default/grub | sed -n '/GRUB_CMDLINE_LINUX=/s/"$/ haha"/p' GRUB_CMDLINE_LINUX="crashkernel=auto rhgb quiet net.ifnames=0 haha" 137、awk去除重复行 cat test.tct | awk '{xue[$0]++}END{for(i in xue) {print i}}' ============================================================================================================================================== 138、启用相关的SELinux 布尔值,使上述网站的用户 student 的家目录可通过 http 访问 1、启用 SElinux vim /etc/selinux/config SELINUX=enforcing 2、重新启动机器 reboot 3、启用 http 访问本地用户家目录的功能 1、修改 httpd 配置文件 vim /etc/httpd/conf.d/userdir.conf # UserDir disabled # 注释掉这行 UserDir public_html # 启动此行配置 4、创建用户 http ,并设置密码 5、在 http 目录创建 public_html 目录 6、给 http 目录 x 权限,使得 apache 用户可以访问目录下的文件 7、重新启动 httpd 8、将 SElinux 启动关闭,测试是否有权限浏览目录下资源 9、查看 /var/www/html/index.html 文件 SElinux 的默认标签 10、给 /http/public_html/index.html 文件重新打 SElinux 标签 chcon -t httpd_sys_content_t public_html/index.html 11、重新使用浏览器访问即可以访问 ============================================================================================================================================== 139、expect 应用。ssh 免密登录脚本 1、脚本 #!/usr/bin/expect set timeout 60 set host 172.18.26.3 set username root set pswd xjw,./qwe spawn ssh $host -l $username expect { "(yes/no) ?" { send "yes\n" expect "password:" send "$pswd\n" } "password: " { send "$pswd\n" } } expect "#" send "uname\n" expect "Linux" send_user "Now you can do some operation on this terminal\n" interact # Sent to the remote server expect &> /dev/null < /dev/null < /var/www/cobbler/links/CentOS-6.9-x86_64 在/var/www/cobbler/ks-mirror/目录下生成安装目录树 2.生成一个默认的profile文件 3.在/var/lib/tftpboot/image目录下生成系统所对应的内核和ramdisk文件 6、生成profile文件 cobbler profile add --name=CentOS-7.3-Mini --distro=CentOS-7.3-x86_64 --kickstart=/var/lib/cobbler/kickstarts/ks-7.cfg 注: 1.修改 /var/lib/cobbler/kickstarts/ks-7.cfg 文件中安装目录树的路径位置 7、同步 cobbler sync systemctl restart cobblerd 5、部署不同的系统 cobbler profile add --name='CentOS-6.9-desktop' --distro=CentOS-6.9-x86_64 --kickstart=/var/lib/cobbler/kickstarts/ks-6.cfg cobbler profile remove --name=CentOS-6.9-x86_64 注: 修改 /var/lib/cobbler/kickstarts/ks-7.cfg 文件中安装目录树的路径位置 ============================================================================================================================================== 145、仅开放本机两个IP地址中的一个地址 172.16.0.X 上绑定的 sshd 和 vsftpd 服务给 172.16.0.0/16 网络中除了 172.16.0.0/24 网络中 的主机之外的所有主机,但允许 172.16.0.200 访问,每次的用户访问都要记录于日志文件中。注:其中X为学号 Note:TCP Wrapper进行限制。 # 检测 vsftpd 和 sshd 是否支持TCP wrapper 进行访问控制 $ ldd `which vsftpd` | grep libwrap libwrap.so.0 => /lib64/libwrap.so.0 (0x00007fd1af323000) $ ldd `which sshd` | grep libwrap libwrap.so.0 => /lib64/libwrap.so.0 (0x00007fd9f02a5000) # 添加规则进行限制 $ vim /etc/hosts.allow sshd@172.18.26.1:172.16.0.0/16 EXPECT (172.16.0.0/24 EXPECT 172.16.0.200):spawn /bin/echo %c access %s:%d >> /var/log/sshd.access.log ============================================================================================================================================== 146、http基于主机名的虚拟主机 Options Indexes FollowSymLinks AllowOverride None Require all granted ServerName book.xuejinwei.me DocumentRoot "/web/book" ServerAdmin jinweiayy@gmail.com ServerName file.xuejinwei.me DocumentRoot "/web/file" ServerAdmin jinweiayy@gmail.com ============================================================================================================================================== 147、跨网络记录日志 148、将日志记录到MySQL数据库,分离式部署 149、journalctl工具 ============================================================================================================================================== 150、CentOS6 LAMP:httpd-2.4.6(编译安装) php-5.4.16(作为httpd的模块运行) mairadb-5.5.52(二进制分发包) Wordpress 1、编译安装httpd-2.4.27 1、编译 ./configure \ --prefix=/usr/local/httpd24 \ --enable-modules=most \ --enable-mods-shared=all \ --enable-so \ --enable-proxy \ --enable-proxy-fcgi \ --enable-ssl \ --enable-static-htpasswd \ --enable-mpms-shared=all \ --enable-rewrite \ --disable-status \ --enable-deflate \ --enable-cgi \ --with-mpm=prefork \ --with-apr=/prog/apr \ --with-apr-util=/prog/apr-util Note: 在CentOS6上,需要安装较新版本的apr及apr-util,有两种方式安装apr及apr-util 1、先行编译apr和apr-util,然后再编译httpd时指定apr及apr-util的路径 --with-apr=/usr/local/apr/ --with-apr=/usr/local/ --with-apr-util=/usr/loca/apr-util/ --with-apr-util=PATH/usr/loca/ Note: CentOS6上,编译apr和apr-util时,不要指定路径 2、将apr和apr-util的源码目录复制到 httpd 源码目录下的 srclib 目录下,并重命名为 apr 和 apr-util --with-included-apr 3、根据报错信息解决依赖关系 4、卸载低版本的apr及apr-util 5、后续的配置 2、安装MariaDB-5.5.52 3、编译安装php ./configure \ --prefix=/usr/local/php \ --with-openssl \ --with-mysqli=/usr/local/mysql/bin/mysql_config \ --enable-mbstring \ --with-freetype-dir \ --with-jpeg-dir \ --with-png-dir \ --with-zlib \ --enable-sockets \ --with-apxs2=/usr/local/httpd24/bin/apxs \ --with-mcrypt \ --with-config-file-path=/etc \ --with-config-file-scan-dir=/etc/php.d \ --with-bz2 4、Wordpress ============================================================================================================================================== 151、CentOS7 编译安装最新版本 httpd(编译安装) php(作为httpd的模块运行) mairadb(二进制分发包) Wordpress (LAMP 分离式部署) Note: 1、编译安装apr-util时还依赖于yum install expat-devel包 2、httpd在CentOS7上的服务脚本 [Unit] Description=The Apache-2.4.28 HTTP Server After=network.target remote-fs.target nss-lookup.target Documentation=man:httpd(8) Documentation=man:apachectl(8) [Service] Type=simple #EnvironmentFile=/etc/sysconfig/httpd ExecStart=/usr/local/httpd24/bin/httpd $OPTIONS -DFOREGROUND ExecReload=/usr/local/httpd24/bin/httpd $OPTIONS -k graceful ExecStop=/bin/kill -WINCH ${MAINPID} # We want systemd to give httpd some time to finish gracefully, but still want # it to kill httpd after TimeoutStopSec if something went wrong during the # graceful stop. Normally, Systemd sends SIGTERM signal right after the # ExecStop, which would kill httpd. We are sending useless SIGCONT here to give # httpd time to finish. KillSignal=SIGCONT PrivateTmp=true [Install] WantedBy=multi-user.target 3、php-fpm systemd脚本 [Unit] Description=The PHP FastCGI Process Manager After=network.target [Service] Type=simple PIDFile=/usr/local/php/var/run/php-fpm.pid ExecStart=/usr/local/php/sbin/php-fpm --nodaemonize --fpm-config /usr/local/php/etc/php-fpm.conf ExecReload=/bin/kill -USR2 $MAINPID PrivateTmp=true [Install] WantedBy=multi-user.target 4、二进制安装MairaDB需要安装依赖库文件 yum install libaio ============================================================================================================================================== 152、FTP MariaDB数据库存储FTP账号密码 ============================================================================================================================================== 153、NFS用户映射的实现;NFS实现伪根的挂载 ============================================================================================================================================== 154、两台主机,nfs服务器,nfs客户端的用户登录时自动将用户的家目录挂载 [ root@node1 ~ ]# cat /etc/auto.master /home /etc/auto.xuekaixin1 [ root@node1 ~ ]# cat /etc/auto.xuekaixin1 xuekaixin1 -fstype=nfs,rw 172.18.26.1:/shareNFS/xuekaixin1/ ==============================================================================================================================================