《linux命令行与shell脚本编程大全》第三版 - 核心笔记(4/4):编写实用工具脚本

《linux命令行与shell脚本编程大全》
全书4部分:
☆ 【1】linux命令行(1-10章)
☆ 【2】shell脚本编程基础(11-16章)
☆ 【3】高级shell脚本编程(17-23章)
☆ 【4】创建实用的脚本(24-26章):编写实用工具脚本



>>第24-26章丶编写脚本实用工具


归档--备份
1. 需要的功能:
tar归档命令
$ tar -zcf archive.tar.gz /home/Christine/Project/*.* 2>/dev/null
配置文件Files_To_Backup
$ cat Files_To_Backup
/home/Christine/Project
/home/Christine/Downloads
/home/Does_not_exist
/home/Christine/Documents
环境变量 CONFIG_FILE
为归档配置文件使用了一个变量,CONFIG_FILE。配置文件中每一条记录都会被读入。
2. 创建逐日归档文件的存放位置
$ sudo mkdir /archive
[sudo] password for Christine:
//创建一个集中归档仓库目录
$ sudo groupadd Archivers
$ sudo chgrp Archivers /archive
$ ls -ld /archive
drwxr-xr-x. 2 root Archivers 4096 Aug 27 14:10 /archive
$ sudo usermod -aG Archivers Christine
[sudo] password for Christine:
$ sudo chmod 775 /archive
$ ls -ld /archive
drwxrwxr-x. 2 root Archivers 4096 Aug 27 14:10 /archive
// 通过sudo命令或者创建一个用户组的方式,为需要在集中归档目录中创建文件的用户授权。
$ mv Files_To_Backup /archive/
$ ls /archive
Files_To_Backup
3. 创建按日归档的脚本
DATE=$(date +%y%m%d)
# Set Archive File Name
FILE=archive$DATE.tar.gz
# Set Configuration and Destination File
CONFIG_FILE=/archive/Files_To_Backup
DESTINATION=/archive/$FILE
/* 完整归档脚本Daily_Archive如下 */
#!/bin/bash
#
# Daily_Archive - Archive designated files & directories
########################################################
#
# Gather Current Date
#
DATE=$(date +%y%m%d)
#
# Set Archive File Name
#
FILE=archive$DATE.tar.gz
#
# Set Configuration and Destination File
#
CONFIG_FILE=/archive/Files_To_Backup
DESTINATION=/archive/$FILE
#
######### Main Script #########################
#
# Check Backup Config file exists
#
if [ -f $CONFIG_FILE ] # Make sure the config file still exists.
then # If it exists, do nothing but continue on.
    echo
else # If it doesn't exist, issue error & exit script.
    echo
    echo "$CONFIG_FILE does not exist."
    echo "Backup not completed due to missing Configuration File"
    echo
    exit
fi
#
# Build the names of all the files to backup
#
FILE_NO=1 # Start on Line 1 of Config File.
exec < $CONFIG_FILE # Redirect Std Input to name of Config File
#
read FILE_NAME # Read 1st record
#
while [ $? -eq 0 ] # Create list of files to backup.
do
        # Make sure the file or directory exists.
    if [ -f $FILE_NAME -o -d $FILE_NAME ]
    then
        # If file exists, add its name to the list.
        FILE_LIST="$FILE_LIST $FILE_NAME"
    else
        # If file doesn't exist, issue warning
        echo
        echo "$FILE_NAME, does not exist."
        echo "Obviously, I will not include it in this archive."
        echo "It is listed on line $FILE_NO of the config file."
        echo "Continuing to build archive list..."
        echo
    fi
    FILE_NO=$[$FILE_NO + 1] # Increase Line/File number by one.
    read FILE_NAME # Read next record.
