OS X: 实用脚本程序(bash scripts)系列-14

显示所有服务是否开启的状态(System Preferences->Sharing)

运行logger.sh程序,

#!/bin/bash
# Logger, software to display information about the "divisions" in Mac OS X [10.6]
# 2011-05-31 / Peter Morller, Computer Science
# Version 0.2
# Moved to / usr / bin (from / bin)
# 2011-06-13,14: bugfix


help() {
  echo
  echo "Usage: $0 [-u]"
  echo
  echo "-u: Update the script"
  echo
  echo "If run by root: datafiles in /Library/OpenPorts are created, but no output."
  echo "If run by any other user: output is displayed based on those datafiles."
  echo
  echo "This script is supposed to be used in conjunction with a launchd-component, se.lth.cs.open_ports,"
  echo "that creates the datafiles in /Library/OpenPorts every two minutes. The use of GeekTool to display the result"
  echo "is also part of the idea behind this script!"
  exit 0
}

# Locating an IP address. Publishes: 
locate_ip() {
  curl http://www.geoiptool.com/en/?IP=$1 2>/dev/null | awk '
  /<td.*>(Country:|City)/ {
  record="t";gsub("[\t ]*<[^>]*>",""); printf("%-1s ",$0);next;
  }
  record == "t" { gsub("[\t ]*<[^>]*>[\t ]*","");print $0;record="f";next}
  {next}
  END{print ""}'
  }

# Check if $ IP's $ IP_CACHE and dig out $ $ Country and City
# If not, look it up and update $ IP_CACHE
# Provides: $ $ Country & City (and updates $ IP_CACHE) 
check_ip() {
  if [ "`grep "$IP:" $IP_CACHE`" ]; then
    #say "Found address in cache"
    City=`grep "$IP:" $IP_CACHE | cut -d: -f3`
    Country=`grep "$IP:" $IP_CACHE | cut -d: -f2`
  else
    #say "Performing a lookup"
    locate_ip "$IP" | iconv --from-code=ISO-8859-1 --to-code=UTF-8 > "$IP_LOCATE_CACHE"
    City=`grep "City" "$IP_LOCATE_CACHE" | awk '{ print $2" "$3" "$4 }' | sed 's/\ *$//g'`
    Country=`grep "Country:" "$IP_LOCATE_CACHE" | awk '{ print $2" "$3" "$4 }' | sed 's/\ *$//g'`
    echo "$IP:$Country:$City" >> "$IP_CACHE"
  fi
  }

# Call up the DNS for $ IP
# Provides: $ HOSTNAME
# Also take care of the private addresses:
# • 10.x.x.x
# • 172.16.x.x
# • 192.168.x.x
# As well as self-assigned address:
# 169.254.x.x 
GetDNS() {
 PrivateAddress="No"
 if [ "$(echo "$IP" | cut -d\. -f1)" = "10" ]; then
   HOSTNAME="Private address ($IP)"
   PrivateAddress="Yes"
 elif [ "$(echo "$IP" | cut -d\. -f1,2)" = "172.16" ]; then
   HOSTNAME="Private address ($IP)"
   PrivateAddress="Yes"
 elif [ "$(echo "$IP" | cut -d\. -f1,2)" = "192.168" ]; then
   HOSTNAME="Private address ($IP)"
   PrivateAddress="Yes"
 elif [ "$(echo "$IP" | cut -d\. -f1,2)" = "169.254" ]; then
   HOSTNAME="Self-assigned address ($IP)"
   PrivateAddress="Yes"
 else
   HOSTNAME_tmp=`host $IP`
   ERR="$?"
   if [ ! "$ERR" = "0" ]; then
     HOSTNAME="$IP could not be looked up! (DNS timeout)"
   else
     HOSTNAME=`echo $HOSTNAME_tmp | awk '{ print $NF }' | sed 's/\.$//g'`
   fi
 fi
 }


# Exit if there are already running a open_ports 
if [ "`ps -ef | grep [l]ogger.sh | wc -l`" -gt "2" ]; then
  echo "\"logger.sh\" already running -- will exit now"
  exit 0
