Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Tuesday, 24 June 2014

How To Send Email With Python (smtplib and MIMEText)

It is actually pretty easy to  send emails with python. The smtplib module provides the necessary "tools" to send mail to any Internet machine with an SMTP or ESMTP listener daemon.

In this script I am using gmail, but it is not limited to Google as long as your provide the correct smtp server + port.

Python 2.7.3 

  1. from email.mime.text import MIMEText  
  2. import smtplib  
  3.   
  4. def sendmail(to,subject,text):  
  5.     user = 'name@gmail.com'  
  6.     pwd = 'password'  
  7.     msg = MIMEText(text)  
  8.     msg['From'] = 'james@gmail.com'  
  9.     msg['To'] = to  
  10.     msg['Subject'] = subject  
  11.     try:  
  12.         smtpServer = smtplib.SMTP('smtp.gmail.com', 587)  
  13.         smtpServer.ehlo()  
  14.         smtpServer.starttls()  
  15.         smtpServer.ehlo()  
  16.         smtpServer.login(userpwd)  
  17.         smtpServer.sendmail(user, to, msg.as_string())  
  18.         smtpServer.close()  
  19.         print "mail sent."  
  20.     except SMTPException:  
  21.         print "failed."  

Let's take it for a test drive... 


How To Send Email With Python (smtplib and MIMEText)

 Seems to work.

How To Send Email With Python



Sunday, 18 May 2014

How To Geolocate an IP Address with Python

Python 2.7.3

In order to geolocate an IP address with Python you will need a database to match an IP to a location. I am using the Maxmind database, which is available for free.
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
gunzip GeoLiteCity.dat.gz
Next, we install the Pure Python API for Maxmind's GeoIP databases (https://github.com/appliedsec/pygeoip)
sudo pip install pygeoip
Code
import pygeoip
rawdata = pygeoip.GeoIP('/home/user/GeoLiteCity.dat')
def ipquery(ip):
    data = rawdata.record_by_name(ip)
    country = data['country_name']
    city = data['city']
    longi = data['longitude']
    lat = data['latitude']
    print '[x] '+str(city)+',' +str(country)
    print '[x] Latitude: '+str(lat)+ ', Longitude: '+ str(longi)
Running the code
How To Geolocate an IP with Python

UPDATE - PYTHON 3 (Ubuntu 16.04)

sudo pip3 install pygeoip
Download Maxmind location-data
user@user:~$ cd Desktop
user@user:~/Desktop$ mkdir geolocate
user@user:~/Desktop$ cd geolocate
user@user:~/Desktop/geolocate$ wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
user@user:~/Desktop/geolocate$ gunzip GeoLiteCity.dat.gz

Code (save as geo.py in folder geolocate)

import pygeoip
rawdata = pygeoip.GeoIP('/home/user/Desktop/geolocate/GeoLiteCity.dat')
def ipquery(ip):
    data = rawdata.record_by_name(ip)
    country = data['country_name']
    city = data['city']
    longi = data['longitude']
    lat = data['latitude']
    print ('[x] '+str(city)+',' +str(country))
    print ('[x] Latitude: '+str(lat)+ ', Longitude: '+ str(longi))

#optional

ip = input("What's your ip? ")
print (ipquery(ip))

Run the code

user@user:~/Desktop/geolocate$ python3 geo.py
What's your ip? 207.38.138.230
[x] New York,United States
[x] Latitude: 40.7449, Longitude: -73.9782

Friday, 11 April 2014

VTC/USD, VTC/EUR and VTC/GBP Python Script

You may  want download the file here: https://drive.google.com/file/d/0B06EJahqJCOCVzY1eTVMYTZDS00/edit?usp=sharing 

import urllib2
import json
import time
import pandas as pd
from pandas import Series, DataFrame
from urllib2 import URLError
import ystockquote

# Accessing VTC/BTC price from Cryptsy

def vtcbtc():
    try:
        raw = urllib2.urlopen("http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid=151").read()
        dictionary = json.loads(raw)
        #BID
        bidraw = dictionary['return']['VTC']['buyorders']
        newformatb = pd.DataFrame(bidraw)
        newnameb = newformatb.rename(columns={'price': 'BID'})
        global finalbid1
        finalbid1 = newnameb[0:1]
    except URLError, error:
        print error

#BTC/USD price from BTC-e

def btcusd():
    btcePrices = urllib2.urlopen("https://btc-e.com/api/2/btc_usd/ticker").read()
    btcejson = json.loads(btcePrices)
    global btcelastP 
    btcelastP = btcejson['ticker']['last']
    
    global btcelastB #bid
    btcelastB = btcejson['ticker']['sell']
    
    global btcelastA #ask
    btcelastA = btcejson['ticker']['buy']

def eurusd():
    global eur
    eur=ystockquote.get_price('eurusd=X')

def gpbusd():
    global gbp
    gbp=ystockquote.get_price('GBPUSD=X')

# Calculates Vert/USD price

while True:
    vtcbtc()
    btcusd()
    eurusd()
    gpbusd()
    pricevtcbtc = float(finalbid1["BID"])
    VertUSD = btcelastP * pricevtcbtc
    VertEUR = VertUSD / float(eur)
    VertGBP = VertUSD / float(gbp)
    print time.strftime('%I:%M%p %Z on %b %d, %Y')
    print "VERT/$", VertUSD
    print "VERT/EUR", VertEUR
    print "VERT/GBP", VertGBP
    print
    time.sleep(20) #20 seconds.  
 
 
Sample Output
 

Sunday, 2 March 2014

Wednesday, 29 January 2014

Tuesday, 21 January 2014

How to hash and crack UNIX passwords in python

Crypt module

I am using the crypt module here, which is a one-way hash function based upon a modified DES algorithm. You can easily adjust the script to crack secure hash algorithms (SHA1, SHA224, SHA256, SHA384, and SHA512 (defined in FIPS 180-2) as well as RSA’s MD5 algorithm ) by using the hashlib  module.

Crypt Overview

import crypt
crypt.crypt("user", "AD")
'AD5Qg2vQhsLRw'

AD is the salt, which is a random two-character string which will be used to perturb the DES algorithm in one of 4096 ways.

The python password cracking script

import crypt
def testPass(hashpass):
    salt = hashpass[0:2]
    dictionary = open('dictionary.txt', 'r') #this is our dictionary file
    for word in dictionary.readlines():
        word = word.strip('\n')
        crypto = crypt.crypt(word,salt)
        if crypto == hashpass:
            print "[+] Password: "+word+"\n"
            return
    print "[-] Password Not Found.\n"
    return

def main():
    hashpass = open('passwords.txt', 'r') #file with hashed password
    for line in hashpass.readlines():
        if ":" in line:
            user = line.split(':')[0]
            hashpass = line.split(':')[1].strip(' ')
            print "[*] Cracking Password For: "+user
            testPass(hashpass)
if __name__ == "__main__":
    main() 
 
Save the script as cracker.py.
You also need to create a dictionary.txt and password.txt  (with the hashed passwords) file to successfully run the program.

Create a new folder and put the three files into it, afterwards simply run 
python cracker.py

You can download all of the files here: Drive