Year of Python (YOP) – Week Fourteen

06Apr15

Hello Reader!

This weeks script comes out of some playing around I was doing with sqlite databases.  In the class I teach, we were talking about Mozilla Firefox artifacts, along with Google Analytics Cookies.  While I was talking about the different types of utm* cookies that are present, I thought about writing a quick script to parse some of the data in a __utmz cookie.

Now there are other people that have worked with Google Analytic Cookies, including Mari DeGrazia who wrote a very nice program to parse Cookie files, but I was looking for something that would let me play around with some different python concepts.

First was of course just connecting to a sqlite database and running a query against it.  Next was taking those results and processing the data.  Finally just playing around a bit more with python functions to convert an integer to a date/time stamp (or in this case just a time stamp).

So first we have a simple function to handle the timestamp:

def unixtime(timevalue):
    return datetime.datetime.utcfromtimestamp(int(timevalue))

Now there’s a simpler way to handle formatting with the python datetime module, but I wanted to put it in to a function just to practice utilizing them.

Next we have the section that just opens the database and connects to it:

try:
    db_connect = sqlite3.connect(cookies_db)
    db_cursor = db_connect.cursor()
    db_cursor.execute('SELECT * FROM moz_cookies WHERE name = "__utmz"')
    db_row = db_cursor.fetchall()
except Exception, error:
    print error

Here I just wanted to set up some error checking when I open the database and do my specific select statement.  Basically if it works, great, if it doesn’t print the error saying why.

Finally we just pull out the data we want, and print it to the screen:

for rows in db_row:
    utmz = rows[5]
    utmz_segment = utmz.split(".")
    cookie_last_time = unixtime(utmz_segment[1])
    print "Domain: {}\t\t\tLast Visit: {}:{}:{}\t\tNo of sessions: {}".format(rows[1], cookie_last_time.hour, cookie_last_time.minute, cookie_last_time.second, utmz_segment[3])

And that’s it.  Just a real simple script to parse out the data quickly and look it over if necessary.

Until next week!

https://github.com/CdtDelta/YOP

Advertisements


No Responses Yet to “Year of Python (YOP) – Week Fourteen”

  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: