Tonight I decided to relax a bit and what better way of relaxing is there for a geek then to do some bash scripting?! So for fun and no profit I decided to try and benchmark pages with ab, Apache HTTP server benchmarking tool, which are behind a login. Turns out, it’s pretty easy after reading some man pages ;)
ab’s help pages gives a few possible leads. We can POST data with the
-p option, which would be great if we would like to benchmark the login process itself. But, we want to test the page after the login. So we’ll need the ab’s
-C option, which allows for passing cookies in
The login process itself is done with curl as it allows us to POST data to a server and store cookies received from the server in a cookie jar. curl writes the cookies in a Netscape cookie file format, whatever that is. Sample line is:
# Netscape HTTP Cookie File # http://curl.haxx.se/rfc/cookie_spec.html # This file was generated by libcurl! Edit at your own risk. example.com FALSE / FALSE 0 PHPSESSID [RANDOM_SESSION_ID]
From this output we’re interested in the [RANDOM_SESSION_ID] cookie value, as the cookie name is simply PHPSESSID and we can just hard-code it. To get the value, we use some obscure *nix magic:
cut. grep to grep the line with the PHPSESSID cookie and cut to cut out the 7th column from that line. Easy!
Now that we have the value of the cookie, we just pass it along with ab and done! We’re benchmarking pages behind a login.
The entire script is:
#!/bin/bash COOKIE_JAR="/tmp/ab-login-cookie-jar" echo "Logging in..." curl -c $COOKIE_JAR -d username=user -d password=h4x0r http://example.com/login echo "Getting the session id..." PHPSESSID=$(cat $COOKIE_JAR | grep PHPSESSID | cut -f 7) echo "The session id is:" echo $PHPSESSID echo "==================" ab -n 10 -c 10 -C PHPSESSID=$PHPSESSID http://example.com/loggedin
The script is also on Github here.
Tip: use ab’s -v option to test for HTTP codes and/or redirects to see if you are really on the page you want to be.