Tuesday, 22 April 2014

Download and install Lync for mac 14.0.8 using bash script.

#!/bin/bash
#Download and install Lync for mac 14.0.8 using bash

USERNAME=$(ls -l /dev/console | awk '{print $3}' )
#get current username of AD user
HOME=$(sudo dscl . -read /Users/$USERNAME NFSHomeDirectory | awk '{print $2}')
#get user's home directory
MobileUsers=`dscl . read /Users/$USERNAME OriginalNodeName | grep "Active Directory"`
#do only for AD users
dmg="lync_14.0.8_140321.dmg"
give the current folder name
logfile="/private/var/log/Lyncwebupgrade.log"
log () {
echo $1
echo $(date "+%Y-%m-%d %H:%M:%S: ") $1 >> $logFile
}
#logging function
receipt='/private/var/db/receipts/com.microsoft.lync.all.lync.pkg.14.0.8.plist'
if [ -f "$receipt" ]
then
log "lync reciept found aborting"
exit 0
else
check=$(osascript -e 'tell application "System Events" to display dialog "Your Lync is out of date, please click OK to upgrade Lync" with title "Lync Sign in Details" with icon note buttons {"OK","Do Later"} default button 1')

if [[ $check =~ OK ]];
then
#kill lync if open
LYNC_PID=$(ps ax | grep "/Applications/Microsoft Lync.app/Contents/MacOS/Microsoft Lync" | grep -v grep | awk '{ print $1 }')
kill -9 ${LYNC_PID}
if [ $? = 0 ] ; then
log "Lync is open killing it now "
else
log "Lync is not running"
fi
for username in $MobileUsers
do
#this is in case user had pervious version of Lync
rm -rf $HOME/Documents/Microsoft\ User\ Data/Microsoft\ Lync\ Data/sip_*
done
log "Removed SIP dir"
if [ -f "$dmg" ];   
then
#attach the dmg if its already on current folder
hdiutil attach "$dmg" -nobrowse -noverify -noautoopen
else
#dl the lync dmg
curl -O http://download.microsoft.com/download/5/0/0/500C7E1F-3235-47D4-BC11-95A71A1BA3ED/lync_14.0.8_140321.dmg
hdiutil attach "$dmg" -nobrowse -noverify -noautoopen
fi
/usr/sbin/installer -dumplog -verbose -pkg /Volumes/Microsoft\ Lync/Lync\ Installer.pkg -target / &>/private/var/log/Lyncwebupgrade.log
#install it silently
sleep 3
/usr/bin/hdiutil detach "/Volumes/Microsoft Lync"
sleep 3
rm -f lync_14.0.8_140321.dmg
#remove the dmg
#add lync icon to dock, again only for AD users
for username in $MobileUsers
do
defaults write $HOME/Library/Preferences/com.apple.dock.plist persistent-apps -array-add "tile-datafile-data_CFURLString/Applications/VMware Fusion.app/_CFURLStringType0"
log "Lync icon added to dock"
done
sleep 5

chown $USERNAME:"CORP\Domain Users" $HOME/Library/Preferences/com.apple.dock.plist
chmod 600 $HOME/Library/Preferences/com.apple.dock.plist
log "perms changed on dock plist"

killall -HUP cfprefsd
killall -HUP Dock
sleep 3
log "bounced dock"


else
log "user declined"
exit 0

fi
fi
exit 0

Monday, 21 April 2014

Createmobileaccount and add to admin using bash script.

         I got a request to simplify the process of addition of mobile accounts to macs from our local techs. Their primary complaint was that the script we used currently to create mobile accounts from AD creadentials was terminal based and hence confusing. Our local network is waay too slow for network users to just login, hence the necessity of adding mobile accounts. I created a bash script with interactive dialogs which would run as a policy in JAMF Self Service. All the tech would need to do is run the policy and enter the AD username for which the mac was to be configured.
   As usual free to use as long as i'm credited.

#!/bin/sh
#createmobileuser.sh interactive app to create mobile accounts by checking AD.
#created by tausif
checkAD=`/usr/bin/dscl localhost -list . | grep "Active Directory"`
if [ "${checkAD}" != "Active Directory" ]; then
          osascript -e 'tell application "System Events" to display dialog "A This machine is not bound to Active Directory" & "\nExiting" with title "Not on CORP Domain" buttons {"OK"} default button 1 giving up after 300 with icon 0'
