第四周作业
1、统计出/etc/passwd文件中其默认shell为非/sbin/nologin的用户个数,并将用户都显示出来
方法一:
grep -v '/sbin/nologin$' /etc/passwd|awk -F: '{print $1}END{print NR}'
方法二:
sed -n '/\/sbin\/nologin$/!s@^\([^:]\+\).*@\1@p' /etc/passwd|awk '{count[$1]}END{for(user in count){print user}{print length(count)}}'
2、查出用户UID最大值的用户名、UID及shell类型
sort -t: -k3 -n /etc/passwd|tail -1|cut -d: -f1,3,7 --output-delimiter=" "
3、统计当前连接本机的每个远程主机IP的连接数,并按从大到小排序
netstat -nt|sed -n '1,2!p'|tr -s ':' ' '|awk '{count[$(NF-2)]++}END{for(ip in count){print ip,count[ip]}}'
4、编写脚本 createuser.sh,实现如下功能:使用一个用户名做为参数,如果 指定参数的用户存在,就显示其存在,否则添加之;显示添加的用户的id号等 信息
方法一
#!/bin/bash
USERNAME=$@
COLOR_PRE="\e[1;31m"
COLOR_END="\e[0m"
CMD="echo -e"
if [[ $# -eq 0 || $USERNAME == '' ]];then
$CMD "${COLOR_PRE}Usage `basename $0` USERNAME1 USERNAME2 USERNAME3 ...${COLOR_END}"
exit 1
fi
for NAME in $USERNAME;do
if id $NAME &>/dev/null;then
$CMD "${COLOR_PRE}User $NAME is exists${COLOR_END}"
else
if useradd $NAME &>/dev/null;then
getent passwd $NAME
else
$CMD "${COLOR_PRE}useradd: invalid user name $NAME${COLOR_END}"
fi
fi
done
方法二
if [ -z "$1" ];then
echo -e "\e[1;31mUsage `basename $0` username1 username2 userme3 ...\e[0m"
fi
while [ "$1" ];do
if id $1 &>/dev/null;then
echo -e "\e[1;31mUser $1 is exists\e[0m"
else
if useradd $1 &>/dev/null;then
getent passwd $1
else
echo -e "\e[1;31mUser $1 create fail\e[0m"
fi
fi
shift
done
5、编写生成脚本基本格式的脚本,包括作者,联系方式,版本,时间,描述等
vim ~/.vimrc
set autoindent
set showmatch
set incsearch
set shiftwidth=4
autocmd BufNewFile *.sh exec ":call SetTitle()"
func SetTitle()
if expand("%:e") == 'sh'
call setline(1,"#!/bin/bash")
call setline(2,"#")
call setline(3,"#********************************************************************")
call setline(4,"#Author: xuepeng")
call setline(5,"#QQ: 2242740665")
call setline(6,"#Date: ".strftime("%Y-%m-%d"))
call setline(7,"#FileName: ".expand("%"))
call setline(8,"#URL: https://my.oschina.net/u/4270793")
call setline(9,"#Description: The test script")
call setline(10,"#Copyright (C): ".strftime("%Y")." All rights reserved")
call setline(11,"#********************************************************************")
call setline(12,"")
endif
endfunc
autocmd BufNewFile * normal G