Friday 20 January 2012

Clarion sorter with python - dosemu

This is my one of my first i write in python. This program do a sorter for a clarion system, interact with dosemu. Here is the code


sorter_clarion

Download

Saturday 14 January 2012

ssha hash generator

A typical script, that generate ssha hash.
Thanks to the openldap project


#!/usr/bin/env python
import hashlib
import os
from base64 import encodestring as encode
from base64 import decodestring as decode
import getpass

def makeSecret(password):
    salt = os.urandom(4)
    h = hashlib.sha1(password)
    h.update(salt)
    return "{SSHA}" + encode(h.digest() + salt)

def checkPassword(challenge_password, password):
    challenge_bytes = decode(challenge_password[6:])
    digest = challenge_bytes[:20]
    salt = challenge_bytes[20:]
    hr = hashlib.sha1(password)
    hr.update(salt)
    return digest == hr.digest()

if __name__ == "__main__":
   pass1 = getpass.getpass()
   pass2 = getpass.getpass()
   if pass1 == pass2:
      ver = makeSecret(pass1)
      print ver
      bol = checkPassword(ver,pass1)
      print bol
   else:
      print "pass are not equals"

Connect to a zk clock


I'm spent a half week try to connect this clock. I use reverse engineering to create a network script that read network packages and do some black magic, but i don't have good result. When i give up, Found this wonderful page that's show me how to dispatch the dll of the clock (The sdk only works in windows, is here). !!!Bingo :) !!Boom goes the dynamite :).

 I study the sdk a weekend. Now i'm proud of my code.

This are the methods of the sdk in the code.

Connect_Net(ip, port) # connect to devie
ReadAllUser(machineNumber) #read all user data and put into a buffer
SSR_GetAllUserInfo(machineNumber, EnrrollNumber, Name, Password, Privilege, Enable)  #get all the user data from the buffer
ReadGeneralLogData(machineNumber) # read all the attendance data of the clock in put into a buffer
SSR_GetGeneralLogData
EnableDevice(machinenumber, state) # enabled or disabled the clock

For more information read the TFT manual that comes with the sdk

#!/usr/bin/env python 
#coding:utf-8 
# Author:  peter --<pjl@hpc.com.py> 
# Purpose: manage the dll of the zk software, thanks to sy, for the prototype code 
# Created: 06/12/2011 
# Todo 
# 2012/01/06 
# we add a ldap proxy to diferrent the user company 

# -*- coding: utf-8 -*-   
from win32com.client import Dispatch   
import sys   
from datetime import datetime   
import sys, logging 
import qrclock 
from proxy import PrLdap 


