Friday, November 2, 2007

Form based login from a shell script

The following code uses only shell scripting and curl to log in to a website protected by a form based authentication and download contents of page "about.jspx". We pay special attention to returning reasonable error messages. These snippets were tested with Tomcat 5.5.

  1. Get user name, password, and the application's URL from the command line,
    eval set -- $(getopt "u:p:b:" "$@")
    while [ "$1" != "--" ]
    case "$1" in
    -u) shift; WEB_UID="$1"; shift; ;;
    -p) shift; WEB_PWD="$1"; shift; ;;
    -b) shift; BASE_URL="${1%\/}"; shift; ;;
  2. Store URLs in variables,
    typeset aboutUrl="$BASE_URL/about.jspx"
    typeset securityAction="$BASE_URL/j_security_check"
    typeset logoffUrl="$BASE_URL/logoff.jsp"
  3. Access the URL and look for session cookie JSESSIONID,
    headers="$(curl -s -S -f -L -D - -o /dev/null --url "$aboutUrl" 2>&1)" \
    || error "Error accessing $aboutUrl: $headers"
    if [[ "$headers" =~ 'Set-Cookie: JSESSIONID=([^;]*)' ]]
  4. If JSESSIONID cookie is set, submit user name and password to the login form. On success, the application will redirect us to the original URL. Variable "about" will store the page source or the error message.
    about="$(curl -s -S -L -f -b "JSESSIONID=$sid" -o - \
    -d "
    j_username=$WEB_UID" \
    -d "
    j_password=$WEB_PWD" \
    --url "
    $securityAction" 2>&1)" \
    || error "Error submitting credentials to $securityAction: $about"
  5. Parse the page for some useful information (looking for <sysdate date="20071102">)
    if [[ "$about" =~ 'sysdate date=\"([^\"]*)\"' ]]
  6. Finally, hit the logoff URL so that the application may clean up.
    curl -s -f -b "JSESSIONID=$sid" --url "$logoffUrl" -o /dev/null
For more information, see cURL and libcurl