exit 1
else

activeDirectoryPrompt=$(/usr/bin/osascript << EOF
tell application "System Events" to display dialog "Please the user's Active Directory login ID:" default answer "CORP ID..." with title "Mobile account created" buttons {"Continue"} default button "Continue" giving up after 300 with icon note
set activeDirectoryPrompt to the text returned of result
EOF)
FirstName="`/usr/bin/dscl /Search -read /Users/$activeDirectoryPrompt FirstName | awk '{ print $2 }'`"
LastName="`/usr/bin/dscl /Search -read /Users/$activeDirectoryPrompt LastName | awk '{ print $2 }'`"
RealName="$FirstName $LastName"
confirm=$(osascript -e 'tell application "System Events" to display dialog " Is the user named: '$FirstName' '$LastName' ?" with title "Please Click Yes or no" buttons {"Yes", "No"} default button "Yes" giving up after 300 with icon path to resource "AccountsPref.icns" in bundle "/System/Library/PreferencePanes/Accounts.prefPane/Contents/Resources"')
if [[ $confirm =~ Yes ]];
then
#create mobile account and log all messages, this is necessary as the command spews some weird messages.
/System/Library/CoreServices/ManagedClient.app/Contents/Resources/createmobileaccount -v -n $activeDirectoryPrompt &>/private/var/log/mobacc.log
dscl . -append /Groups/admin GroupMembership $activeDirectoryPrompt
osascript -e 'tell application "System Events" to display dialog "Account created." with title "Account created." buttons {"Ok"} default button "Ok" giving up after 300 with icon path to resource "AccountsPref.icns" in bundle "/System/Library/PreferencePanes/Accounts.prefPane/Contents/Resources"'
exit 0
else
osascript -e 'tell application "System Events" to display dialog "Incorrect username. Account creation has ended." with title "Incorrect Username" buttons {"Ok"} default button "Ok" giving up after 300 with icon path to resource "AccountsPref.icns" in bundle "/System/Library/PreferencePanes/Accounts.prefPane/Contents/Resources"'
fi
fi
exit 0

Saturday, 19 April 2014

Set multiple NTP servers for macs using shell script

Script to set multiple NTP servers on macs.

#this script sets multiple NTP servers on a mac, with the first choice to the internal NTP server
#Script to set multiple NTP servers and also enable time zone
#Created by Tausif Ahmed Khan
#!/bin/sh
TimeServer1="yourinternal.ntp.server"
TimeServer2="time.apple.com"

/usr/sbin/systemsetup -setusingnetworktime off
#Set specific time server
/usr/sbin/systemsetup -setnetworktimeserver $TimeServer1
echo "server $TimeServer2" >> /etc/ntp.conf

# enable location services
/bin/launchctl unload /System/Library/LaunchDaemons/com.apple.locationd.plist
uuid=`/usr/sbin/system_profiler SPHardwareDataType | grep "Hardware UUID" | cut -c22-57`
/usr/bin/defaults write /var/db/locationd/Library/Preferences/ByHost/com.apple.locationd.$uuid LocationServicesEnabled -int 1
/usr/sbin/chown -R _locationd:_locationd /var/db/locationd
/bin/launchctl load /System/Library/LaunchDaemons/com.apple.locationd.plist

# set time zone automatically using current location
/usr/bin/defaults write /Library/Preferences/com.apple.timezone.auto Active -bool true

/usr/sbin/systemsetup -setusingnetworktime on

/usr/sbin/systemsetup -gettimezone
/usr/sbin/systemsetup -getnetworktimeserver

exit 0

AD password expiration script for macs (launchd item)

      We have been having issues with people forgetting to change their AD passwords on macs because there is no alert mechanism which lets users know that their password might expire soon.
I created a password expiration alert script to remediate this. I wanted the alert to be persistent and hence created a launchd item, which runs the script every 4 hours.
  In my setup, i've put the script in /Library/passchange.sh , and a launchagent in
/Library/LaunchAgents/
You'll need to make sure the script is executable and the launchagent (owned by root:wheel) is not.
TO do this, i created an installer which places both items on the client macs and runs a postflight script to adjust the permissions and load the launchAgent.
  I used Composer to package the install, you can use packages or iceberg.

 As usual, free to use as long as you credit me.
