how to run a python script in the background as a service

December 17, 2008 by lazysource

nohup python pyscript.py &

How to play with udp in python

December 3, 2008 by lazysource
#!/usr/bin/env python
from socket import *
host = "10.0.0.148"
port = 514
buf = 1024
address = (host,port)
sock = socket(AF_INET,SOCK_DGRAM)
sock.bind(address)
while 1:
    data,addr = sock.recvfrom(buf)
    if not data:
        print "Client has exited!"
        break
    else:
        print data
sock.close()

THE RESULTS LOL

November 19, 2008 by lazysource

I didint know whether I should have given up on non threading or not. I nearly fell asleep waiting for the iterations to complete. But here are the results:(on a ubuntu 8.10 latest kernel core 2 duo t5000 series):

Threading:

10 loops, best of 3: 1.78 sec per loop

Non-Threading:

10 loops, best of 3: 1.77 sec per loop

And the windows result:

10 loops, best of 3: 535 msec per loop

Why do my threading attempts always fail?

Brute force MD5 cracker…. Linux Multithreaded (need a quad core to test this on a long password)

November 19, 2008 by lazysource
#!/usr/bin/env python
import threading
import timeit
import hashlib
import sys
# This is the much better version using multithreading.
# Created by blu3man@gmail.com
#
#
# Many thanks to Rohit Krishna Kumar http://www.geocities.com/rohitkkumar
# brute.alpha was loosely based of his work. and improved

class brute(threading.Thread):
    def __init__(self, depth, testrange, vaultpass):
    threading.Thread.__init__(self)
        self.depth = depth
        self.vaultpass = vaultpass
        self.max = depth
        self.password = ""
        self.process()
        print self.password

    def process(self):
        l = []
        guess = self.listify(testrange)
        for i in range(self.max):########THIS IS THE BEGINING
            l.append('')
        self.alpha(l, self.depth, guess)

    def alpha(self, l, depth, guesses):      
        if(depth==0):                       # String has been generated
            s=""                            
            for k in l:                     # Make the list into a string
                s+=k                       
            self.crak(s, self.vaultpass)         # Call your password cracking routine here ;)
        else:                               
            for i in range(0, len(guesses)): 
                l[self.depth-depth]=guesses[i]
                self.alpha(l,depth-1, guesses)

    def listify(self, chars):
        possible = []
        for i in range(0, len(chars)):
            possible.append(chars[i])
        return possible

    def crak(self, trial, vault):
        test = hashlib.md5(trial).hexdigest()
        if test == vault:
            self.password = "Unencrypted data: %s" % trial

hashpass = "21ad0bd836b90d08f4cf640b4c298e7c" # our hash we want to crack ... in this case its "bb" hashed.
testrange = "0123456789abcdefghijklmnopqrstuvwqyzABCDEFGHIJKLMNOPQRSTUVWXYZ" # our character range
maxilength = 3 # our maximum length
def main():)
    for i in range(1, maxilength + 1): #this time we have a thread for each length.
        t = brute(i, testrange, hashpass)
            t.setDaemon(True)
            t.start()

if __name__=="__main__":

    main()

double day. MD5 brute forcer (single threaded)

November 19, 2008 by lazysource
import hashlib
import sys
# by blu3man@gmail.com
#for all you windowz users. a Single threaded md5 cracker
# have fun sleeping
# Many thanks to Rohit Krishna Kumar http://www.geocities.com/rohitkkumar
# brute.alpha was loosely based of his work. and improved.....

