Showing posts with label My Python Scripts. Show all posts
Showing posts with label My Python Scripts. Show all posts

Friday, January 30, 2015

USD to INR Exchange Rate Calculator (Xoom, PayPal) Script in Python

Written by Pranshu Bajpai |  | LinkedIn

I frequently transfer money to India. For this reason, I find myself calculating amounts pertaining to USD to INR conversions using major remit websites such as the following:
  • Xoom
  • PayPal
  • Remitly
  • RIA Money Transfer
  • MoneyDart - Money2Anywhere
  • Trans-Fast
  • USForex Money Transfer
  • IndusInd Bank - Indus Fast Remit
  • State Bank of India
  • ICICI Money2India
  • Axis Bank - AxisRemit
  • Western Union

Since almost all of these websites offer more or less similar services, I usually choose the one that is offering me the best exchange rate. Having said that, I was quickly annoyed by having to visit each of these websites to compare them and determine the one that is offering the best USD to INR exchange rate on the present day. For this reason, I decided to write a Python web scrapping script that would go online, locate the exchange rates germane to all of these major websites and then show them to me for comparison.

Usage: python usdtoinr.py

Download: Github: https://github.com/lifeofpentester/usdtoinr




By default, it shows you the exchange rate grabbed from xoom (without any switch). Or, you can use '-x' or '--xoom' switch to do the same thing.

By using the '-a' or '--all' switch, you can view the current exchange rates corresponding to all major remit websites.



Initially, my 'usdtoinr' python script only displayed the current exchange rate from the major websites, but then I realized that it would be better if they could convert an amount in USD (US dollars) to an amount in INR (Indian Rupees). Accordingly, I added this functionality in the script. You can use the '-c' or '--convert' switch for this purpose.



As I started using PayPal, I added another function in my script that would show me an amount in USD (US dollars) converted to an amount in INR (Indian Rupees) and then deduct PayPal's fees of 4 percent from this amount to show me the money that someone would actually receive in India. To invoke this function, use the '-p' or '--paypal' switch.


Of course, '-h' or '--help' is to see the usage information.

That's all the functionality that is coded in the script at the moment since that's all I needed. With time, I may add more functions should I need them. As with all web scrapping scripts, the functionality of the script depends on the websites from where it is capturing the information pertaining to the exchange rates. If those websites change with time, it might result in the script breaking down. If that is the case, or if you want some other functionality added, feel free to modify the code.

Note: argparse is a nice library that you can use to allow for command line arguments or switches in your scripts.

Note: The ASCII text banner in the script has been generated with a utility called 'figlet'

Source Code:


If you would like to read the code, here it is:


#!/usr/bin/python

import requests
from bs4 import BeautifulSoup
import argparse
import re
import time

def _xoom():
 r = requests.get('https://www.xoom.com/india/send-money')
 data = r.text

 soup = BeautifulSoup(data)

 for rate in soup.find_all('em'):
  return rate.text

def _all():
 r = requests.get('http://www.compareremit.com')
 print "[+] Requested information!"
 data = r.text
 print "[+] Grabbed all exchange rates online!"
 soup = BeautifulSoup(data)
 for rate in soup.find_all('div',{"class":"c_logo_box"}):
      print rate.a.img['alt'] 
      print rate.span.text

def _rate_calc():
 ratetext = _xoom()
 print "[+] Requested exchange rate from Xoom!"
 found = re.search("(?<=\=)(.*?)(?=I)", ratetext)
 print "[+] Located today's exhange rate!" 
 rate = float(found.group())
 print "[+] Converting USD to INR now..."
 amount = args.convert * rate
 return amount

def _paypal():
 ratetext = _xoom()
 print "[+] Requested exchange rate from Xoom!"
 found = re.search("(?<=\=)(.*?)(?=I)", ratetext)
 print "[+] Located today's exchange rate!" 
 rate = float(found.group())
 print "[+] Converting USD to INR now..."
 print "[+] Calculating amount left after PayPal's 4 percent fee..."
 amount = 0.96*(args.paypal*rate)
 return amount
 

parser = argparse.ArgumentParser(description="Script for USD to INR calculations")
parser.add_argument('-x', '--xoom', help='exchange rate from xoom.com', action='store_true')
parser.add_argument('-a', '--all', help='exchange rate from all major remit websites', action='store_true')
parser.add_argument('-c', '--convert', help='USD to INR conversion using current exchange rate', type=float)
parser.add_argument('-p', '--paypal', help='amount after deducting PayPal\'s 4 percent fees', type=float)
args = parser.parse_args()