fi


# Read parameters: 
while getopts ":hu" opt; do
case $opt in
    u ) fetch_new=t;;
 \?|h ) help;;
esac
done


# Default values:
# PREFIX pointing out where all data files are stored. Change this if 
PREFIX="/Library/com.any/Logger"
# IP_CACHE is a growing list of IP addresses and their geographical locations. Built on post
# Because this file is used by other scripts, is it not open the Ports directory 
IP_CACHE="/Library/com.any/ip_cache.txt"
# IP_LOCATE_CACHE save the geographic locations of the computer's exterior (external) address. Temporary 
IP_LOCATE_CACHE="$PREFIX"/ip_locate_cache.txt
SharingFile="$PREFIX"/Sharing.txt
# Logfile for Apple File Sharing
AFS_Log=/Library/Logs/AppleFileService/AppleFileServiceAccess.log
# FieldSeparator indicates IFS file 
FieldSeparator="_"
# String for printf (used for printing EST Relations) 
Formatstring="%-23s%-4s"
# String for printf (used to print lists, links) 
FormatstringListen="%-6s%-6s%-18s%-15s%6s%2s%-17s%-15s"

# (The colors can be found on http://en.wikipedia.org/wiki/ANSI_escape_code, http://graphcomp.com/info/specs/ansi_col.html etc.) 
Reset="\e[0m"
ESC="\e["
RES="0"
BoldFace="1"
ItalicFace="3"
UnderlineFace="4"
SlowBlink="5"
BlackBack="40"
RedBack="41"
BlueBack="44"
WhiteBack="47"
BlackFont="30"
RedFont="31"
GreenFont="32"
YellowFont="33"
BlueFont="34"
CyanFont="36"
WhiteFont="37"

# Reset all colors 
BGColor="$RES"
Face="$RES"
FontColor="$RES"

# Determine defaulinterface and corresponding IP address 
DEFAULT_INTERFACE=`route get www.lu.se | grep interface | awk '{ print $2 }'`
IP_ADDRESS=`ifconfig $DEFAULT_INTERFACE | grep "inet " | awk '{ print $2 }'`
#DOMAIN="`ipconfig getpacket en0 | grep 'domain_name (string)' | awk '{ print $3 }'`"
#DOMAIN="`hostname | cut -d\. -f2-7`"
Host_Name="$(hostname)"
Machine_Name="$(hostname -s)"
DOMAIN="${Host_Name##$Machine_Name.}"
# Check where in the world localhost is: 
IP="$IP_ADDRESS"
check_ip
Localhost_Location=" ($Country, $City)"


# <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>
#
# Create input data (if we drive through launchd, $ USER = nil or root), then stop 
if [ "$USER" = "root" -o -z "$USER" ]; then
#set -x
  rm "$SharingFile"
  
  ########################
  ## Check AFP 
  ########################
  AFP_Share="$(defaults read /var/db/launchd.db/com.apple.launchd/overrides com.apple.AppleFileServer 2> /dev/null | grep [D]isabled | awk '{print $3}' | sed 's/;//g')"
  AFP_Verification="$(lsof -i :548)"
  if [ "$AFP_Share" = "0" -a -n "$AFP_Verification" ]; then
    Share_AFP="t"
  else
    Share_AFP="f"
  fi
  AFP_Verification="$(lsof -i :548)"
  echo "Apple file share_$(if [ "$Share_AFP" = "t" ]; then echo "ON"; else echo "OFF"; fi)" > "$SharingFile"
  
  # Check the logs and report
  # Typical logfile entry (login and logout) set like this:
  # IP 90230245202 - - [17/Dec/2010: 09:08:53 0100] "Login Johnnie" 0 0 0
  # IP 90230245202 - - [17/Dec/2010: 10:16:09 0100] "Logout Johnnie" 0 0 0

  # 1. Is log file? 
  if [ -f "$AFS_Log" ]; then
    # 2. OK, it's there. Is any assembly started? 
    if [ -n "$(ps -ef | grep [A]ppleFileServer)" ]; then
      # 3. Go through the active links 
      for IP in $(lsof -i :548 -n | grep EST | cut -d\> -f2 | cut -d: -f1); do 
        # 4. Locate the last log from the machine 
        LastLine="$(grep " $IP " $AFS_Log | grep \"Login\  | tail -1)"
        AuthUser="$(echo $LastLine | awk '{print $8}' | cut -d\" -f1)"
        AuthTime="$(echo $LastLine | cut -d\[ -f2 | cut -d\] -f1)"
        GetDNS
        check_ip
        Location=" ($Country, $City)"
        # Now we have all the pieces in place: write them in $ file-sharing! 