done
#
#######################################
#
# Backup the files and Compress Archive
#
echo "Starting archive..."
echo
#
tar -czf $DESTINATION $FILE_LIST 2> /dev/null
#
echo "Archive completed"
echo "Resulting archive file is: $DESTINATION"
echo
#
exit
4. 运行按日归档的脚本
$ ls -l Daily_Archive.sh
-rw-rw-r--. 1 Christine Christine 1994 Aug 28 15:58 Daily_Archive.sh
$ chmod u+x Daily_Archive.sh
$ ./Daily_Archive.sh
/home/Does_not_exist, does not exist.
Obviously, I will not include it in this archive.
It is listed on line 3 of the config file.
Continuing to build archive list...
Starting archive...
Archive completed
Resulting archive file is: /archive/archive140828.tar.gz
$ ls /archive
archive140828.tar.gz Files_To_Backup
5. 创建按小时归档的脚本
$ sudo mkdir /archive/hourly
[sudo] password for Christine:
$ sudo chgrp Archivers /archive/hourly
$ ls -ld /archive/hourly/
drwxr-xr-x. 2 root Archivers 4096 Sep 2 09:24 /archive/hourly/
$ sudo chmod 775 /archive/hourly
$ ls -ld /archive/hourly
drwxrwxr-x. 2 root Archivers 4096 Sep 2 09:24 /archive/hourly
$ cat Files_To_Backup
/usr/local/Production/Machine_Errors
/home/Development/Simulation_Logs
$ mv Files_To_Backup /archive/hourly/
/* 按小时归档脚本代码演示 */
#!/bin/bash
#
# Hourly_Archive - Every hour create an archive
#########################################################
#
# Set Configuration File
#
CONFIG_FILE=/archive/hourly/Files_To_Backup
#
# Set Base Archive Destination Location
#
BASEDEST=/archive/hourly
#
# Gather Current Day, Month & Time
#
DAY=$(date +%d)
MONTH=$(date +%m)
TIME=$(date +%k%M)
#
# Create Archive Destination Directory
#
mkdir -p $BASEDEST/$MONTH/$DAY
#
# Build Archive Destination File Name
#
DESTINATION=$BASEDEST/$MONTH/$DAY/archive$TIME.tar.gz
#
########## Main Script ####################
[...]
// 一旦脚本Hourly_Archive.sh到了Main Script部分,就和Daily_Archive.sh脚本完全一样了。
6. 运行按小时归档的脚本
$ chmod u+x Hourly_Archive.sh
$ date +%k%M
1011
$ ./Hourly_Archive.sh
$ ls /archive/hourly/09/02/
archive1011.tar.gz
// 脚本正常运行,并创建了归档文件。现在可以把它放到cron表中了
crontab命令:linux定时运行脚本命令
http://blog.csdn.net/ziyunlong1984/article/details/38560621

管理用户账户
1. 获取正确的账户名
2. 创建函数获取正确的账户名
3. 验证输入的用户名
4. 确定账户是否存在
5. 删除属于账户的进程
6. 查找属于账户的文件
7. 删除账户
/* 完整的Delete_User.sh脚本代码 */
#!/bin/bash
#
#Delete_User - Automates the 4 steps to remove an account
#
###############################################################
# Define Functions
#
#####################################################
function get_answer {
#
	unset ANSWER
		ASK_COUNT=0
#
		while [ -z "$ANSWER" ] #While no answer is given, keep asking.
			do
				ASK_COUNT=$[ $ASK_COUNT + 1 ]
#
					case $ASK_COUNT in #If user gives no answer in time allotted
					2)
					echo
					echo "Please answer the question."
					echo
					;;
			3)
				echo
				echo "One last try...please answer the question."
				echo
				;;
			4)
				echo
				echo "Since you refuse to answer the question..."
				echo "exiting program."
				echo
#
				exit
				;;
			esac
#
				echo
#
				if [ -n "$LINE2" ]
					then #Print 2 lines
						echo $LINE1
						echo -e $LINE2" \c"
				else #Print 1 line
					echo -e $LINE1" \c"
						fi
#
# Allow 60 seconds to answer before time-out
						read -t 60 ANSWER
						done
# Do a little variable clean-up
						unset LINE1
						unset LINE2
#
} #End of get_answer function
#
#####################################################
function process_answer {
#
	case $ANSWER in
		y|Y|YES|yes|Yes|yEs|yeS|YEs|yES )
# If user answers "yes", do nothing.
		;;
	*)
# If user answers anything but "yes", exit script
		echo
		echo $EXIT_LINE1
		echo $EXIT_LINE2
		echo
		exit
		;;
	esac
