Home Linux Community Community Blogs General Linux See Behind That Shortened URL Using Python

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
# -- 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: <shortened url>'

# 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

The execute the script like so:

[+] Shortened URL:
[+]          Real URL:

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



Subscribe to Comments Feed
  • Aram Iskenderian Said:

    Why are comments automatically marked as spam and never released? If you don't want comments on your article, you might as well disable comment section.

  • Aram Iskenderian Said:

    Here is the comment that I posted earlier. Please tell me how this was a spam. While your article is good for someone who wants to learn/experiment with Python, but it is an overkill for a simple thing like this. All the URL shortening services use standard HTTP redirection and you can detect that by examining server response headers. In fact, such a thing can be easily solved a by a bash onliner. For this same article, I added a tinyurl link tinyurl . com / mmzde3o To get the original or target URL you are being redirected to, all you have to do is extract the data from in the Location: header in the server response. curl -I --insecure /dev/null [the above URL] 2>&1 | grep Location | awk '{print $2}' The result will be the link to this article.

Upcoming Linux Foundation Courses

  1. LFD211 Introduction to Linux for Developers
    09 Feb » 10 Feb - Virtual
  2. LFD411 Embedded Linux Development
    09 Feb » 13 Feb - Mississauga - ON
  3. LFD312 Developing Applications For Linux
    16 Feb » 20 Feb - Atlanta - GA

View All Upcoming Courses

Who we are ?

The Linux Foundation is a non-profit consortium dedicated to the growth of Linux.

More About the foundation...

Frequent Questions

Join / Linux Training / Board