class brute:
    def __init__(self, depth, testrange, vaultpass):
        self.depth = 1
        self.vaultpass = vaultpass
        self.max = depth
        self.password = ""
        self.process()
        print self.password

    def process(self):
        l = []
        guess = self.listify(testrange)
        for i in range(self.max): ########THIS IS THE BEGINING
            l.append('')
            self.alpha(l, self.depth, guess)
            self.depth += 1

    def alpha(self, l, depth, guesses):     
        if(depth==0):                       # String has been generated
            s=""                           
            for k in l:                     # Make the list into a string
                s+=k                       
            self.crak(s, self.vaultpass)
            print s                         # Call your password cracking routine here ;)
        else:                              
            for i in range(0, len(guesses)):
                l[self.depth-depth]=guesses[i]
                self.alpha(l,depth-1, guesses)

    def listify(self, chars):
        possible = []
        for i in range(0, len(chars)):
            possible.append(chars[i])
        return possible

    def crak(self, trial, vault):
        test = hashlib.md5(trial).hexdigest()
        if test == vault:
            self.password = "Unencrypted data: %s" % trial

hashpass = "21ad0bd836b90d08f4cf640b4c298e7c"  # add in the hash you want to break here
testrange = "0123456789abcdefghijklmnopqrstuvwqyzABCDEFGHIJKLMNOPQRSTUVWXYZ" #list of letters you want to use
maxilength = 2 #how long you want to check... ie 2 characters long
manly = brute(maxilength, testrange, hashpass)
manly

Concept port scanner

November 18, 2008 by lazysource
#!/usr/bin/env python
import socket
import sys
#usage scan host portmax
#basic port scanner without using pings
target = str(sys.argv[1])
portmax = int(sys.argv[2])
def useless():
    return 0
for n in range(portmax):
   sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   address = (target, n)
   try:
      sock.connect(address)
      print address, "IS OPEN (listening)"
   except socket.error:
      useless()
   sock.close()

MD5 Encryption/password authentication – concept

November 17, 2008 by lazysource
#!/usr/bin/env python
# Lets make a basic authentication program using MD5 as our encryption for our passwords
import hashlib

# to make our md5 hashes
def hasher(someinput):
    stuff = hashlib.md5(someinput).hexdigest()
    return stuff

class authman:    ###### I was going to add more to this class but am now tired and ill go to sleep now..... im sure you can figure it out
    def __init__(self, manifest):
        self.manifest = manifest
        self.userpass = []
        self.splitter()

    def splitter(self): #does the initial caching of the file to the list
        try:
            datafile = open(self.manifest, "r")
        except IOError: # if the file doesnt exist
            datafile = open(self.manifest, "w")
            datafile.write("exampleuser:examplepass")
            datafile.close()
            datafile = open(self.manifest, "r")
        count = 0
        for line in datafile:
            for word in line.split(":"):
                count += 1
                if count == 3:
                    self.userpass.append([x, y])
                    count = 1    
                if count == 1:
                    x = word.strip()
                if count == 2:
                    y = word.strip()
        self.userpass.append([x, y]) # add the last user as he is not in the loop
        datafile.close()

    def auth(self, useri, passi):
        good = 0
        for login in self.userpass:
            if login[0] == useri and login[1] == passi:
                good = 1
        if good == 1:
            return "AUTHENTICATED"
        else:
            return "FAILURE"

    def useradd(self, useri, passi):
        datafile = open(self.manifest, "a")
        userline = "%s:%s\n" % (useri,passi)
        datafile.write(userline)
        datafile.close()

def menus():
    try:
        menu = input("1)add user\n2)test user\n3)exit\n\n What would you like to do?")
        if menu==1:
            username = raw_input("what would you like to use as your username?")
            password = raw_input("and password?")
            newpass = hasher(password)
            authgator.useradd(username, newpass)
            menu = 0
            menus()
        if menu==2:
            username = raw_input("please enter the username you wish to test?")
            password = raw_input("and password?")
            newpass = hasher(password)
            result = authgator.auth(username, newpass)
            print result
            raw_input("press to continue")
            menu = 0
            menus()
        if menu==3:
            exit
    except NameError:
        print "bad option"
        menus()

if __name__ == "__main__":
    f = "userlist.txt"
    authgator = authman(f)
    menus()

The smallest rss reader I could make in python (quite old code i found)