passchange.sh
####################################################
#!/bin/bash
#pass word alert script created by tausif to alert people to change their passwords.
# PasswordChange.sh
ASROOT=${ASROOT:-sudo}

log () {
echo $1
echo $(date "+%Y-%m-%d %H:%M:%S: ") $1
}
logFile="/private/var/log/passwdchg.log"
# Variables and Functions #
PwdPolicy=90

OSVersion=`sw_vers | grep ProductVersion | cut -c 17-20`
ADcheck=`dscl localhost -list . | grep "Active Directory"`
Domain=`$ASROOT dsconfigad -show | grep "Active Directory Domain" | awk '{print $5}'`
LoggedInUser=`ls -l /dev/console | awk '{print $3}'`
LoggedInUID=`dscl . read /Users/$LoggedInUser UniqueID | awk '{print $2}'`

NetworkLocation=$(
ping -c 2 "corp.fairisaac.com" > /dev/null
if [ $? -eq 0 ]; then
log "Connected to FICO internal network.Checking password expiration";
else
log "Error: Not connected to FICO internal network."
fi
fi
)
if [[ $ADcheck == "Active Directory" && $Domain == "corp.fairisaac.com" && $LoggedInUID -ge 1025 ]]; then
SetDate=`dscl /Active\ Directory/CORP/All\ Domains/ read /Users//$LoggedInUser pwdLastSet | awk '/pwdLastSet:/{print $2}'`
LastSet=`expr $SetDate / 10000000 - 1644473600`
LastSet2=`expr $LastSet - 10000000000`
Time=`date +%s`
TimeSinceSet=`expr $Time - $LastSet2`
DaysSinceSet=`expr $TimeSinceSet / 86400`
DaysLeft=`expr $PwdPolicy - $DaysSinceSet`
if [[ $DaysLeft -le 14 ]];
                 then
                            CHANGE=$(osascript -e 'tell application "System Events" to display dialog "Your password will expire in '$DaysLeft' days." with title "FICO CORP Password" buttons {"Change Password Now", "Cancel"} default button "Change Password Now" giving up after 300 with icon path to resource "AccountsPref.icns" in bundle "/System/Library/PreferencePanes/Accounts.prefPane/Contents/Resources"')
                            if [[ $CHANGE =~ Password ]];
                                then
                                osascript -e 'tell application id "com.apple.systempreferences"' -e "activate" -e 'set the current pane to pane id "com.apple.preferences.users"' -e "end tell"
                                else
                                log "User clicked cancel"
fi
fi
fi
exit 0


####################################################

#LaunchAgent item,  needs to be placed in /Library/LaunchAgents/
#net.fico.passchg.plist filename





####################################################
#postflight script to schange permissions on the script and plist.
#!/bin/sh
## postinstall

logFile="/private/var/log/passch_install.log"
log () {
echo $1
echo $(date "+%Y-%m-%d %H:%M:%S: ") $1 >> $logFile
}


chown root:wheel /Library/LaunchAgents/net.fico.passchg.plist
chmod 644 /Library/LaunchAgents/net.fico.passchg.plist
chmod +x /Library/passwordchange/Scripts/passchange.sh

log "change perms on script and plist"

launchctl load /Library/LaunchAgents/net.fico.passchg.plist
log "loaded job"

exit 0        ## Success
exit 1        ## Failure



####################################################

Enjoy.
tausif

Lync for mac 14.0.8 package

So microsoft brought out an update to Lync for mac, this update fixes the contacts not searchable issue on mavericks. There are a few changes when its installed though.

Previously in order to auto populate a Lync users ID from the AD server all we had to do was populate the com.microsoft.Lync.plist with the sign in name and Lync address.

But in Lync 14.0.8 the /Users/UserName/Library/Preferences/com.microsoft.Lync.plist file is created only when lync is launched for the first time and the license agreement accepted. So for a new install the old method doesn't work. We worked around it by displaying the sign-in details as part of a postflight script that ran after Lync got installed.

To create the lync for mac package use composer to capture a snapshot before Lync is installed.

Modify the  MicrosoftLyncRegistrationDB.plist located at /Library/Preferences with the Lync internal and external server name.


Create the package after Lync is installed and remove unnecessary items.
You'll need to  make sure that the modified MicrosoftLyncRegistrationDB.plist is in the package,












