| 1 | #!/bin/bash |
| 2 | # logon.sh: A quick 'n dirty script to check whether you are on-line yet. |
| 3 | |
| 4 | umask 177 # Make sure temp files are not world readable. |
| 5 | |
| 6 | |
| 7 | TRUE=1 |
| 8 | LOGFILE=/var/log/messages |
| 9 | # Note that $LOGFILE must be readable |
| 10 | #+ (as root, chmod 644 /var/log/messages). |
| 11 | TEMPFILE=temp.$$ |
| 12 | # Create a "unique" temp file name, using process id of the script. |
| 13 | # Using 'mktemp' is an alternative. |
| 14 | # For example: |
| 15 | # TEMPFILE=`mktemp temp.XXXXXX` |
| 16 | KEYWORD=address |
| 17 | # At logon, the line "remote IP address xxx.xxx.xxx.xxx" |
| 18 | # appended to /var/log/messages. |
| 19 | ONLINE=22 |
| 20 | USER_INTERRUPT=13 |
| 21 | CHECK_LINES=100 |
| 22 | # How many lines in log file to check. |
| 23 | |
| 24 | trap 'rm -f $TEMPFILE; exit $USER_INTERRUPT' TERM INT |
| 25 | # Cleans up the temp file if script interrupted by control-c. |
| 26 | |
| 27 | echo |
| 28 | |
| 29 | while [ $TRUE ] #Endless loop. |
| 30 | do |
| 31 | tail -n $CHECK_LINES $LOGFILE> $TEMPFILE |
| 32 | # Saves last 100 lines of system log file as temp file. |
| 33 | # Necessary, since newer kernels generate many log messages at log on. |
| 34 | search=`grep $KEYWORD $TEMPFILE` |
| 35 | # Checks for presence of the "IP address" phrase, |
| 36 | #+ indicating a successful logon. |
| 37 | |
| 38 | if [ ! -z "$search" ] # Quotes necessary because of possible spaces. |
| 39 | then |
| 40 | echo "On-line" |
| 41 | rm -f $TEMPFILE # Clean up temp file. |
| 42 | exit $ONLINE |
| 43 | else |
| 44 | echo -n "." # The -n option to echo suppresses newline, |
| 45 | #+ so you get continuous rows of dots. |
| 46 | fi |
| 47 | |
| 48 | sleep 1 |
| 49 | done |
| 50 | |
| 51 | |
| 52 | # Note: if you change the KEYWORD variable to "Exit", |
| 53 | #+ this script can be used while on-line |
| 54 | #+ to check for an unexpected logoff. |
| 55 | |
| 56 | # Exercise: Change the script, per the above note, |
| 57 | # and prettify it. |
| 58 | |
| 59 | exit 0 |
| 60 | |
| 61 | |
| 62 | # Nick Drage suggests an alternate method: |
| 63 | |
| 64 | while true |
| 65 | do ifconfig ppp0 | grep UP 1> /dev/null && echo "connected" && exit 0 |
| 66 | echo -n "." # Prints dots (.....) until connected. |
| 67 | sleep 2 |
| 68 | done |
| 69 | |
| 70 | # Problem: Hitting Control-C to terminate this process may be insufficient. |
| 71 | #+ (Dots may keep on echoing.) |
| 72 | # Exercise: Fix this. |
| 73 | |
| 74 | |
| 75 | |
| 76 | # Stephane Chazelas has yet another alternative: |
| 77 | |
| 78 | CHECK_INTERVAL=1 |
| 79 | |
| 80 | while ! tail -n 1 "$LOGFILE" | grep -q "$KEYWORD" |
| 81 | do echo -n . |
| 82 | sleep $CHECK_INTERVAL |
| 83 | done |
| 84 | echo "On-line" |
| 85 | |
| 86 | # Exercise: Discuss the relative strengths and weaknesses |
| 87 | # of each of these various approaches. |