######################################################################## 
class ZkDispatch(object): 
    """Manage the windows enviroment for the zk connections to the iclock 2000""" 
    __doc__ = 'Manage the operations on the biometric clock' 
    __userdata = [] 
    __logdata = [] 
    __clock = "" 
    __today = datetime.today().strftime('%Y-%m-%d')     
    __proxyldap = PrLdap.ProxyLdap()         

    #---------------------------------------------------------------------- 
    def __init__(self): 
        """ 
        Instance the database class, and distpatch the windows dll of the zk sdk 
        """ 
        self.dbmanag = qrclock.QuerysClock(host="XXX.XXX.XXX.XXX", user="XXX", passwd="XXXX", db="XXXXX") 
        self.zk = Dispatch("zkemkeeper.ZKEM") 
        logging.basicConfig(format='%(asctime)s %(message)s',filename="c:\\iclock.log",level=logging.DEBUG)                            

    #----------------------------------------------------------------------         
    def Connect(self, ip, port, mn): 
        """ 
        first connections to the clock, and retrieve the initialize data 
        Connect_Net(ip, port) 
        """ 
        self.__clock = ip 
        logging.info("conectando al reloj %s" % ip) 

        #devPort = 4370   
        #devIPAddr = ’192.168.30.198′   

        flag = self.zk.Connect_Net(ip,port)   
        if flag:   
            logging.info("Conexion exitosa al reloj") 

        else: 
            logging.info("Error de conexion, verifique el dispositivo")             

        if self.zk.ReadAllUserID(mn): 
            #print self.zk.GetAllUserInfo(mn, 0, "", "", 0, False) 

            while True:   
                #s= self.zk.GetAllUserInfo(mn, 0, "", "", 0, False) 
                s= self.zk.SSR_GetAllUserInfo(mn, 0, "", "", 0, False)                 
                #s= self.zk.GetAllUserID(mn, 0, None, 0, False)                 
                if s[0]:   
                    #print type(s[3]) 
                    #print s 
                    self.__userdata.append((s[1], s[2])) 

                else:   
                    break               

    #---------------------------------------------------------------------- 
    def QueryAttendanceDb(self, dateb=__today, datee=__today, mn=1):                 
        """ 
        Read all the log data by the given date, . 
        we use here the SSR_GetGeneralLogData function of the sdk that use the following parameters 
        machinenumber, enrollnumber, verifymode, outmode, year, month, day, hour, minute, second 
        """ 
        tmpstore = [] 
        if self.zk.ReadGeneralLogData(mn): 
            while True:
        #i don't why, but no matters if you give a specific date, the method get all the records from the beginning 
                att = self.zk.SSR_GetGeneralLogData(mn, "", 0, 0,2011, 12, 4, 0, 0, 0, 0) 
                #att = self.zk.SSR_GetGeneralLogData(mn, "", None, None, 2011, 5, 13, None, None, None, None) 
                if att[0]: 
                    tmpstore.append(att) 
                    #print att 
                else: 
                    break 

        for v in tmpstore: 
            for u in self.__userdata: 
                if v[1] == u[0]: 
                    dtlog = datetime(v[4], v[5], v[6], v[7], v[8], v[9]) 
                    dlog = dtlog.strftime("%Y-%m-%d") 
                    tlog = dtlog.strftime("%H:%M:%S") 
                    ta = self.ChangeAuthType(v[2])             
                    tc = self.ChangeCheckType(v[3]) 
                    user = u[1].replace(","," ") 
                    self.__logdata.append((v[1], user, ta, tc, dlog, tlog)) 

        for rl in self.__logdata: 
            dcheck = (rl[0], rl[4], rl[5], rl[3]) 
            if self.dbmanag.CheckFirstTime(dcheck): 
                #proxy ldap 
                r = self.__proxyldap.FormatUserCompany(rl[0]) 
               
                if r: 
                    empresa = r[0][1]["Empresa"][0] 
                else: 
                    empresa = "NULL" 
                try: 
                    dcinser = (rl[0], rl[1].split()[-1].strip(), rl[1].split()[0].strip(), rl[4], rl[5], self.__clock, rl[2], rl[3], empresa)             
                    self.dbmanag.InsertData(dcinser) 
                except: 
                    logging.info("Error al insertar el dato %s" % rl[0]) 

    #---------------------------------------------------------------------- 
    def ClearLog(self, mn=1): 
        """Clear all the log attendance of the lock""" 
        logging.info("Borrando logs de registros") 
        self.zk.ClearGLog(mn) 
        logging.info("Borrando logs de registros Exito")    

    #---------------------------------------------------------------------- 
    def Enabled(self, mn=1, state=1): 
        """Enalbed or disable the device""" 
        if state == 0: 
            logging.info("Desactivando dispositivo")    
        else: 
            logging.info("Activando dispositivo")                     
        self.zk.EnableDevice(mn, state) 


    #---------------------------------------------------------------------- 
    def ChangeCheckType(self, ctyp): 
        """change the check type for a human data""" 

        if ctyp == 0: 
            return "Entrada" 

        if ctyp == 1: 
            return "Salida" 

        if ctyp == 2: 
            return "Salida Intermedia" 

        if ctyp == 3: 
            return "Entrada Intermedia"    

        if ctyp == 4: 
            return "Entrada Almuerzo"        

        if ctyp == 5: 
            return "Salida Almuerzo"            

    #---------------------------------------------------------------------- 
    def ChangeAuthType(self, atyp): 
        """change the auth type for a human data""" 

        if atyp == 0: 
            return "Clave" 

        if atyp == 1: 
            return "Huella"    

        if atyp == 2: 
            return "Tarjeta"        

        if atyp == 3: 
            return "Clave"            

        if atyp == 4: 
            return "Clave"                

        if atyp == 5: 
            return "Clave"                    

        if atyp == 6: 
            return "Clave"    
     
    #---------------------------------------------------------------------- 
    def CalculeTime(self, times): 
        """ 
        calculate how long take the transactions 
        """ 
        ini = times[0] 
        end = times[1] 
        horai, minutoi, segundoi = ini.split(":") 
        horai = int(horai) 
        minutoi = int(minutoi) 
        segundoi = int(segundoi) 
         
        valor0 = (horai*60)+(minutoi*60)+segundoi 
        horae, minutoe, segundoe = end.split(":") 
        horae = int(horae) 
        minutoe = int(minutoe) 
        segundoe = int(segundoe) 
        valor1 = (horae*60)+(minutoe*60)+segundoe 
        dur = valor1 - valor0 
         
        logging.info("Duracion de la conexion %s segundos" % str(dur)) 
         