#        echo " - mounted by \"$AuthUser\" from $(echo $HOSTNAME | sed s/\.$DOMAIN//g)$(if [ -z "$(echo $HOSTNAME | grep -o $DOMAIN)" ]; then echo " ($City, $Country)"; fi) at ${AuthTime}${FieldSeparator}" >> "$SharingFile"
        echo " - mounted by \"$AuthUser\" from ${HOSTNAME%%.$DOMAIN}${Location%%$Localhost_Location} at ${AuthTime}${FieldSeparator}" >> "$SharingFile"
      done
    fi
  else
    echo " - NO LOGFILE FOR AFP!! See:${FieldSeparator}" >> "$SharingFile"
    echo " - http://com.any/kontakt/peter_moller/unix/applefileserver/${FieldSeparator}" >> "$SharingFile"
    echo " - for info on how to enable it!${FieldSeparator}" >> "$SharingFile"
  fi

  ########################
  # # Check SMB 
  ########################
  #SMB_Share="$(defaults read /var/db/launchd.db/com.apple.launchd/overrides org.samba.nmbd 2> /dev/null | grep [D]isabled | awk '{print $3}' | sed 's/;//g')"
  SMB_Share="$(grep "enable disk services" /var/db/smb.conf | cut -d= -f2 | sed 's/^\ *//g')"
  SMB_Verification_139="$(lsof -i :139)"
  SMB_Verification_445="$(lsof -i :445)"
  if [ "$SMB_Share" = "yes" -a -n "$SMB_Verification_139" -a -n "$SMB_Verification_445" ]; then
    Share_SMB="t"
  else
    Share_SMB="f"
  fi
  echo "Samba file share${FieldSeparator}$(if [ "$Share_SMB" = "t" ]; then echo "ON"; else echo "OFF"; fi)" >> "$SharingFile"
  # List of those who are logged 
  SMB_loggfile=/var/log/samba/log.smbd
  # Check the logs and report
  # Typical logfile (login and logout) looks like this:
  # [10/12/2010 16:19:52, 1, pid = 78387] / SourceCache/samba/samba-235.5/samba/source/smbd/service.c: make_connection_snum (1092)
  # 130.235.16.20 (130.235.16.20) connect to service peterm initially as user peterm (uid = 503, gid = 20) (pid 78387)
  # ...
  # [12/13/2010 10:06:07, 1, pid = 78387] / SourceCache/samba/samba-235.5/samba/source/smbd/service.c: close_cnum (1289)
  # 130.235.16.20 (130.235.16.20) closed connection to service peterm
  # So divided in two lines! 
  for IP in $(lsof -i -n | grep EST | grep smbd | cut -d\> -f2 | cut -d: -f1)
  do
    grep -n "$IP\b" $SMB_loggfile | grep "connect to service" | tail -1 > /tmp/smb_slask
    RAD="$(less /tmp/smb_slask  | cut -d: -f1)"
    SMB_user="$(less /tmp/smb_slask  | awk '{print $11}')"
