December 28, 2013

See Behind That Shortened URL Using Python

I'm a big user of URL shortening, especially when sending links via email to family, friends, and/or coworkers. But there are occasions when I come across a shortened URL either on a website or from an unknown source.  So, with just a few lines of Python code, I managed to write a script that, given a shortened URL, will reveal the actual URL behind the shortened link.

Copy the following code into a file and make it executable:

#!/usr/bin/env python
#
# showURL.py
#
# -- simple python script to take a shortened url
# -- and return the true url that it's pointing too
#
import sys
import urllib2

# get the url from the command-line, bail
# if nothing was entered and show usage
if len(sys.argv) != 2:
print '[!] Usage: showURL.py <shortened url>'
sys.exit(1)

# store the given url
url = sys.argv[1]

# connect to the url and retrieve the real
# url
shortenedUrl = urllib2.urlopen(url)
realUrl = shortenedUrl.geturl()

# display result
print '[+] Shortened URL: ' + url
print '[+] Real URL: ' + realUrl

# done
sys.exit(0)

The execute the script like so:

./showURL.py http://tinyurl.com/x0vw
[+] Shortened URL: http://tinyurl.com/x0vw
[+]          Real URL: http://www.linux.com/

There you have it.  A quick and easy way to show what's behind those shortened URLs.

Click Here!