if __name__ == '__main__':   
    clock = ZkDispatch() 
    ini = datetime.today() 
    ini = ini.strftime("%H:%M:%S")     
    clock.Connect('192.168.0.50', 4370, 1) 
    clock.Enabled(1, 0) 
    clock.QueryAttendanceDb() 
    clock.ClearLog(mn=1) 
    clock.Enabled(1, 1)     
    end = datetime.today() 
    end = end.strftime("%H:%M:%S") 
    clock.CalculeTime((ini, end)) 
 
 
 

Convert a xls file to a ldif file

I create this script to convert this xls file:


Friday 13 January 2012

Embed python with rsync

This is a nice way to control the backup in our company. I just Embed python with rsync 
This is a basci scheme.
'a' copy to 'b', files in production are copy to 'a' and 'b' copy to 'c' 
--------------------------
A—->  B —> C
-------------------------

 
#!/usr/bin/env python
#better backup, made in python
#Autor: peter pjl@hpc.com.py
from subprocess import call
import sys
import time
import datetime

def bkp()
    for bkp in [0, 1, 2]:
 if bkp == 0:
 #B to C
    sync("/mnt/company/","192.168.1.16:/mnt/companybckall","company")
    sync("/mnt/company1/","192.168.1.16:/mnt/company1bckall","company1")
    sync("/mnt/company2/","192.168.1.16:/mnt/company2bckall","company2")
    sync("/mnt/company3/","192.168.1.16:/mnt/company3bckall","company3")
     elif bkp == 1:
     #files in production to A
    sync("/media/company/","/mnt/companybckall","company")
    sync("192.168.12.2:/media/users/company/","/mnt/companybckall","company1")
    sync("192.168.13.2:/media/users/company/","/mnt/companybckall","company2")
    sync("192.168.10.8:/media/company/","/mnt/companybckall","company3")
     elif bkp == 2:
     #A to B
    sync("/mnt/comanybckall/","192.168.10.8:/mnt/companybckall","company")
    sync("/mnt/company1bckall/","192.168.10.8:/mnt/company1bckall","company1")
    sync("/mnt/company2bckall/","192.168.10.8:/mnt/company2bckall","company2")
    sync("/mnt/company3bckall/","192.168.10.8:/mnt/company3bckall","company3")

def sync(sources, destins, logs):
    fecha = datetime.date.today()
    fechastr = fecha.strftime("%Y-%m-%d")
    lognom = destins + "/" + fechastr + "-" + logs + ".log"
    logerror = destins + "/" + fechastr + "-" + logs + "err" + ".log"
    rsync = "rsync"
    # the arguments of the ssh must be in this way to work with crontab :)
    argum = "-agEvvz --exclude-from=/root/excluir -e \"ssh -i /home/peter/.ssh/id_rsa\""
    cmd = "%s %s %s %s" % (rsync, argum, sources, destins)
    while True:
 ret = call(cmd, shell=True, stdout=open(lognom, "a+"), stderr=open(logerror, "a+"))
 if ret != 0:
    time.sleep(30)
 else:
    sys.exit(0)

if __name__ == "__main__":
   bkp()
 
 
 
this is just a basic use 

Sunday 8 January 2012

Compile python in linux
Download freeze: http://www.codepanel.net/showthread.php?tid=700
Visit my python blog: http://pycenter.blogspot.com/

usage:
python freeze.py -o output-folder/ helloworld.py
cd output-folder
make

Saturday 7 January 2012

Solve any Captcha

This method is: 95.9% accurate(last time I checked). This program uses the site captchatrader.com and you'll need an account there.

import urllib, urllib2, sys

if len(sys.argv )<2:
    sys.exit("the first argument should be the captcha file")
url = "http://api.captchatrader.com/submit"
api_key = "API_KEY"
passwd = "PASSWORD"
user = "USERNAME"
img = base64.b64encode(open(sys.argv[1]).read())

