Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

What next?
1. Bookmark us with del.icio.us or Digg Us!
2. Subscribe to this site's RSS feed
3. Browse the site.
4. Post your own code snippets to the site!

Top Tags and Latest Posts

ruby
  Install postgres gem on Mac OS X 10.5 (Leopard)
  Suppress Warnings in Ruby
  Add missing empty directories in .svn

rails
  Subversion Configuration Script for Your Rails A..
  Install plugin on rails app
   Ubuntu 7.10: bootstrap a Ruby on Rails stack

osx
  Install postgres gem on Mac OS X 10.5 (Leopard)
  Compile ClamAV from source on Mac OS X
  Run ClamAV from a system service agent account

php
  Installs pecl memcache php5 extension on a Joyen..
  关于MYSQL的用法
  Test php mysql pdo_mysql

shell
  how to get process start time
  Compile ClamAV from source on Mac OS X
  rename many files at once

javascript
  xpath helper function
  jQuery namespaced event binding/unbinding
  jQuery and Rails' respond_to

bash
  Compile ClamAV from source on Mac OS X
  rename many files at once
  add apache to users group

mysql
  move column in mysql
  关于MYSQL的用法
  Test php mysql pdo_mysql

mac
  Compile ClamAV from source on Mac OS X
  Run ClamAV from a system service agent account
  Creating & deleting system service agent account..

