Testing for a Text String

by mike on November 10, 2011

Test Text String
You can test a string from the command line. The test requires 3 parameters; the variable name($name), the test condition(=) and the value(fred).

name=fred; test $name = fred ; echo $?

The section of code shows a test to evaluate if a user has been deliberately blocked from logging into the server.  The user in the example, lionel, can be locked out using:
useradd lionel
usermod -L lionel

This command places a “!” in the second field of the /etc/shadow file.  That is why the grep searches for the user and  cuts out the second field “cut -d: -f2”, where it would be placed.  The echo command takes the output of the variable $USER and uses egrep to search for the string that is needed “!”.  The if…then clause tests and sends the appropriate email to the administrator.

# Test for Locked Account
USER=`grep ^"lionel" /etc/shadow | cut -d: -f2`
echo $USER | egrep ^"!"
if [ "$?" -ne "0" ];
echo "User Not Blocked" | mail -s "User Able to Login $(date)" $ADMIN; echo "User Can Login"
echo "User Blocked" | mail -s "User Unable to Login  $(date)" $ADMIN; echo "User Cannot Login"
exit 0

Comments on this entry are closed.

Previous post:

Next post: