Linux.com

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
#
# 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.

 

Comments

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
    08 Dec » 09 Dec - Virtual
    Details
  2. LFS220 Linux System Administration
    08 Dec » 11 Dec - Virtual
    Details
  3. LFD331 Developing Linux Device Drivers
    15 Dec » 19 Dec - Virtual
    Details

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