#    SMB_from="$(less /tmp/smb_slask  | awk '{print $2}')"
    SMB_from="$(less /tmp/smb_slask  | cut -d\( -f2 | cut -d\) -f1)"
    IP="$SMB_from"
    SMB_time="$(sed -n $(echo $(( $(echo $RAD) - 1 )))p /var/log/samba/log.smbd | cut -d, -f1 | cut -d\[ -f2)"
    GetDNS
    check_ip
    Location=" ($Country, $City)"
    echo " - mounted by \"$SMB_user\" from ${HOSTNAME%%.$DOMAIN}${Location%%$Localhost_Location} at $SMB_time${FieldSeparator}" >> "$SharingFile"
    rm -f /tmp/smb_slask 2> /dev/null
  done

  ########################
  # # Check FTP
  ########################
  FTP_Share="$(defaults read /var/db/launchd.db/com.apple.launchd/overrides com.apple.ftpd 2> /dev/null | grep [D]isabled | awk '{print $3}' | sed 's/;//g')"
  FTP_Verification="$(lsof -i :20)"
  #if [ "$FTP_Share" = "0" -a -n "$FTP_Verification" ]; then
  if [ "$FTP_Share" = "0" ]; then
    Share_FTP="t"
  else
    Share_FTP="f"
  fi
  echo "FTP${FieldSeparator}$(if [ "$Share_FTP" = "t" ]; then echo "ON"; else echo "OFF"; fi)" >> "$SharingFile"
  # List of those who are logged 
  FTP_loggfile=/var/log/ftp.log
  # Check the logs and report
  # Typical logfile (login and logout) looks like this:
  # December 20 16:32:03 paravel ftpd [67765]: Connection from 130.235.16.41 to 130.235.16.211
  # December 20 16:32:08 paravel ftpd [67765]: FTP LOGIN FROM 130.235.16.41 as peterm (class: real, type: REAL)
  # December 20 16:32:30 paravel ftpd [67765]: Data Traffic: 6552 bytes in 2 files
  # December 20 16:32:30 paravel ftpd [67765]: Total traffic: 7623 bytes in 2 transfers 
  for FTP_pid in $(lsof -i -n | grep EST | grep ftpd | awk '{print $2}' | uniq)
  do
    grep -n "$FTP_pid" $FTP_loggfile | grep "LOGIN" > /tmp/ftp_slask
    FTP_user="$(less /tmp/ftp_slask | cut -d\] -f2 | awk '{print $7}')"
    IP="$(less /tmp/ftp_slask | cut -d\] -f2 | awk '{print $5}')"
    FTP_time="$(less /tmp/ftp_slask | awk '{print $1" "$2" "$3}')"
    GetDNS
    check_ip
    Location=" ($Country, $City)"
    echo " - authenticated by \"$FTP_user\" from ${HOSTNAME%%.$DOMAIN}${Location%%$Localhost_Location} at $SMB_time${FieldSeparator}" >> "$SharingFile"
    rm -f /tmp/ftp_slask 2> /dev/null
  done

  ########################
  # # Check HTTP 
  ########################
  HTTP_Share="$(defaults read /var/db/launchd.db/com.apple.launchd/overrides org.apache.httpd 2> /dev/null | grep [D]isabled | awk '{print $3}' | sed 's/;//g')"
  HTTP_Verification="$(lsof -i :80)"
  if [ "$HTTP_Share" = "0" -a -n "$HTTP_Verification" ]; then
    Share_HTTP="t"
  else
    Share_HTTP="f"
  fi
  echo "Web-server (http)${FieldSeparator}$(if [ "$Share_HTTP" = "t" ]; then echo "ON"; else echo "OFF"; fi)" >> "$SharingFile"

  ########################
  ## Check SSH
  ########################
  SSH_Share="$(defaults read /var/db/launchd.db/com.apple.launchd/overrides com.openssh.sshd 2> /dev/null | grep [D]isabled | awk '{print $3}' | sed 's/;//g')"
  SSH_Verification="$(lsof -i :22)"
  if [ "$SSH_Share" = "0" -a -n "$SSH_Verification" ]; then
    Share_SSH="t"
  else
    Share_SSH="f"
  fi
  echo "Secure shell${FieldSeparator}$(if [ "$Share_SSH" = "t" ]; then echo "ON"; else echo "OFF"; fi)" >> "$SharingFile"
  # Rapportera ssh-inloggningar
  SuccessfulSSH=/Library/com.any/Breakins/Successful_ssh.txt
  if [ -f "$SuccessfulSSH" ]; then
    exec 6<"$SuccessfulSSH"
    while read -u 6 Month Day Time PID Way Who IP
    # December 13 17:35:04 18 759 interactively peterm 130.235.16.20 
    do
      # Is the user still logged in? 
      if [ "`ps -ef | grep [s]sh | grep -v "^    0 " | grep "\b$(echo $PID | sed 's/sshd\[//g' | sed 's/\]://g')\b"`" ]; then
        # Determine hostname (a) for IP. Scale of the ending point
        # This function gives: $ HOST
        GetDNS
        # Look up geolokationen
        # This function gives: $ City, $ Country 
        check_ip
        echo " - \"$Who\" logged in from ${HOSTNAME%%.$DOMAIN}${Location%%$Localhost_Location} at $Month $Day $Time${FieldSeparator}" >> "$SharingFile"
      fi
    done
  fi

  ########################
  ## Check Printer Sharing 
  ########################
  #SMB_Share="$(defaults read /var/db/launchd.db/com.apple.launchd/overrides org.samba.nmbd 2> /dev/null | grep [D]isabled | awk '{print $3}' | sed 's/;//g')"
  Print_Share="$(grep "enable print services" /var/db/smb.conf | cut -d= -f2 | sed 's/^\ *//g')"
  Print_Verification_139="$(lsof -i :139)"
  Print_Verification_445="$(lsof -i :445)"
  if [ "$Print_Share" = "yes" -a -n "$Print_Verification_139" -a -n "$Print_Verification_445" ]; then
    Share_Print="t"
  else
    Share_Print="f"
  fi
  echo "Printer-sharing${FieldSeparator}$(if [ "$Share_Print" = "t" ]; then echo "ON"; else echo "OFF"; fi)" >> "$SharingFile"

  ########################
  ## Check ARD
  ########################
  ARD_Share="$(defaults read /var/db/launchd.db/com.apple.launchd/overrides com.openssh.sshd 2> /dev/null | grep [D]isabled | awk '{print $3}' | sed 's/;//g')"
  ARD_Verification_5900="$(lsof -i :5900)"
  ARD_Verification_3283="$(lsof -i :3283)"
  if [ "$ARD_Share" = "0" -a -n "$ARD_Verification_5900" -a -n "$ARD_Verification_3283" ]; then
    Share_ARD="t"
  else
    Share_ARD="f"
  fi
  VNC="$(defaults read /Library/Preferences/com.apple.RemoteManagement VNCLegacyConnectionsEnabled)"
  echo "Apple Remote Desktop${FieldSeparator}$(if [ "$Share_ARD" = "t" ]; then echo "ON"; else echo "OFF"; fi)" >> "$SharingFile"
  # List of those who are logged 
  ARD_loggfile=/var/log/appfirewall.log
  # Check the logs and report
  # Typical logfile (only login - logout visible only through the process is over) looks like this:
  # December 20 paravel 16:34:20 Firewall [76]: Allow AppleVNCServer connecting from 130.235.225.135:50940 to port 5900 proto = 6
  # The name of the user authenticate themselves visible only by seeing who owns the process! 
  for IP in $(lsof -i -n | grep EST | grep AppleVNCS | cut -d\> -f2 | cut -d\] -f1 | cut -d\[ -f2 | sed 's/:*//g')
  do
    grep "$IP:" $ARD_loggfile | grep "Allow AppleVNCServer connecting from $IP" | tail -1 > /tmp/ard_slask
    ARD_user="$(lsof -i -n | grep EST | grep AppleVNCS | grep "$IP" | awk '{print $3}')"
    ARD_time="$(less /tmp/ard_slask | awk '{print $1" "$2" "$3}')"
    GetDNS
    check_ip
    Location=" ($Country, $City)"
    echo " - accessed by \"$ARD_user\" from ${HOSTNAME%%.$DOMAIN}${Location%%$Localhost_Location} at $ARD_time${FieldSeparator}" >> "$SharingFile"
    rm -f /tmp/ard_slask 2> /dev/null
  done
  echo "VNC${FieldSeparator}$(if [ "$VNC" = "1" ]; then echo "ON"; else echo "OFF"; fi)" >> "$SharingFile"
 

  ########################
  ## Check Internet Sharing
  ########################
  Internet_Share="$(defaults read /var/db/launchd.db/com.apple.launchd/overrides com.apple.InternetSharing 2> /dev/null | grep [D]isabled | awk '{print $3}' | sed 's/;//g')"
  Internet_Verification="$(lsof -i :53)"
  if [ "$Internet_Share" = "0" -a -n "$Internet_Verification" ]; then
    Share_Internet="t"
  else
    Share_Internet="f"
  fi
  echo "Internet-sharing${FieldSeparator}$(if [ "$Share_Internet" = "t" ]; then echo "ON"; else echo "OFF"; fi)" >> "$SharingFile"

  ########################
  ## Check RemoteAppleEvents
  ########################
  RAE_Share="$(defaults read /var/db/launchd.db/com.apple.launchd/overrides com.apple.AEServer 2> /dev/null | grep [D]isabled | awk '{print $3}' | sed 's/;//g')"
  RAE_Verification="$(lsof -i :3031)"
  if [ "$RAE_Share" = "0" -a -n "$RAE_Verification" ]; then
    RAE_Internet="t"
  else
    RAE_Internet="f"
  fi
  echo "Remote Apple Events${FieldSeparator}$(if [ "$RAE_Internet" = "t" ]; then echo "ON"; else echo "OFF"; fi)" >> "$SharingFile"

  ########################
  ## Check Xgrid
  ########################
  Xgrid_Share="$(defaults read /var/db/launchd.db/com.apple.launchd/overrides com.apple.xgridagentd 2> /dev/null | grep [D]isabled | awk '{print $3}' | sed 's/;//g')"
  if [ "$Xgrid_Share" = "0" ]; then
    Xgrid_Internet="t"
  else
    Xgrid_Internet="f"
  fi
  echo "Xgrid${FieldSeparator}$(if [ "$Xgrid_Internet" = "t" ]; then echo "ON"; else echo "OFF"; fi)" >> "$SharingFile"

 exit 0