print """               _ _        _           
 _   _ ___  __| | |_ ___ (_)_ __  _ __ 
| | | / __|/ _` | __/ _ \| | '_ \| '__|
| |_| \__ \ (_| | || (_) | | | | | |   
 \__,_|___/\__,_|\__\___/|_|_| |_|_|   

                          --by Pranshu
"""

_time = time.asctime(time.localtime(time.time()))

print "[i] " + _time


if args.xoom:
 rate = _xoom()
 print "[i] Exchange Rate: " + rate
elif args.all:
 _all()
elif args.convert:
 amount = _rate_calc()
 print "\n[i]Amount in Rupees according to the exchange rate today: %f" %amount
elif args.paypal:
 amount = _paypal()
 print "\n[i]Amount in Rupees after deduction of Paypal's fees: %f" %amount
else:
 rate = _xoom()
 print "[i] Exchange Rate: " + rate
 #parser.print_help()

Thursday, January 8, 2015

PhD Comics Downloader | Python Script to Download Piled Higher and Deeper Comics

Written by Pranshu Bajpai |  | LinkedIn

PhD Comics, by Jorge Cham, provide a funny (but accurate) glimpse into the life of a graduate student. Being a graduate student myself, I have always enjoyed reading this comic.

At some point, I decided to read a bunch of these comic during my travel when I wouldn't be able to access the Internet. Since this is an online comic, this was a problem. I wrote a small python scraping script that is able to visit different pages on the phdcomics website, locate the comic GIFs, and download them on local disk for reading later on.

Usage: python downloadphdcomics.py

Download: Githubhttps://github.com/lifeofpentester/phdcomics


Note that the start comic number and end comic number is hard coded in the script as '1' and '1699' respectively. You can modify the script in any text editor to download a different range of comics.

You can store all of these GIFs in a ZIP file and change the extension from ZIP to CBR. Then, you can use any CBR reader to read these comics.


In case you are interested in reading the code, here it is:


#!/usr/bin/python

"""The PhD Comics Downloader"""
"""
This code fetches PhD comics from www.phdcomics.com
and saves to '/root/'

Written by: Pranshu
bajpai [dot] pranshu [at] gmail [dot] com

""" 


from bs4 import BeautifulSoup
from urllib import urlretrieve
import urllib2
import re

for i in range(1, 1699):

    url = "http://www.phdcomics.com/comics/archive.php?comicid=%d" %i 
    html = urllib2.urlopen(url)
    content = html.read()
    soup = BeautifulSoup(content)

    for image in soup.find_all('img', src=re.compile('http://www.phdcomics.com/comics/archive/' + 'phd.*gif$')):
        print "[+] Fetched Comic " + "%d" %i + ": " + image["src"]
    outfile = "/root/" + "%d" %i + ".gif"
    urlretrieve(image["src"], outfile)


Wednesday, October 9, 2013

'remindme.py' A Simple Python Script To Remind You About Events That You Want To Remember | Pranshu

Written by  | Google+ Pranshu Bajpai | LinkedIn

This is a simple Linux utility that I coded long ago for personal use that would remind me about events that I want to remember. It reminds you of a given event on a certain data after you log onto your computer on that date.

This is a basic script in Python. Please feel free to improve it to suit your particular needs.

Functionality:

-Displays a Graphical Notification in Top Right Corner Each Time you Login
-You Manually Enter Events and Corresponding dates

How to Use:

Create a Folder called "python codes" in your root directory and place "remindme.py" there

(Path is hard coded in the script. This is bad coding, but I was in a hurry. Like I said, feel free to improve the code)

Create a File in this folder called "remindme.data"

Enter the Dates and Events in this format and Save:

MonthDay Event
Example for 10th of Oct:
1010 EventName



Add remindme.py to 'Startup'  (Applications -> System Tools -> Preferences -> Startup)



(I have added a module for 'Auto-Add to Startup' but it was giving issues, so I commented it out, feel free to correct that)

Each Time you login now, remindme will check the remindme.data file and see if there's an Event listed for today. If an event is listed, it will display a notification:




If you're new to Python you might like to read the code:

#!/usr/bin/python

import time       #for checking current date
import gtk.gdk    
import pynotify   #For Notifications

