Clean some Safari cookies via a Perl script

Feb 10, '09 07:30:00AM

Contributed by: Anonymous

If you want to clean your Safari cookies, but you want to keep certain (login) cookies, you could manually remove cookies from the Safari preferences menu -- Safari » Preferences » Security » Show Cookies. However, that can be time consuming. As an alternative, try this Perl script:

#!/usr/bin/perl

use strict;
use warnings;
use File::Slurp;

### Edit this to your liking (put a pipe character between two words)
my $keepCookiesWith = "aap|teun|betterbe|tweakers.net";

### Put your OS X short username here (there should be a directory with the same name under /Users)
my $userName = "teun";

### ### ### Don't edit beneath this line unless you know some Perl
my $path = "/Users/$userName/Library/Cookies/Cookies.plist";
my @date = localtime();
my $date = sprintf("%04d%02d%02d", $date[5] + 1900, $date[4] + 1, $date[3]);
my $cookies = read_file($path);
rename ($path, $path . "." . $date);

open(WH, ">$path");
print WH <<EOF;
<?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">
<array>
EOF
while ($cookies =~ m#(\s*<dict>.+?</dict>)#gs)
{
    my $cookie = $1;
    if ($cookie =~ /$keepCookiesWith/)
    {
        print WH $cookie;
    }
}
print WH <<EOF;

</array>
</plist>
EOF
close (WH);
This code will back up your Cookies.plist file, and create a new one with only the cookies that match the regex you put in $keepCookiesWith.

To use the script, save the code as cleanSafariCookies.pl (or some other name), somewhere on your hard disk. Put something in $keepCookiesWith and in $userName. Give the file execute permission with chmod 755 cleanSafariCookies.pl, and run it in Terminal by typing (assuming you're in the directory where the program is located) ./cleanSafariCookies.pl.

This could easily be rewritten in the language of your choice, if you desire.

Comments (6)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20090207074358144