#
# Do a little variable clean-up
#
		unset EXIT_LINE1
		unset EXIT_LINE2
#
} #End of process_answer function
#
##############################################
# End of Function Definitions
#
############# Main Script ####################
# Get name of User Account to check
#
echo "Step #1 - Determine User Account name to Delete "
echo
LINE1="Please enter the username of the user "
LINE2="account you wish to delete from system:"
get_answer
USER_ACCOUNT=$ANSWER
#
# Double check with script user that this is the correct User Account
#
LINE1="Is $USER_ACCOUNT the user account "
LINE2="you wish to delete from the system? [y/n]"
get_answer
#
# Call process_answer funtion:
# if user answers anything but "yes", exit script
#
EXIT_LINE1="Because the account, $USER_ACCOUNT, is not "
EXIT_LINE2="the one you wish to delete, we are leaving the script..."
process_answer
#
################################################################
# Check that USER_ACCOUNT is really an account on the system
#
USER_ACCOUNT_RECORD=$(cat /etc/passwd | grep -w $USER_ACCOUNT)
#
	if [ $? -eq 1 ] # If the account is not found, exit script
	then
	echo
	echo "Account, $USER_ACCOUNT, not found. "
	echo "Leaving the script..."
	echo
	exit
	fi
#
	echo
	echo "I found this record:"
	echo $USER_ACCOUNT_RECORD
#
	LINE1="Is this the correct User Account? [y/n]"
	get_answer
#
#
# Call process_answer function:
# if user answers anything but "yes", exit script
#
	EXIT_LINE1="Because the account, $USER_ACCOUNT, is not "
	EXIT_LINE2="the one you wish to delete, we are leaving the script..."
	process_answer
#
##################################################################
# Search for any running processes that belong to the User Account
#
	echo
	echo "Step #2 - Find process on system belonging to user account"
	echo
#
	ps -u $USER_ACCOUNT >/dev/null #Are user processes running?
#
	case $? in
	1) # No processes running for this User Account
#
	echo "There are no processes for this account currently running."
	echo
	;;
	0) # Processes running for this User Account.
# Ask Script User if wants us to kill the processes.
#
	echo "$USER_ACCOUNT has the following processes running: "
	echo
	ps -u $USER_ACCOUNT
#
	LINE1="Would you like me to kill the process(es)? [y/n]"
	get_answer
#
	case $ANSWER in
	y|Y|YES|yes|Yes|yEs|yeS|YEs|yES ) # If user answers "yes",
# kill User Account processes.
#
	echo
	echo "Killing off process(es)..."
#
# List user processes running code in variable, COMMAND_1
	COMMAND_1="ps -u $USER_ACCOUNT --no-heading"
#
# Create command to kill proccess in variable, COMMAND_3
	COMMAND_3="xargs -d \\n /usr/bin/sudo /bin/kill -9"
#
# Kill processes via piping commands together
	$COMMAND_1 | gawk '{print $1}' | $COMMAND_3
#
	echo
	echo "Process(es) killed."
	;;
	*) # If user answers anything but "yes", do not kill.
	echo
	echo "Will not kill the process(es)"
	echo
	;;
	esac
	;;
	esac
#################################################################
# Create a report of all files owned by User Account
#
	echo
	echo "Step #3 - Find files on system belonging to user account"
	echo
	echo "Creating a report of all files owned by $USER_ACCOUNT."
	echo
	echo "It is recommended that you backup/archive these files,"
	echo "and then do one of two things:"
	echo " 1) Delete the files"
	echo " 2) Change the files' ownership to a current user account."
	echo
	echo "Please wait. This may take a while..."
#
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 "Report is complete."
	echo "Name of report: $REPORT_FILE"
	echo "Location of report: $(pwd)"
	echo
####################################
# Remove User Account
	echo
	echo "Step #4 - Remove user account"
	echo
#
	LINE1="Remove $USER_ACCOUNT's account from system? [y/n]"
	get_answer
#
# Call process_answer function:
# if user answers anything but "yes", exit script
#
	EXIT_LINE1="Since you do not wish to remove the user account,"
	EXIT_LINE2="$USER_ACCOUNT at this time, exiting the script..."
	process_answer