--> Then put in preflight and postflight scripts as follows:Then after putting in the scripts Build your pkg.
I'll put in my scripts here, on condition that you credit me with any future use:
Preupgrade.sh:
################################################################
#!/bin/sh
## preinstall
#Lync for mac preupgrade script created by tausif
#created to kill lync and remove the sip_* directory in current AD users home folder .
USERNAME=$(ls -l /dev/console | awk '{print $3}' )
#get console user
HOME=$(sudo dscl . -read /Users/$USERNAME NFSHomeDirectory | awk '{print $2}')
#get current users home directory
MobileUsers=`dscl . read /Users/$USERNAME OriginalNodeName | grep "Active Directory"`
#this is to filter out local users and target only AD users
logFile="/private/var/log/LyncPreinstall.log"
log () {
echo $1
echo $(date "+%Y-%m-%d %H:%M:%S: ") $1 >> $logFile
}

LYNC_PID=$(ps ax | grep "/Applications/Microsoft Lync.app/Contents/MacOS/Microsoft Lync" | grep -v grep | awk '{ print $1 }')
kill -9 ${LYNC_PID}
if [ $? = 0 ] ; then
log "Lync is open killing it now "
else
log "Lync is not running"
fi
for username in $MobileUsers
do
rm -rf $HOME/Documents/Microsoft\ User\ Data/Microsoft\ Lync\ Data/sip_*
log "Removed SIP dir"
done

exit 0          ## Success
exit 1          ## Failure

################################################################

Postfilght.sh:
################################################################
#!/bin/sh
## postinstall.sh
#Lync for mac postupgrade script created by tausif
#created to install lync, diplay Lync credentials to user,add lync to user's dock and remove the sip_* #directory in current AD users home folder .
USERNAME=$(ls -l /dev/console | awk '{print $3}' )
#get current user
HOME=$(sudo dscl . -read /Users/$USERNAME NFSHomeDirectory | awk '{print $2}')
#get current users home directory
EMAILADDRESS=$( dscl /Search -read /Users/$USERNAME | grep -i msRTCSIP-PrimaryUserAddress | awk '{print $2}'| cut -c 5- )
#very tricky get Lync signin address
CORP='CORP\\'
LYNCNAME=$CORP$USERNAME
#do this because osascript is strange when run from shell
MobileUsers=`dscl . read /Users/$USERNAME OriginalNodeName | grep "Active Directory"`
#filter only for AD users, we don't want to do this from a local account
logFile="/private/var/log/LyncPostinstall.log"
log () {
echo $1
echo $(date "+%Y-%m-%d %H:%M:%S: ") $1 >> $logFile
}
#log everything
#check for local user running this.
if [[ $MobileUsers != " /Active Directory/CORP/corp.fairisaac.com" ]];
then
/usr/bin/osascript << EOF
tell application "System Events"
    activate
    display dialog "Lync auto-setup applies only to Active Directory accounts. Aborting " with title "Aborting" with icon note buttons {"OK"} default button 1
end tell
EOF
log "Local account used"
exit 1
fi
#tell user his lync details
/usr/bin/osascript << EOF
 tell application "System Events"
        activate
        display dialog "Please note your sign in details and click ok to complete the Installation" & "\nLync sign-in Address: \"$EMAILADDRESS\""  &  " \nLync Username: \"$LYNCNAME\" " with title "Lync Sign in Details" with icon note buttons {"OK"} default button 1
    end tell
EOF
log "sign in details displayed"
#add lync icon to dock
for username in $MobileUsers
do
defaults write $HOME/Library/Preferences/com.apple.dock.plist persistent-apps -array-add "tile-datafile-data_CFURLString/Applications/Microsoft Lync.app/_CFURLStringType0"
done
log "Lync icon added to dock"
sleep 5

chown $USERNAME:"CORP\Domain Users" $HOME/Library/Preferences/com.apple.dock.plist
chmod 600 $HOME/Library/Preferences/com.apple.dock.plist
log "perms changed on dock plist"
#bounce dock
killall -HUP cfprefsd
#cfprefsd for mavericks
killall -HUP Dock

log "bounced dock"

exit 0        ## Success
exit 1        ## Failure

Detect autopilot session

  Ensuring that some apps only install during autopilot is not easily accomplished, you can use the below powershell script as a requiremen...