today = time.strftime("%m%d")
Remind_Me_Path = "python /root/python\ codes/remindme.py"  #Path to script


#Following Function that checks whether Startup Entry is already made
#Coz We don't want multiple startup entries made, everytime program runs

def check_startup_entry():                   
 flag = 0
 file = open ("/root/.bash_profile", 'r')
        for line in file:
                if Remind_Me_Path in line:
   flag = 1
 if flag == 0:
  add_to_startup()  

#Following Function adds the startup entry if it check_startup didn't find one

def add_to_startup():
 file = open ("/root/.bash_profile", 'a+')
 file.write(Remind_Me_Path)
 file.write("\n")
 file.close() 

#Following Function checks for Events in Remind_Me.data file

def check_for_event():
 file = open ("/root/python codes/remindme.data", 'r')
 for line in file:
  if today in line:
   notify(line)
 file.close()


#Following Function is called by check_for_event for notification

def notify(arg):
 pynotify.init("Basic")
 n = pynotify.Notification("Remind_Me: " + arg)
 n.set_hint('x', gtk.gdk.screen_width()/2.)
 n.set_hint('y', gtk.gdk.screen_height()/2.)
 n.show()

check_startup_entry()
check_for_event()

Thursday, September 5, 2013

HuntPass.py: Python Script That Searches for Passwords [Or Any String] in a File Then Saves Results to a New File

Written by: Pranshu Bajpai | Find Pranshu on Google+ And LinkedIn

It is amazing how people on a shared LAN are still typing away their confidential information over http (non-SSL, un-encrypted) links. Someone sniffing the LAN could easily capture such information in plaintext.

During a recent test, I used Ettercap for sniffing the local LAN.

Since this was a large internal network with a lot of users, it was able to discover a LOT of passwords in transit in plaintext form over the link. After dumping, the problem was to sort these passwords in the Ettercap dump file. So I wrote this simple python script.

Functionality: The script looks for user-supplied passwords strings in a given file and then stores the 'unique' passwords found to a new file. It just gets things done. Please feel free to improve it if you feel the need to do so.

Usage: python HuntPass.py <InputFile> <OutputFile> <SearchString>

Download: Github - https://github.com/lifeofpentester/huntpass

Example:

Here, I have saved my Ettercap sniffer results to a file called 'etterlog'. This is my <InputFile>


I am looking for lines with the word "PASS" ( for password) in them. I want these passwords saved in a file called 'Passwords.txt'


             #python HuntPass.py etterlog Passwords.txt PASS




Only two lines in 'etterlog' had 'PASS', so total passwords found are 2 in this case.

They are stored in a separate file called 'Passwords.txt'.





If a new user misses out an argument while running the program, it exits printing 'Usage' information.




If you're new to Python, you might like to read the code. Here it is:

#!/usr/bin/python

import sys  #Taking Arguments in Terminal
import os   #Clearscreen
import time

if len(sys.argv) < 4:  #First Argument is always the program name
        sys.exit('Usage: python HuntPass.py <InputFile> <OutputFile> <SearchString>')    #Exit if New User doesn't give all the Arguments

os.system('clear')

time_on_your_system = time.asctime(time.localtime(time.time()))

print "\t\t_____________", time_on_your_system, "_____________"
print "\n\t\t_____A Small Script to find Passwords in Dumps_____"

print "\n\t\t####################################################"

print "\n\t\t#________________Written by Pranshu_________________#"

print "\t\t______________________________________________________"



filename = sys.argv[1]  #Input File

newfile = sys.argv[2]   #Output File

f1 = open (filename, "r") #Read Mode

f2 = open (newfile, "a+") #Append Mode

search_string = sys.argv[3] #Text to Search

print "\n\tLooking in", filename + " | " + "Storing Result in", newfile + " | " + "Searching for", search_string

flag = raw_input("\n\n\t\tProceed? (y/n): ")

if flag == 'y':
    lines_seen = set()  #A Data Structure to store lines seen, to prevent duplicate passwords while saving

    total_pass = 0

    for line in f1:
        if line not in lines_seen:  
            if search_string in line:
                f2.write(line)
                lines_seen.add(line)
                total_pass = total_pass + 1
    print "\n\t\tTotal Passwords found are: ", total_pass
    print "\n\t\tSaved in ", newfile
f1.close()
f2.close()
print "\n\t\t________________________QUITTING!____________________\n\n"



Like I said, feel free to improve it according to your needs.