values = {'api_key' : api_key,'password' : passwd,'username' : user, 'value':img}
data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
the_page = response.read().split(",")
the_page = the_page.replace("\"", "")
the_page = the_page.replace("]", "")
print the_page[1]
Just change the variables the top to your credentials then run it using these arguments:
python captcha.py '/image/location/image.jpg'
My Def for clicking and controlling the mouse in windows mac and linux

If you are in windows you'll need to install pywin32 and if you are in linux or OSX then you'll need to install xdotool

def click(x, y):
    if os.name == "posix":
        os.system("xdotool mousemove " + str(x) + " " + str(y))
        os.system("xdotool click 1")
    else:
        win32api.SetCursorPos((x,y))
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)

in the code it's basically saying if the operating system is posix (linux/mac) then run the nesseary terminal commands the move the mouse to x,y then click it. but if the operating system is not Linux or windows then use win32api (part of pywin32) to move the mouse then click it.

in windows you must:
import win32api, win32con
in Linux/Mac you must:
import os

Friday 6 January 2012

Generate real random urls in python
This will create a random ip address using random.randint(0, 255) like this:

        ip0 = str(random.randint(0, 255))
        ip1 = str(random.randint(0, 255))
        ip2 = str(random.randint(0, 255))
        ip3 = str(random.randint(0, 255))
        url = ip0 + '.' + ip1 + '.'+ ip2 + '.'+ ip3
It will then try to get the hosts address by using socket.gethostbyaddr(url) and if it's good/real it will print the address and write it to the file links.txt


import random, urllib2, os, socket, time
from threading import Thread, active_count

f=open("links.txt", 'w')
global p
global done
global alinks
alinks = []
maxurls = 100
p=0
def main():
    global alinks
    global done
    global p
    while p != maxurls:
        ip0 = str(random.randint(0, 255))
        ip1 = str(random.randint(0, 255))
        ip2 = str(random.randint(0, 255))
        ip3 = str(random.randint(0, 255))
        url = ip0 + '.' + ip1 + '.'+ ip2 + '.'+ ip3
        try:
            link = socket.gethostbyaddr(url)
            print link[0]
            f.write(link[0])
            f.write("\n")
            p=p+1
            try:
                urlContent = urllib2.urlopen(url).read()
                if urlContent.find('<html') > -1 or urlContent.find('<HTML') > -1:
                    break
            except:
                pass
        except:
            pass
    done = done - 1
   

maxi = 55
done = maxi
hhh = 0
while hhh != maxi:
    hhh=hhh+1
    Thread(target=main, args=()).start()

while done != 0 or done > 0:
        time.sleep(1.2)

print "Writing to File"
alinks.tofile(f)
print "Done exiting"

Download - mediafire.com
Download - codepanel.net

Wednesday 4 January 2012

Bruteforce dictionary creator.

Need a dictionary file but don't want to download 36GB? Just use the script to create of for your self.

Download

it takes no arguments, it will ask you for the specs in program.
How to compile python in linux

In this tutorial we'll be using freeze ,  just use your python script as the first argument see:
python freeze.py yourfile.py

Tuesday 3 January 2012

Convert Images to text and text back to images

When we convert images to/from text we use base64 and import python you can use base64 by 
import base64
 So this script will open the image from the first argument and save to readable text version as output.txt


import sys, base64

img = open(sys.argv[1], 'r')
txt = img.read()
txt2 = base64.b64encode(txt)
txtfile = open("output.txt", 'w')
txtfile.write(txt2)
#print txt2

If you uncomment the last line by removing the '#' it will print out the text value of the image.

And this 

import sys, base64

img = open(sys.argv[1], 'r')
txt = img.read()
txt2 = base64.b64decode(txt)
txtfile = open("output.png", 'w')
txtfile.write(txt2)
Will open the text file as the first argument and output the image to 'output.png'

Download

Monday 2 January 2012

Controlling the CD/DVD drive in python

This program requires pygame to be installed

import pygame.cdrom as cdrom
cdrom.init()
cd = cdrom.CD(0) # 0 = first cdrom device
cd.init()
cd.eject()
cd.quit()
cdrom.quit()

 Hide my ass proxy grabber

This program will grabber all the proxies from this page http://hidemyass.com/proxy-list/
And will print out each http or https and and will write them to a file if you specify -o in the arguments but it will keep the proxies that are already in the file and will not write the same on twice.
Download