开发者

bash - finding unexpected user accounts

I have a great line to list all the user accounts, but how do I tell if one of them is NOT expected to be in the list开发者_如何学运维.

cat /etc/passwd | grep "/home" | cut -d: -f1

fred 
barney
wilma
elroy_jetson

I don't expect Elroy Jetson to be in Bedrock, so I want to raise a flag. The only way I can think of to do it seems clumsy:

ALL_USERS_ARE_VALID="true"
for USER in `cat /etc/passwd | grep "/home" | cut -d: -f1`; do
  if [[ "$USER" == "fred" ]]; then
    #valid user
  elif [[ "$USER" == "barney" ]]; then
    #valid user
  elif [[ "$USER" == "wilma" ]]; then
    #valid user
  else
    ALL_USERS_ARE_VALID="false"
  fi
done

There's gotta be a better way...


:> cat expectedResidents
fred 
barney
wilma
:> cat /etc/passwd | grep "/home" | cut -d: -f1| fgrep -vf expectedResidents
elroy_jetson

fgrep means *file*grep, where file contains the targets you are searching for. Note that traditional fgrep only supports exact string matching (and the the -i ignore-case) option, so trailing spaces etc. in you searchlist file will cause problems. Using the -v option, as usual, means ignore lines that match the specified patterns. -f tells fgrep which file to use. Finally, for traditional fgreps (Sun, etc), there are limitings to how many lines can be in the searchlist file, so if this is for large production system, test, test, test ;-)

Depending on your OS, you may need to figure out if you need to use grep -F -vf ... or similar instead.

I hope this helps.


How would you expect the computer to know elroy shouldnt be in bedrock? If you have a list of "known" valid accounts, have a file of them, and do grep -v which says find whats not these..


A better way to write the chained if statements would be using a case construct as follows:

case "$USER" in
  fred|barney|wilma)
    # valid user
    ;;
  *)
    ALL_USERS_ARE_VALID="false"
esac


Instead of using multiple if statements, store your valid users in a file then do a comparison using comm.

Example:

$ cat valid_users # file containing valid users
fred 
barney
wilma

$ comm -23 <(cat /etc/passwd | grep "/home" | cut -d: -f1 | sort) <(sort valid_users)
elroy_jetson


You can use case in statement.

For e.g.:

case `cat /etc/passwd | grep "/home" | cut -d: -f1` in
        fred | barney | wilma )
                # valid
        ;;
        *)
                echo "Unallowed user";
                break;
        ;;
esac;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