
Bash
1 前言
一个问题,一篇文章,一出故事。
笔者生产环境有台老旧的FTP服务器,用户众多。笔者希望每天获取昨天的活跃用户以及当前有效用户,于是整理此脚本。
2 最佳实践
2.1 创建管理脚本
vim ~/scripts/ftpUserStatus.sh
加入如下配置,
#!/bin/bash xferLog="/var/log/xferlog" passwdFile="/etc/passwd" mailTo="will@cmdschool.org" activeUsers="" noLockUsers="" yesterDay=`date "+%a %b %d.* %Y" -d '-1 day'` myDay=`date '+%d' -d '-1 day'` editDay="$(expr `date '+%d' -d '-1 day'` + 0)" if [ "$myDay" == "$editDay" ]; then grepStr="$yesterDay" else grepStr=`echo "$yesterDay" | awk -F' ' '{print $1" "$2}'`" $editDay.* "`echo "$yesterDay" | awk -F' ' '{print $4}'` fi IFS=$'\n' for i in $(egrep "$grepStr" "$xferLog" | egrep ".*i r.*"); do userName=`echo "$i" | sed -r 's/.*r (.*) ftp .*/\1/' | awk '$1=$1'` ipAddr=`echo "$i" | awk -F ' ' '{print $7}'` if [ `id $user 2>&1 | grep "No such user" | wc -l` == 1 ]; then continue fi if [ `echo $activeUsers | grep "$userName $ipAddr" | wc -l` -eq 1 ]; then continue fi activeUsers="$activeUsers"$'\n'" $userName $ipAddr" done users=`cat "$passwdFile" | cut -d":" -f1,6 | egrep -v ":/root|:/usr|:/bin|:/sbin|:/var|:/dev|:/etc|:/$" | cut -d':' -f1` for user in $users; do if [ `id $user 2>&1 | grep "No such user" | wc -l` == 1 ]; then continue fi if [ `passwd -S $user 2>&1 | grep "Password locked" | wc -l` == 1 ]; then continue fi noLockUsers="$noLockUsers"$'\n'" $user" done cat <<-EOF | mail -s 'Active user yesterday' "$mailTo" Hi All Script checked the logs and found that the following ftps users were active yesterday, $activeUsers Script checked system found below user password are not locked, $noLockUsers Note: This email is an automatically generated email from [CMDSCHOOL FTPS], please do not respond to this email. EOF
2.2 创建脚本触发
crontab -e
加入如下配置,
0 8 */1 * * sh ~/scripts/ftpUserStatus.sh
没有评论