fi
#
# <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>


# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Print! 
IFS=_
exec 5<"$SharingFile"
if [ -s "$SharingFile" ]; then
  DATE=$(ls -ls "$SharingFile" | awk '{ print $7" "$8" "$9 }')
  printf "${ESC}1;40;37mFile-sharing status:$Reset ${ESC}47;30m($DATE)${Reset}\n\n"
#  printf "\n\n${ESC}${BoldFace}mStatus of File Sharing:$Reset ($DATE)\n\n"
  printf "${ESC}${UnderlineFace};${YellowFont}m$Formatstring$Reset\n" "Sharing" "Status"
fi
while read -u 5 Share Status
do
  if [ "$Status" = "ON" -o -z "$Status" ]; then
    FontColor="$WhiteFont"
  else
    FontColor="$RedFont"
  fi
  if [ "$(echo $Share | cut -c1-2)" = " -" ]; then
    printf "${ESC}${BGColor};${ItalicFace};${FontColor}m$Formatstring$Reset\n" "$Share" "$Status"
  else
    printf "${ESC}${BGColor};${FontColor}m$Formatstring$Reset\n" "$Share" "$Status"
  fi
done
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

exit 0



如果需要定时运行,将下面文件存放在/Library/LaunchDaemons/com.any.plist,之后
launchctl load /Library/LaunchDaemons/com.any.com.plist

launchctl start com.any.com.plist:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>Label</key>
	<string>se.lth.cs.logger</string>
	<key>ProgramArguments</key>
	<array>
		<string>/usr/bin/logger.sh</string>
	</array>
	<key>StartInterval</key>
	<integer>300</integer>
</dict>
</plist>


Tony Liu, July 2011





Tony Liu - Http://cs.lth.se/kontakt/peter_moller/script/loggersh/Tony Liu - http://cs.lth.se/kontakt/peter_moller/script/



原文链接: http://blog.csdn.net/afatgoat/article/details/6616587

你可能感兴趣的:(OS X: 实用脚本程序(bash scripts)系列-14)