#
	userdel $USER_ACCOUNT #delete user account
	echo
	echo "User account, $USER_ACCOUNT, has been removed"
	echo
#
exit
测试脚本:
$ chmod u+x Delete_User.sh
$ sudo ./Delete_User.sh
// 现在已经拥有了一个在删除用户账户时能够辅助你的脚本实用工具。更妙的是你还可以修改它来满足组织的需要!

监测磁盘空间
/* 脚本源码 */
#!/bin/bash
#
# Big_Users - Find big disk space users in various directories
###############################################################
# Parameters for Script
#
CHECK_DIRECTORIES=" /var/log /home" #Directories to check
#
############## Main Script #################################
#
DATE=$(date '+%m%d%y') #Date for report file
#
exec > disk_space_$DATE.rpt #Make report file STDOUT
#
echo "Top Ten Disk Space Usage" #Report header
echo "for $CHECK_DIRECTORIES Directories"
#
for DIR_CHECK in $CHECK_DIRECTORIES #Loop to du directories
do
echo ""
echo "The $DIR_CHECK Directory:" #Directory header
#
# Create a listing of top ten disk space users in this dir
du -S $DIR_CHECK 2>/dev/null |
sort -rn |
sed '{11,$D; =}' |
sed 'N; s/\n/ /' |
gawk '{printf $1 ":" "\t" $2 "\t" $3 "\n"}'
#
done #End of loop
#
exit
测试脚本:
$ sudo bash Big_Users.sh
$ cat disk_space_090314.rpt

发送消息脚本
/* 脚本演示 */
#!/bin/bash
#
#mu.sh - Send a Message to a particular user
#############################################
#
# Save the username parameter
#
muser=$1
#
# Determine if user is logged on:
#
logged_on=$(who | grep -i -m 1 $muser | gawk '{print $1}')
#
if [ -z $logged_on ]
then
    echo "$muser is not logged on."
    echo "Exiting script..."
    exit
fi
#
# Determine if user allows messaging:
#
allowed=$(who -T | grep -i -m 1 $muser | gawk '{print $2}')
#
if [ $allowed != "+" ]
then
    echo "$muser does not allowing messaging."
    echo "Exiting script..."
    exit
fi
#
# Determine if a message was included:
#
if [ -z $2 ]
then
    echo "No message parameter included."
    echo "Exiting script..."
    exit
fi
#
# Determine if there is more to the message:
#
shift
#
while [ -n "$1" ]
do
    whole_message=$whole_message' '$1
    shift
done
#
# Send message to user:
#
uterminal=$(who | grep -i -m 1 $muser | gawk '{print $2}')
#
echo $whole_message | write $logged_on $uterminal
#
exit
测试脚本:
$:' ./mu.sh Timothy The boss is coming! Look busy!
用户Timothy在自己的终端上接收到下面的消息:
Message from christine@server01 on tty2 at 10:30 ...
The boss is coming! Look busy!
EOF

web端获取格言脚本--wget
/* 脚本演示 */
#!/bin/bash
#
# Get a Daily Inspirational Quote
#####################################
#
# Script Variables ####
#
quote_url=www.quotationspage.com/qotd.html
#
# Check url validity ###
#
check_url=$(wget -nv --spider $quote_url 2>&1)
#
	if [[ $check_url == *error404* ]]
	then
	echo "Bad web address"
	echo "$quote_url invalid"
	echo "Exiting script..."
	exit
	fi
#
# Download Web Site's Information
#
	wget -o /tmp/quote.log -O /tmp/quote.html $quote_url
#
# Extract the Desired Data
#
	sed 's/<[^>]*//g' /tmp/quote.html |
	grep "$(date +%B' '%-d,' '%Y)" -A2 |
	sed 's/>//g' |
	sed '/ /{n ; d}' |
	gawk 'BEGIN{FS=" "} {print $1}' |
	tee /tmp/daily_quote.txt > /dev/null
#
exit
测试脚本:
$:' ./get_quote.sh
$:' cat /tmp/daily_quote.txt
Selected from Michael Moncur's Collection of Quotations
- September 23, 2015
Horse sense is the thing a horse has which keeps it from
betting on people. W. C. Fields (1880 - 1946)




2017.07.09
全书完... ...
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

姜源Jerry

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值