linux
  activate root in ubuntu after install
  running scheduled programs in linux
  Rename files by reordering existing data (regula..

lighttpd
  Tomcat connector for lighttpd:
  Lighttpd redirect www to no www
  lighttpd launchd script for Leopard

ssh
  ssh-copy-id for automated pubkey append
  ssh remote systems
  Local SOCKS Proxy for Safari

Top Tags Alphabetically

accelerator (12)
actionscript (18)
administration (32)
ajax (25)
apache (34)
applescript (15)
backup (12)
bash (63)
cli (23)
css (44)
delphi (21)
dns (15)
dom (17)
effect (12)
email (19)
expressionengine (25)
fastcgi (14)
flash (17)
freebsd (12)
html (41)
image (23)
java (15)
javascript (104)
js (11)
lighttpd (46)
linux (53)
mac (56)
mysql (63)
osx (110)
perl (19)
php (110)
prototype (15)
python (21)
rails (125)
recipe (16)
regex (26)
ruby (130)
rubyonrails (19)
shell (106)
sql (32)
ssh (45)
subversion (24)
svn (35)
sysadmin (14)
terminal (27)
textdrive (15)
textpattern (17)
tiger (11)
ubuntu (13)
unix (44)

« Newer Snippets
Older Snippets »
Showing 21-40 of 995 total

moving subversion server to another machine

dump the repository to a text file
svnadmin dump repositoryPath > repository.dumpfile


create the new repository on the new machine
cd /path/to/new-repository-parent-directory
svnadmin create repository-name
svnadmin load repository-name < repository.dumpfile


transfer your local svn project to the new machine. Use absolute paths!
svn switch --relocate oldurl newurl


Example:

svn switch --relocate http://myoldcrapserver.com/svn/myfunkyproj svn+ssh://mykickingnewserver.com/var/svn/myfunkyproj

Tomcat connector for lighttpd:

To connect Tomcat to lighttpd use the following code:



server.modules  += ( "mod_proxy_backend_ajp13" )
$HTTP["url"] =~ "^/tomcat/" {
  proxy-core.balancer = "round-robin"
  proxy-core.protocol = "ajp13"
  proxy-core.backends = ( "localhost:8009" )
  proxy-core.max-pool-size = 16
}

export certain revision of file from svn

Easier to just cat the revision you want and copy it over rather than try to check out a certain revision.

svn cat -r [REV] mydir/myfile > mydir/myfile

sort installed packages by size

// sort installed packages by size

rpm -qa --queryformat="%{size} %{name}-%{version}-%{release}\n" | sort -rn | less

Django and Open-flash-charts

// Found this on the django-users mailing list, need to test
ok, I finally got open-flash-chart to work.

1. create an xhtml-file and insert (something like) this:

    <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
        codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/
flash/swflash.cab#version=8,0,0,0"
        width="600"
        height="400"
        id="graph-2"
        align="middle">
    <param name="allowScriptAccess" value="sameDomain" />
    <param name="movie" value="/media/site/chart/open-flash-chart.swf?
width=600&height=400&data=/chart_data/" />
    <param name="quality" value="high" />
    <param name="bgcolor" value="#FFFFFF" />
    <embed src="/media/site/chart/open-flash-chart.swf?
width=600&height=400&data=/chart_data/"
        quality="high"
        bgcolor="#FFFFFF"
        width="600"
        height="400"
        name="open-flash-chart"
        align="middle"
        allowScriptAccess="sameDomain"
        type="application/x-shockwave-flash"
        pluginspage="http://www.macromedia.com/go/getflashplayer"; />
    </object>

2. define the url for the chart, eg: (r'^chart/$',
'www.views.charts.chart'),

3. define the url for the chart-data, e.g.: (r'^chart_data/$',
'www.views.charts.chart_data'),

4. the views:

def chart(request):

   ### nothing really required. whatever you want to do here. points
to the html-file created above

    return render_to_response('site/charts/chart.html', {
        'var': 'var',
    }, context_instance=RequestContext(request) )


def chart_data(request):

    import random

    g = graph()

    data_1 = []
    data_2 = []
    data_3 = []
    for i in range(12):
      data_1.append( random.randint(14,19) )
      data_2.append( random.randint(8,13) )
      data_3.append( random.randint(1,7) )

    g.title('PageViews (2007)', '{color: #999999; font-size: 16; text-
align: center}' );
    g.bg_colour = '#ffffff'

    # we add 3 sets of data:
    g.set_data( data_1 )
    g.set_data( data_2 )
    g.set_data( data_3 )

    # we add the 3 line types and key labels
    g.line_dot( 3, 5, '#333333', 'Page views', 10 )
    g.line_dot( 3, 5, '#666666', 'Visits', 10)    # <-- 3px thick +
dots
    g.line_hollow( 2, 4, '#999999', 'Unique visitors', 10 )


g.set_x_labels( 
'Jänner,Februar,März,April,Mai,Juni,Juli,August,September,Oktober,November,Dezember'.split(',')
 )
    g.set_x_label_style( 11, '0x666666', 2, 1)

    g.set_y_max(20)
    g.y_label_steps(4)
    g.set_y_label_style( 10, '0x666666')

    return HttpResponse(g.render())


script for migrating from UW-IMAP to Dovecot [PATCHED]

#!/bin/bash

# A script for migrating from UW-IMAP to Dovecot
#
# By Andrew Ziem
# Copyright (c) 2007 Springs Rescue Mission.  All rights reserved.
#
#
# Moves UW-IMAP mboxes from two locations to ~/mail so that Dovecot
# can easily convert mboxes to Maildirs.  Mailboxes with whitespace
# should be handled properly, and IMAP subscriptions should be preserved.
#
#


# Edit the below variables

#HOME_USERS=/home
HOME_USERS=/home/users

#MAIL_SPOOL=/var/mail
MAIL_SPOOL=/var/spool/mail



# to this function pass the user name
function move_mailboxlist
{
        if [ ! -d "$HOME_USERS/$1" ];
        then
                echo "Error: $HOME_USERS/$1 does not exist"
                return 0
        fi

        # make ~/mail
        cd "$HOME_USERS/$1"
        mkdir mail
        chown "$1" mail

        # find each mbox and move it to ~/mail
        if [ ! -f ".mailboxlist" ];
        then
                echo "Warning: .mailboxlist does not exist for $1"
                return 0
        fi
        
        # cat .mailboxlist | while read line; do mv "${line}" ./mail/; done
        cat .mailboxlist | tr '\n' '\0' | xargs -0 mv -t ./mail/

        # preserve subscriptions (to prevent manual resubscriptions)
        mkdir Maildir
        chown "$1" Maildir
        cp -a .mailboxlist Maildir/subscriptions
}

# move inbox from $MAIL_SPOOL to ~/mail/inbox
function move_inbox
{
        if [ ! -f "${MAIL_SPOOL}/$1" ];
        then
                echo "Error: ${MAIL_SPOOL}/$1 does not exist"
                return 0
        fi
        cp "${MAIL_SPOOL}/$1" "${HOME_USERS}/$1/mail/inbox"
        chown "$1" "${HOME_USERS}/$1/mail/inbox"
}

if [ $# -eq 0 ];
then
        echo "First, did you edit the directory names in the script?"
        echo "Then, if you want to do a dry run, prefix mv and cp with echo."
        echo "Then, invoke $0 by passing one or more user names."
        exit
fi

for user in $@
do
        echo "*** Processing user $user"
        move_mailboxlist $user
        move_inbox $user
done

import data into mysql

Things to note:
Mysql may not have access to the directory you've put the datafile. Use /tmp to overcome this problem.
Datafile name must be the same as the mysql table you're importing to.

mysqlimport -u username -p --columns=column_1,column_2 --fields-terminated-by=',' databasename /tmp/data_file_same_as_mysql_table_name

add apache to users group

// this handy one liner is used on any new webserver..
// puts apache into the users group to allow dev teams etc..

sed -i 's/users:x:1000:admin/users:x:1000:admin,wwwrun/' /etc/group

Run ClamAV from a system service agent account

The following instructions on how to run ClamAV from a system service agent account (non-root) require an admin user account, a ClamAV setup as described here and the creation of a clamavadmin system service agent account as described here.

Use at your own risk!


First uncomment the following lines of code in the first script at http://textsnippets.com/posts/show/1405:

# create further subdirectories if necessary
...
#fi
#
#fi


Then save the file, start the script and enter the following:

You are going to create a system service agent account!

Enter first name: clamavadmin

Note: The last name is optional and defaults to "agent" if you just press <return>!
Enter last name: 

Note: The user shell is optional and defaults to "/usr/bin/false" if you just press <return>!
Enter user shell: /bin/bash

Note: The home directory is optional and defaults to "/private/var/empty" if you just press <return>!
Enter home directory: /private/var/clamavadmin

System service agent account:  clamavadmin  successfully created!



# test
dscl . -read /Users/clamavadmin
dscl . -read /Groups/clamavadmin
dscl . list /Groups GroupMembership
dscl . read /Groups/clamavadmin GroupMembership
dscl . -search /Groups GroupMembership clamavadmin
echo $(dscl . -search /Groups GroupMembership clamavadmin | awk '{print $1}' | tr '\n' ' ')
printf -- "$(dscl . -search /Groups GroupMembership clamavadmin | awk '{print $1}' | tr '\n' ' ')\n"

sudo ls -ld /private/var/clamavadmin
sudo ls -l /private/var/clamavadmin/log/clamd.log
sudo ls -ld /private/var/clamavadmin/tmp
#sudo ls -l /private/var/clamavadmin/tmp/clamd   # will be created later by man clamd
sudo find /private/var/clamavadmin \( -type f -or -type d -or -type s \) -print0 | xargs -0 sudo ls -ldG



# add clamavadmin to group admin and group $(logname)
# add $(logname) to group clamavadmin
sudo dscl . -append /Groups/admin GroupMembership clamavadmin
sudo dscl . -append /Groups/$(logname) GroupMembership clamavadmin
sudo dscl . -append /Groups/clamavadmin GroupMembership $(logname)

#sudo dscl . -delete /Groups/admin GroupMembership clamavadmin 
#sudo dscl . -delete /Groups/$(logname) GroupMembership clamavadmin  
#sudo dscl . -delete /Groups/clamavadmin GroupMembership $(logname)   

# cf. http://textsnippets.com/posts/show/1402
dirmodes ~/Documents/ClamAV/Downloads/QueueDirectory


# copy update_clamd_db.sh
sudo cp /usr/local/sbin/update_clamd_db.sh /private/var/clamavadmin/update_clamd_db.sh
sudo chown clamavadmin:clamavadmin /private/var/clamavadmin/update_clamd_db.sh
sudo chmod 0750 /private/var/clamavadmin/update_clamd_db.sh
ls -l /private/var/clamavadmin/update_clamd_db.sh

# then change the following line in sudo nano  /private/var/clamavadmin/update_clamd_db.sh
/opt/local/bin/freshclam -u root
# ... to read ...
/opt/local/bin/freshclam -u clamavadmin


# get an overview of your ClamAV file & folder permissions in /opt
sudo find /opt \( -type f -or -type d \) -iregex ".*clam.*" -print0 | xargs -0 sudo ls -ldG

# set new ClamAV file & folder permissions
sudo find /opt  \( -type f -or -type d \) -iregex ".*clam.*" -print0 | xargs -0 sudo chown clamavadmin:clamavadmin
sudo find /opt  \( -type f -or -type d \) -iregex ".*clam.*" -print0 | xargs -0 sudo chmod 0750

# reset permissions
#sudo find /opt  \( -type f -or -type d \) -iregex ".*clam.*" -print0 | xargs -0 sudo chown root:wheel  
#sudo find /opt  \( -type f -or -type d \) -iregex ".*clam.*" -print0 | xargs -0 sudo chmod 0755


# test
sudo find /opt \( -type f -or -type d \) -iregex ".*clam.*" -print0 | xargs -0 sudo ls -ldG
sudo find /opt -not -user clamavadmin \( -type f -or -type d \) -iregex ".*clam.*" -print0 | xargs -0 sudo ls -ldG


# then modify clamd.conf
sudo nano /opt/local/etc/clamd.conf

LogFileMaxSize 10M
LogTime yes
FixStaleSocket yes
TCPAddr 127.0.0.1
MaxConnectionQueueLength 30
MaxThreads 20
ExitOnOOM yes
ScanOLE2 yes  # Microsoft Office documents and .msi files
ScanPDF yes
ArchiveMaxFileSize 100M
ArchiveMaxCompressionRatio 0
#VirusEvent echo virus: %v >> /path/to/file.txt

DatabaseDirectory /opt/local/share/clamav    # hardcoded
#LogFile /private/var/log/clamd.log
#TemporaryDirectory /private/var/tmp
#DatabaseDirectory /opt/local/share/clamav
#LocalSocket /tmp/clamd

#DatabaseDirectory /private/var/clamavadmin/share/clamav
LogFile /private/var/clamavadmin/log/clamd.log
TemporaryDirectory /private/var/clamavadmin/tmp
LocalSocket /private/var/clamavadmin/tmp/clamd



# modify net.clamav.clamd.plist

sudo launchctl unload -w /Library/LaunchDaemons/net.clamav.clamd.plist 2>/dev/null
sudo cp -p /Library/LaunchDaemons/net.clamav.clamd.plist /Library/LaunchDaemons/net.clamav.clamd.root-wheel

sudo nano /Library/LaunchDaemons/net.clamav.clamd.plist

<?xml version="1.0" encoding="UTF-8"?>
DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.$
"1.0">

        Disabled
        
        GroupName
        clamavadmin
        Label
        net.clamav.clamd
        ProgramArguments
        
                /opt/local/sbin/clamd
                -c
                /opt/local/etc/clamd.conf
        
        RunAtLoad
        
        UserName
        clamavadmin


sudo launchctl load -w /Library/LaunchDaemons/net.clamav.clamd.plist 2>/dev/null



# modify net.clamav.update.clamd.db.plist

sudo launchctl unload -w /Library/LaunchDaemons/net.clamav.update.clamd.db.plist 2>/dev/null
sudo cp -p /Library/LaunchDaemons/net.clamav.update.clamd.db.plist /Library/LaunchDaemons/net.clamav.update.clamd.db.plist.root-wheel

sudo nano /Library/LaunchDaemons/net.clamav.update.clamd.db.plist

"1.0" encoding="UTF-8"?>
"-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.$
<plist version="1.0">
<dict>
        <key>Disabledkey>
        />
        <key>GroupNamekey>
        clamavadmin</string>
        <key>Labelkey>
        net.clamav.update.clamd.db</string>
        <key>ProgramArgumentskey>
        
                /private/var/clamavadmin/update_clamd_db.shstring>
        </array>
        <key>RunAtLoadkey>
        />
        <key>StartIntervalkey>
        20000</integer>
        <key>UserNamekey>
        clamavadmin</string>
dict>


sudo launchctl load -w /Library/LaunchDaemons/net.clamav.update.clamd.db.plist 2>/dev/null



# watch clamd.log in a second Terminal window
open /bin/bash
sudo tail -n 50 -f /private/var/clamavadmin/log/clamd.log


# now restart clamd
if [[ -e "/private/var/clamavadmin/tmp/clamd" ]]; then sudo /bin/rm -f "/private/var/clamavadmin/tmp/clamd" ; fi
sudo /opt/local/sbin/clamd -c /opt/local/etc/clamd.conf


# test
(sleep 3; echo PING; sleep 3; echo exit) | sudo telnet -u /private/var/clamavadmin/tmp/clamd
echo PING | /opt/local/bin/socat - /private/var/clamavadmin/tmp/clamd    # requires: sudo port install socat
sudo find /private/var/clamavadmin \( -type f -or -type d -or -type s \) -print0 | xargs -0 sudo ls -ldG   # /private/var/clamavadmin/tmp/clamd

Creating & deleting system service agent accounts on Mac OS X

Inspired by: Description and guidelines on creating system service agent accounts on Mac OS X (Tiger) and HiddenAdminCreate

Use at your own risk!

1. create a system service agent account


#!/bin/bash

if [[ "$(/usr/bin/whoami)" != "root" ]]; then printf '\nMust be run as root!\n\n'; exit 1; fi

OPATH=$PATH
export PATH=/usr/bin:/usr/sbin:/bin:/sbin

OIFS=$IFS
export IFS=$' \t\n'

printf '\n\e[1mYou are going to create a system service agent account!\e[m\n\n'

declare sudo=/usr/bin/sudo dscl=/usr/bin/dscl


# first name 

printf "\e[1mEnter first name\e[m: "
read fn

# no spaces in names
if [[ -z "$(printf -- "$fn" | /usr/bin/grep -Eo "^[^[:space:]]+$")" ]]; then
   printf '\nUse a name without spaces! \nPlease, try again!\n\n'
   exit 1
fi

# name must not begin with a number
if [[ -n "$(printf -- "$fn" | /usr/bin/grep -E "^[[:digit:]]")" ]]; then
   printf '\nName must not begin with a number! \nPlease, try again!\n\n'
   exit 1
fi


# make sure the user name is unique
new_user="$(/usr/bin/dscl . -search /Users name "$fn" 2>/dev/null)"

if [[ -z "$new_user" ]]; then
  new_user="$fn"               
else
  printf "\nUser name already exists: $fn \nPlease, modify your name and try it again\x21\n\n"
  exit 1
fi 


# make sure the agent's primary group name is unique 
# note: the agent's primary group name is also based on the first name!

new_group="$(/usr/bin/dscl . -search /Groups name "$fn")"

if [[ -z "$new_group" ]]; then
  new_group="$fn"             
else
  printf "\nThe agent's primary group name already exists: $fn\x21 \nPlease, try again\x21\n\n"
  exit 1
fi 


# last name

printf '\nNote: The \e[1mlast name\e[m is \e[1moptional\e[m and defaults to "agent" if you just press !\n'
printf "\e[1mEnter last name\e[m: "
read ln

if [[ -z "$ln" ]]; then ln="agent"; fi

# no spaces in names
if [[ -z "$(printf -- "$ln" | /usr/bin/grep -Eo "^[^[:space:]]+$")" ]]; then
   printf '\nUse a name without spaces! \nPlease, try again!\n\n'
   exit 1
fi

# name must not begin with a number
if [[ -n "$(printf -- "$ln" | /usr/bin/grep -E "^[[:digit:]]")" ]]; then
   printf '\nName must not begin with a number! \nPlease, try again!\n\n'
   exit 1
fi


# user shell

printf '\nNote: The \e[1muser shell\e[m is \e[1moptional\e[m and defaults to "/usr/bin/false" if you just press !\n'
printf "\e[1mEnter user shell\e[m: "
read sh

if [[ -z "$sh" ]]; then sh="/usr/bin/false"; fi

# test if user shell exists
if [[ ! -e "$sh" ]]; then
   printf "\nUser shell does not exist: $sh\n\n"
   exit 1
fi


# home directory

printf '\nNote: The \e[1mhome directory\e[m is \e[1moptional\e[m and defaults to "/private/var/empty" if you just press !\n'
printf "\e[1mEnter home directory\e[m: "
read hd

if [[ -z "$hd" ]]; then 
   hd="/private/var/empty"
elif [[ "${hd:0:1}" != '/' ]]; then
   printf '\nThe home directory path does not begin with a slash "/".\nPlease, try again!\n\n'
   exit 1
elif [[ -e "$hd" ]]; then
   printf "\nHome directory already exists: $hd \nPlease, try again\x21\n\n"
   exit 1
fi

hd=${hd%/}      # remove a trailing slash character "/" if necessary



# get unique id numbers (uid, gid)
unset -v new_uid new_gid i
declare -i new_uid=0 new_gid=0 i=100

while [[ $i -lt 500 ]]; do      # try to get $new_uid and $new_gid between 100 and 500
   i=$[i+1]
   if [[ -z "$(/usr/bin/dscl . -search /Users uid $i)" ]] && [[ -z "$(/usr/bin/dscl . -search /Groups gid $i)" ]]; then
      new_uid=$i
      new_gid=$i
      break
   fi
done


if [[ $new_uid -eq 0 ]] || [[ $new_gid -eq 0 ]]; then     # get $new_uid and $new_gid greater than 500
   i=500
   idvar=0

   while [[ $idvar -eq 0 ]]; do 
      i=$[i+1]
      if [[ -z "$(/usr/bin/dscl . -search /Users uid $i)" ]] && [[ -z "$(/usr/bin/dscl . -search /Groups gid $i)" ]]; then
         new_uid=$i
         new_gid=$i
         idvar=1
         #break
      fi
   done

fi


if [[ $new_uid -eq 0 ]] || [[ $new_gid -eq 0 ]]; then printf 'Getting unique id numbers (uid, gid) failed!\n'; exit 1; fi



# check once again ...

if [[ $new_uid -eq $new_gid ]] && [[ "$new_user" == "$fn" ]] && [[ "$new_group" == "$fn" ]]; then

# create home directory
if [[ "$hd" != "/private/var/empty" ]]; then
   $sudo /bin/mkdir -p "$hd"
fi

# create the agent's primary group
$sudo /usr/sbin/dseditgroup -o create -r "$fn $ln" -i $new_gid "$new_group"
$sudo $dscl  . -append "/Groups/$new_group" passwd "*"

# create the system service agent
$sudo $dscl . -create /Users/$new_user
$sudo $dscl . -append /Users/$new_user RealName "$fn $ln"
$sudo $dscl . -append /Users/$new_user uid $new_uid
$sudo $dscl . -append /Users/$new_user gid $new_gid
$sudo $dscl . -append /Users/$new_user shell "$sh"
$sudo $dscl . -append /Users/$new_user home "$hd"
$sudo $dscl . -create /Users/$new_user passwd "*"

$sudo $dscl  . -append "/Groups/$new_group" GroupMembership "$new_user"    # add new agent to the agent's primary group
#$sudo /usr/sbin/dseditgroup -o edit -a "$new_group" -t user "$new_user"

else

   printf "\nConfiguration of system service agent account: $fn failed\x21 \nPlease, try again\x21\n\n"
   exit 1

fi

# create further subdirectories if necessary
#if [[ "$hd" != "/private/var/empty" ]]; then
#
#if [[ "$new_user" == "clamavadmin" ]]; then
#   # additional subdirectories for the clamavadmin system service agent account
#   $sudo /bin/mkdir  -p "$hd"/log
#   $sudo /usr/bin/touch "$hd"/log/clamd.log
#   $sudo /bin/mkdir  -p "$hd"/tmp
#   $sudo /bin/mkdir  -p "$hd"/share/clamav
#   $sudo /usr/sbin/chown -R $new_user:$new_user "$hd"
#   $sudo /bin/chmod -R 750 "$hd"
#fi
#
#fi


printf "\nSystem service agent account:  \e[1m$fn\e[m  successfully created\x21\n\n"

export IFS=$OIFS
export PATH=$OPATH

exit 0


#---------------------------

# test
dscl . list /Users
dscl . -read /Users/

dscl . list /Groups
dscl . -read /Groups/
dscl . list /Groups GroupMembership



2. delete a system service agent account

#!/bin/bash


if [[ "$(/usr/bin/whoami)" != "root" ]]; then printf '\nMust be run as root!\n\n'; exit 1; fi

OPATH=$PATH
export PATH=/usr/bin:/usr/sbin:/bin:/sbin

OIFS=$IFS
export IFS=$' \t\n'

declare sudo=/usr/bin/sudo


printf "\n\e[1mDelete system service agent account\e[m: "
read agent

if [[ -z "$agent" ]]; then printf '\nNo name for system service agent specified! Please, try again!\n\n'; exit 1; fi

# make sure the agent exists
agenttest="$(/usr/bin/dscl . -search /Users name "$agent")"

if [[ -z "$agenttest" ]]; then printf "\nThe system service agent does not exist: $agent\n\n"; exit 1; fi 


# find the agent's home directory
home=$(/usr/bin/dscl . -read /Users/$agent home | awk -F ': ' '{ print $NF; }' )


# get the agent's group memberships
groups_of_agent="$(/usr/bin/id -Gn $agent)"

# delete the agent's group memberships
if [[ $? -eq 0 ]] && [[ -n "$(/usr/bin/dscl . -search /Groups GroupMembership "$agent")" ]]; then

   for group in $groups_of_agent; do
      $sudo /usr/bin/dscl . -delete "/Groups/$group"  GroupMembership "$agent"
      #$sudo /usr/sbin/dseditgroup -o edit -d "$agent" -t user "$group"           
   done

fi


# delete the agent's primary group
if [[ -n "$(/usr/bin/dscl . -search /Groups name "$agent")" ]]; then
   $sudo /usr/sbin/dseditgroup -o delete "$agent"
fi

# if the agent's primary group has not been deleted ...
if [[ -n "$(/usr/bin/dscl . -search /Groups name "$agent")" ]]; then
printf "
   \e[1mWarning\e[m:
   The group memberships of the system service agent \e[1m$agent\e[m have been deleted\x21
   groups_of_agent: $groups_of_agent
   The agent's primary group \e[1m$agent\e[m, however, has not been deleted\x21
   Please, try again\x21
   Exiting ...\n
"
  exit 1
fi


# find the GeneratedUID of the agent and remove the password hash file 
# from /private/var/db/shadow/hash/
# sudo ls -a /private/var/db/shadow/hash
# sudo ls -l /private/var/db/shadow/hash/

guid="$(/usr/bin/dscl . -read "/Users/$agent" GeneratedUID | /usr/bin/awk '{print $NF;}')"

if [[ -f "/private/var/db/shadow/hash/$guid" ]]; then
   $sudo /bin/rm -f /private/var/db/shadow/hash/$guid
fi


# delete the agent
$sudo /usr/bin/dscl . -delete "/Users/$agent"

# make a backup
if [[ -d "$home" ]] && [[ "$home" != "/private/var/empty" ]]; then
   $sudo /usr/bin/ditto -rsrc -c -k "$home" "${home}-archive-$(/bin/date).zip"
fi

# remove the agent's home directory
if [[ -d "$home" ]] && [[ "$home" != "/private/var/empty" ]]; then
   $sudo /bin/rm -rf "$home"
fi


printf "\nSystem service agent account:  \e[1m$agent\e[m  successfully deleted\x21\n\n"


export IFS=$OIFS
export PATH=$OPATH

exit 0


« Newer Snippets
Older Snippets »
Showing 21-40 of 995 total