November 15, 2008 by lazysource
#!/usr/bin/env python
import urllib2
from xml.dom import minidom, Node
def dout(part):
    if(itemnode.nodeName == part):
        part = part + ":\n"
        for textnode in itemnode.childNodes:
            part += textnode.nodeValue
        print part + "\n"
feed = urllib2.urlopen(raw_input("enter address of the feed"))
xmldata = minidom.parse(feed)
for node in xmldata.getElementsByTagName('item'):
    for itemnode in node.childNodes:
        dout("title")
        dout("description")

A wecrawler using no 3rd party plugins.

November 15, 2008 by lazysource
#!/usr/bin/env python
import urllib2
from sgmllib import SGMLParser, SGMLParseError

#################################################################
################# web crawler ##################################
#################################################################
#
#Copyright (c) 2008, blu3man@gmail.com
#All rights reserved.
#
#Redistribution and use in source and binary forms, with or without modification,
#are permitted provided that the following conditions are met:
#
#    * Redistributions of source code must retain the above copyright notice,
#    this list of conditions and the following disclaimer.
#    * Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#    * Neither the name of the residence nor the names of its contributors
#    may be used to endorse or promote products derived from this software
#    without specific prior written permission.
#
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
#ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
#WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
#IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
#INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
#NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
#PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
#WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
#ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
#POSSIBILITY OF SUCH DAMAGE.
#
########################################################################
#Other liscesees include http://emptywebsite.com/ (for using the site in my code) to which I found no liscence.
#

##########################Link Discoverer#############################

class urllister(SGMLParser):                                        
    def reset(self):                                                     
        SGMLParser.reset(self)                                      
        self.urls = []                                              
        self.href = ''                                               

    def start_a(self, attrs):                                       
        for tag, value in attrs:                                    
            if tag == 'href':                                       
                self.href = value                                   
            if self.href not in self.urls: #make sure we arnt in the list already
                    if self.href[:4] == "http":  # make sure we are a fqdn over http protocole
                        self.urls.append(self.href)                
######################################################################

######################text searcher####################################
class textcrawl: # search = what i want... page = source(read) .... url = address                                           
    def __init__(self, search, page, url):                         
        found=page.find(search)                                    
        fcount = 0                                                 
        while found > -1:                                          
            fcount += 1                                            
            found=page.find(search, found+1) #start from 1 character after previous occurance
        self.answer = "found %d occurences of %s at %s" % (fcount, search, url)
#####################################################################

###########################the spider itself###########################
#####http://emptywebsite.com/ is a site with no links#################
class linkwalker:
    def __init__(self, webpage, phrase):
        self.phrase = phrase
        #results = open('results.txt', 'w')
        self.purl = webpage
        self.been = []
        self.manifest = self.nomnoms(webpage)
        for link in self.manifest:
            if link not in self.been:
                emptyness = self.nomnoms(link)
                for recurl in emptyness:
                    self.manifest.append(recurl) #behold the power of this

    def nomnoms(self, purl): #eats pages.... ALIVE and writes results to a file
        self.been.append(purl)
        try:
            sock = urllib2.urlopen(purl)
        except urllib2.URLError:
            duck = [ 'http://emptywebsite.com/' ]
            return duck
        except urllib2.HTTPError:
            duck = [ 'http://emptywebsite.com/' ]
            return duck
        if(sock):
            page = sock.read()
            parser = urllister()
            try:
                parser.feed(page)
            except SGMLParseError:
                duck = [ 'http://emptywebsite.com/' ]
                return duck
            sock.close()
            parser.close()
            findstuff = textcrawl(self.phrase, page, purl)
            textfound = findstuff.answer
            self.fwriter(textfound)
            return (parser.urls)
        else:
            duck = [ 'http://emptywebsite.com/' ]
            return duck

    def fwriter(self, res):
        fres = "%s \n \n" % res
        file = open('results2.txt', 'a')
        file.write(fres)
        file.close()
############################################################3  

phrase = raw_input("what would you like to search for?")
webbie = raw_input("where would you like to search from? eg http:\www.(insertwebsitehere).com")
mysearch=linkwalker(webbie, phrase)