Skip to content

Instantly share code, notes, and snippets.

@haircut
Created February 12, 2017 03:16
Show Gist options
  • Save haircut/a13766b4836b57687f916e17f156a548 to your computer and use it in GitHub Desktop.
Save haircut/a13766b4836b57687f916e17f156a548 to your computer and use it in GitHub Desktop.
Removes keychain entries in the logged-in-user's login keychain related to campus print servers. Useful after password changes.
#!/bin/bash
###
#
# Name: clear-saved-printer-passwords.sh
# Description: Removes keychain entries in the logged-in-user's login keychain
# related to campus print servers. Useful after password changes.
# Author: Matthew Warren <[email protected]>
# Created: 2015-08-15
# Last Modified: 2017-02-11
#
###
# Binary locations
security=/usr/bin/security
cancel=/usr/bin/cancel
cupsenable=/usr/sbin/cupsenable
lpstat=/usr/bin/lpstat
cupsctl=/usr/sbin/cupsctl
launchctl=/bin/launchctl
# Print servers
print_servers=(\
'print1.example.com' \
'print2.example.com' \
)
# Current user
current_user=$(python -c "from SystemConfiguration import \
SCDynamicStoreCopyConsoleUser; import sys; username = \
(SCDynamicStoreCopyConsoleUser(None, None, None) or [None])[0]; \
username = [username,\"\"][username in [u\"loginwindow\", None, u\"\"]]; \
sys.stdout.write(username + \"\n\");")
# Delete all pending print jobs
$cancel -a -
# Clear current user's keychain of printer-related entries
for print_server in "${print_servers[@]}"; do
echo "===================="
search=$(su "${current_user}" -c "${security} find-internet-password -s \
${print_server} 2> /dev/null")
if [[ -z $search ]]; then
echo "Print Server ${print_server} not found in \
/Users/${current_user}/login.keychain"
else
if su "${current_user}" -c "${security} delete-internet-password -s \
${print_server} \
/Users/${current_user}/Library/Keychains/login.keychain > \
/dev/null 2>&1"; then
echo "Removed an entry for ${print_server}"
else
echo "Failed to remove keychain entry for ${print_server}"
fi
fi
done
# Resume all queues
mapped_printers=$($lpstat -p | grep disabled | awk '{print $2}')
for i in $mapped_printers; do
$cupsenable "${i}"
done
# Enable CUPS web interface
$cupsctl webinterface=yes
# Restart CUPS
$launchctl start org.cups.cupsd
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment