编写脚本实用工具
1、查看哪个文件占用最大 查看前十名磁盘空间用户,到第11行,sed会删除列表的剩余部分,然后给列表中每行一个行号。要让行号和磁盘空间文本 位于同一行,用N命令将文本行合并在一行。然后用gawk命令清理,在行号后,加一个冒号(:),还给每行文本的输出行中的每个字段放了一个制表符。这样就生成了一个格式精致的前十名 磁盘空间用户列表了 1 2 3 4 5 6 7 8 9 10 11 [root@digitcube-test1qingyun]#du-Sh/home/*|sort-rn|sed '{11,$D;=}' |sed 'N;s/\n//' |gawk '{print$1":""\t"$2"\t"$3"\n"}' 1 :1020K/home/nexus/sonatype-work/nexus/storage/central/org/springframework/spring-context/ 2.5 . 6 2 :1020K/home/nexus/sonatype-work/nexus/storage/central/ant/ant/ 1.6 . 5 3 :1012K/home/nexus/sonatype-work/nexus/storage/central/org/springframework/spring-beans/ 2.5 . 6 4 :1012K/home/maven/.m2/repository/org/xerial/snappy/snappy-java/ 1.0 . 4.1 5 :1008K/home/home/hadoop/jstorm/dc_topology/tmp/org/apache/hadoop/hdfs/server/namenode 6 :1008K/home/home/hadoop/hadoop- 1.0 . 4 /docs/api/org/apache/hadoop/mapreduce 7 :1008K/home/hadoop/sam/datatask/doubixiyou_1290 8 :1008K/home/hadoop/hadoop- 1.0 . 4 /docs/api/org/apache/hadoop/mapreduce 9 :1004K/home/home/hadoop/jstorm/dc_topology/tmp/kafka/log 10 :1000K/home/maven/.m2/repository/org/xerial/snappy/snappy-java/ 1.0 . 3.2 2、创造加了日期的前十名磁盘空间用户报告的脚本 1 <br> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 [root@digitcube-test1tmp] #vimfile_siz.sh #!/bin/bash #Big_User-findbigdiskspaceusersinvariousdirecotries #ParametersforScript # CHECK_DIRECTORIES= "/var/log/home" #direcotriestocheck # ######################MainScript########################### # DATE=` date +%m%d%y` #Dateforreportfile exec >space_file_$DATA.rpt # # echo "TopTenDiskSpaceUsage" #Reportheaderforwholereport echo "for$CHECK_DIRECTORIESDirecotries" # for DIR_CHECK in $CHECK_DIRECTORIES #looptodudirectories do echo "" echo "The$DID_CHECKDirectory:" #Titleheaderforeachdirecotry # #Createalistingoftoptendiskspaceusers du -S$DIR_CHECK2> /dev/null | sort -rn| sed '{11,$D;=}' | sed 'N;s/\n//' | gawk '{printf$1":""\t"$2"\t"$3"\n"}' # done exec > /tmp/test .txt 2、创建按日期归档的脚本 归档文件,让脚本读取file_to_backup里面每个目录或文件,用到一个简单read命令,来读取该文件中的每一条记录。 exec<$CONFIG_FILE read FILE_NAME 为归档配置文件以及从file_to_backup读取每条记录都用了变量.只要read命令在配置文件中发现还有记录要读,它就会在?变量中返回一退出状态码0表示成功,以while循环的测试条件来读取file_to_backup的所有记录 while [ $? -eq 0 ] do .... read FILE_NAME done 一旦read命令到了末尾,返回一个非0状态码,脚本会退出while循环 1 2 3 4 5 [root@digitcube-test1tmp]#cat/home/qingyun/file_to_backup /home/qingyun/test1 /home/qingyun/test2 /home/qingyun/test3 /home/qingyun/love 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 [root@digitcube-test1tmp]#vimDaily_Archive.sh # #SetConfigurationandDestinationFile # CONFIG_FILE=/home/qingyun/file_to_backup DESTINATION=/home/qingyun/$FILE # ##############MainScript###################### # #CheckBackupConfigfileexists # if [-f$CONFIG_FILE]#Makesuretheconfigfilestillexits then echo else echo echo "$CONFIG_FILEdoesnotexist" echo "BackupnotcompletedduetomisstingConfigurationfile" echo exit fi # #Buildthenameofallthefilestobackup # FILE_NO= 1 #Startonline 1 ofConfigFile exec<$CONFIG_FILE#RedirectStdInputtonameofConfigFile # readFILE_NAME#Read1strecord # while [$?-eq 0 ]#Createlistoffilestobackup do #Makesurethefileordirectoryexists if [-f$FILE_NAME] then #Iffileexists.additsnametothelist echo$FILE_NAME FILE_LIST= "$FILE_LIST$FILE_NAME" else #Iffiledoesn'texist.issuewarning echo echo "$FILE_NAME,doesnotexist" echo "Obviously,Iwillnotincludeiinthisarchive" echo "Itislistedonline$FILE_NOoftheconfigfile." echo "Continuingtobuildarchivelist...." echo fi # FILE_NO=$[$FILE_NO+ 1 ]#IncreaseLine/Filenumberbyon readFILE_NAME#Readnextrecord done ############################################################ # #BackupthefilesandCompressArchive # tar-czf$DESTINATION$FILE_LIST 2 >/dev/ null 按小时归档的脚本 归档目录包含了跟一年中的各个月份对应的目录,将月的序号作为目录名。而每月的目录中又包含跟一个月中的各天对应的目录(用天序号来作为目录)。这样只用给每个归档文件加时间戳然后将它他们放到跟日和月份对应的目录就行了。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 [root@digitcube-test1tmp]#vimHourly_Archive.sh #!/bin/bash # #Hourly_Archive-Everyhourcreateanarhive ############################################## # #SetConfigureationFile # CONFIG_FILE=/home/qingyun/hourly/file_to_backup # #SetBaseArchiveDestinationLocation # BASEDEST=/home/qingyun/hourly # #GatherCurrentDay.Month&Time # DAY=`date+%d` MONTH=`date+%m` TIME=`date+%k%M` # #CreateArchiveDestinationDirectory # mkdir-p$BASEDEST/$MONTH/$DAY DESTINATION=$BASEDEST/$MONTH/$DAY/archive.$TIME.tar.gz # #BuildArchvieDestinationfileName # ###############MAINScript##################################### #CheckBackupConfigfileexists # if [-f$CONFIG_FILE]#Makesuretheconfigfilestillexits then echo else echo echo "$CONFIG_FILEdoesnotexist" echo "BackupnotcompletedduetomisstingConfigurationfile" echo exit fi # #Buildthenameofallthefilestobackup # FILE_NO= 1 #Startonline 1 ofConfigFile exec<$CONFIG_FILE#RedirectStdInputtonameofConfigFile # readFILE_NAME#Read1strecord # while [$?-eq 0 ]#Createlistoffilestobackup do #Makesurethefileordirectoryexists if [-f$FILE_NAME] then #Iffileexists.additsnametothelist echo$FILE_NAME FILE_LIST= "$FILE_LIST$FILE_NAME" else #Iffiledoesn'texist.issuewarning echo echo "$FILE_NAME,doesnotexist" echo "Obviously,Iwillnotincludeiinthisarchive" echo "Itislistedonline$FILE_NOoftheconfigfile." echo "Continuingtobuildarchivelist...." echo fi # FILE_NO=$[$FILE_NO+ 1 ]#IncreaseLine/Filenumberbyon readFILE_NAME#Readnextrecord done ############################################################ # #BackupthefilesandCompressArchive # tar-czf$DESTINATION$FILE_LIST 2 >/dev/ null 3、管理用户账号 脚本进入删除用户4个步聚: 1、获得并确认用户账户名, 2、查找和终止用户的进程, 3、创建一份属于该用户账号的所有文件报告, 4、最终删除用户账号 用到判断参数 -z:字符长度0,为真 -n:字符长度非0,为真 unset:删除变量和函数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 [root@logicservertmp]#vimDelte_user.sh #!/bin/bash # #Delte_User-Automatesthe 4 steptoremoveanaccount # #DefinFunctions # ########################################################## function get_answer{ unsetANSWER ASK_COUNT= 0 # while [-z "$ANSWER" ]# while noanwser is given.keeipasking do ASK_COUNT=$[$ASK_COUNT+ 1 ] # case $ASK_COUNT in #Ifusergivesnoanswer in timeallotted 2 ) echo echo "Pleaseanswerthequestion" echo ;; 3 ) echo echo "Onelasttry.....pleaseanswerthequestion." echo ;; 4 ) echo echo "Sinceyourefusetoanswerthequestion.." echo "exitingprogram." # exit ;; esac # echo # if [-n "$LINE2" ] then#print 2 lines echo$LINE1 echo-e$LINE2 "\c" else echo-e$LINE1 "\c" fi # #Allow 60 secondtoanswerbefortime-out read-t 60 ANSWER done #Doalittel var iableclean-up unsetLINE1 unsetLINE2 # }#Endofget_answer function # ##################################################################### function process_answer{ # case $ANSWER in y|Y|YES|yes|Yes|yEs|yeS|YEs|yES) #Ifuseranswer "yes" . do noting ;; *) #Ifuseransweranythingbut "yes" .exitscript echo echo$EXIT_LINE1 echo$EXIT_LINE2 echo exit ;; esac # #Doalittle var iableclean-up # unsetEXIT_LINE1 unsetEXIT_LINE2 # }#Endofprocess_answerfuntion # ################################################################### #EndofFunctionDefinitions # ######################MianScript################################# #GetnameofUserAccounttocheck # echo "Step$1-DeterminUserAccountnametoDelete" echo LINE1= "pleaseentertheusernameoftheuser" LINE2= "Accountyouwishtodeletefromsystem:" get_answer USER_ACCOUNT=$ANSWER # #Doublecheck with scriptuserthat this is thecoreectUserAccount # LINE1= "Is$USER_ACCOUNTtheuseraccount" LINE2= "Youwishtodeletefromthesystem?[y/n]" get_answer # #Callprocess_answerfuntion: #Ifuseransweranythingbut "yes" .exitscript # EXIT_LINE1= "Becausetheaccount,$USER_ACCOUNT,isnot" EXIT_LINE2= "Theoneyouwishtodelete.weareleavingthescript..." process_answer # ############################################################################ # USER_ACCOUNT_RECORD=$(cat/etc/passwd|grep-w$USER_ACCOUNT) # if [$?-eq 1 ]#Iftheaccount is notfound.exitscript then echo echo "Account,$USER_ACCOUNT.notfound" echo "Leavingthescript..." echo exit fi # echo "Ifoundthisrecord:" echo$USER_ACCOUNT_RECORD echo # LINE1= "IsthisthecorrectUserAccount?[y/n]" get_answer # # #Callprocess_answer function : #Ifuseranswersanythingbut "yes" ,exitscript # EXIT_LINE1= "Becausetheaccount,$USER_ACCOUNT,isnot" EXIT_LINE2= "Theoneyouwishtodelete.weareleavingthescript...." process_answer # ##################################################################### #Search for anyrunningprocessesthatbelongtotheUserAccount # echo echo "Step#2-Findprocessonsystembelogingtouseraccount" echo echo "$USER_ACCOUNThasthefollowingprocessrunning:" echo # ps-u$USER_ACCOUNT#Listuserprocessesrunning. case $? in 1 )#Noprocessesrunning for this UserAccount # echo "Therearenoprocessesforthisaccountcurrentlyrunning." echo ;; 0 )#Processesrunning for this UserAccount. #AskScriptUser if wantsustokilltheprocesses. # unsetANSWER LINE1= "Wouldyoulikemetokillmeprocess(es)?[y/n]" get_answer # case $ANSWER in y|Y|YES|yes|Yes|yEs|yeS|YEs|yES)#Ifuseranswers "yes" #KillUserAccountprocesses. # echo # #Clean-uptempfileuponsignals trap "rm$USER_ACCOUNT_Running_Process.rpt" SIGTERMSIGINTSIGQUIT # #Listuserprocessesrunning ps-u$USER_ACCOUNT>$USER_ACCOUNT_Running_Process.rpt # exec<$USER_ACCOUNT_Running_Process.rpt#MakereportStdInput readUSER_PROCESS_REC#Firstrecordwillbeblank readUSER_PROCESS_REC # while [$?-eq 0 ] do #obtainPID USER_PID=`echo$USER_PROCESS_REC|cut-d "" -f1` kill- 9 $USER_PID echo "Killedprocess$USER_PID" readUSER_PROCESS_REC done # echo rm$USER_ACCOUNT_Running_Process.rpt#Removetempreport. ;; *)#Ifuseransweranythingbut "yes" , do notkill echo echo "Willnotkilltheprocess(es)" echo ;; esac ;; esac ########################################################################## #CreateareportofallfilesownedbyUserAccount # echo echo "Step#3-Findfilesonsystembelongingtouseraccount" echo echo "Creatingareportofallfilesownedby$USER_ACCOUNT." echo echo "Itisrecommendedthatyoubackup/archivethesefiles." echo "andthendooneoftwothings;" echo "1)Deletethefiles" echo "2)Changethefiles'ownershiptoacurrentuseraccount." echo echo "Pleasewait.Thismaytakeawhile...." echo echo "Pleasewait.Thismaytakeawhile...." # REPORT_DATE=`date+%y%m%d` REPORT_FILE=$USER_ACCOUNT "_files_" $REPORT_DATE ".RPT" # find/-user$USER_ACCOUNT>$REPORT_FILE 2 >/dev/ null # echo echo "Reportiscommlete." echo "Nameofreport:$REPORT_FILE" echo "Locationofreport:`pwd`" echo ############################################ #RemoveUserAccount echo echo "Step#4-Removeuseraccount" echo # LINE1= "Doyouwishtoremove$USER_ACCOUNTaccountfromsystem?[y/n]" get_answer # #Callprocess_answer function : # if useransweranythinbut "yes" .exitscript # EXIT_LINE1= "Sinceyoudonotwishtoremovetheuseraccount." EXIT_LINE2= "$USER_ACCOUNTatthistime.exitingthescript..." process_answer # userdel$USER_ACCOUNT# delete useraccount echo echo "Useraccount.$USER_ACCOUNT.hasbeenremoved" echo 本文转自 zouqingyun 51CTO博客,原文链接:http://blog.51cto.com/zouqingyun/1696340,如需转载请自行联系原作者