Saturday, 16 November 2013

How to send xml data to server using webservices in python

We can send xml data to server using web-services using Suds module. In last post we have used suds module for web-services either login or sending report.
Please see my post "How to use web-services in pygtk for desktop application"

Here first you have to install suds module and write below code for sending xml data to services through webservices.

            url = 'http://example.com/src/example.asmx?wsdl'
            uid='example@gmail.com'
            psw='hello@123'
            client = Client(url)
            xml = xdata.parse('../src/example.xml') # or xml.dom.minidom.parseString(xml_string)
            senddata= xml.toprettyxml()
            #print senddata
            data = client.service.Dologin(uid,psw)
            print 'token="%s"' % data
            data1 = client.service.SaveScanData({'senddata':senddata})
Enjoy Guys

How to setup active directory LDAP in Python

For setup active directory we need LDAP connection . Using ldap connection we can connect active directory and we can find all users and computers which is connected through it.


The Lightweight Directory Access Protocol (LDAP) is an application protocol for accessing and maintaining distributed directory information services over an Internet Protocol (IP) network.
Directory services may provide any organized set of records, often with a hierarchical structure, such as a corporate email directory. Similarly, a telephone directory is a list of subscribers with an address and a phone number.

Active directory is nothing but a server where many system can connect and we can create number of users. So in 1 system number of users can work with active directory.

Here we will connect Active directory through ldap connection.


try:
    l = ldap.initialize("ldap://example.com")
    l.protocol_version = ldap.VERSION3
    l.set_option(ldap.OPT_REFERRALS, 0)
    bind = l.simple_bind_s("administrator@example.com", "example@123")
    print "Connected is establised!"
except:
    print "Connected failed!"

Above code  is for connection establishment
Now how to find user's list
try:
    l = ldap.initialize("ldap://example.com")
    l.protocol_version = ldap.VERSION3
    l.set_option(ldap.OPT_REFERRALS, 0)
    bind = l.simple_bind_s("administrator@example.com", "example@123")
    print "Connected is establised!"
    base = "dc=example, dc=com"
    criteria = "(&(objectClass=user)(cn=*))"
    #attributes = ['cn','dNSHostName','sAMAccountName','name']
    attributes = ['name']
    result = l.search_s(base, ldap.SCOPE_SUBTREE, criteria,  attributes)
    results = [entry for dn, entry in result if isinstance(entry, dict)]
    print results
except:
    print "Connected failed!"
 
  
How to find computers list
try:
    l = ldap.initialize("ldap://example.com")
    l.protocol_version = ldap.VERSION3
    l.set_option(ldap.OPT_REFERRALS, 0)
    bind = l.simple_bind_s("administrator@example.com", "example@123")
    print "Connected is establised!"
    base = "dc=example, dc=com"
    criteria = "(&(objectClass=computer)(cn=*))"
    #attributes = ['cn','dNSHostName','sAMAccountName','name']
    attributes = ['name']
    result = l.search_s(base, ldap.SCOPE_SUBTREE, criteria,  attributes)
    results = [entry for dn, entry in result if isinstance(entry, dict)]
    print results
except:
    print "Connected failed!"
 
 
Before run this code you have to download ldap module Download LDAP

Saturday, 2 November 2013

how to use thread in Pygtk (python)

or
how to use multiple threads in Pygtk (python)
You are probably familiar with multi-processing (also known as multi-programming or multi-tasking): a single computer running several programs (seemingly) simultaneously. This is done by clever and frequent switching between the execution state of each program. For example, the print spooler on your PC may be printing pages from one document while you are editing another document in your word processor. 
Multi-threading is a finer-grained version of the same idea: multiple things going on simultaneously within the same program. For example, most web browsers allow you to continue to browse while a file download is in progress.
Each "thing" going on independently in this case is called a Thread, short for thread of control.

Another reason for using threads is that the creation of a new thread is much faster than the creation of a new process. This means that when you have a relatively small amount of work that you would like to handle separately,
import threading
import time
import gobject
import gtk

gobject.threads_init()

from socket import *
network = '192.168.1.'

def is_up(addr):
    s = socket(AF_INET, SOCK_STREAM)
    s.settimeout(0.01)    ## set a timeout of 0.01 sec
    if not s.connect_ex((addr,135)):    # connect to the remote host on port 135
        s.close()                       ## (port 135 is always open on Windows machines, AFAIK)
        return 1
    else:
        s.close()

class MyThread(threading.Thread):
    def __init__(self, label):
        super(MyThread, self).__init__()
        self.label = label
        self.quit = False

    def run(self):
        for i in xrange(1,256):
            addr = network + str(i)
            if is_up(addr):
                msg = '%s' %(getfqdn(addr))
                iter = model.append()
                model.set(iter, 0, msg)

w = gtk.Window()
w.set_position(gtk.WIN_POS_CENTER)
w.set_default_size(260, 300)
scrolled_window = gtk.ScrolledWindow()         
scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
scrolled_window.set_size_request(100,300)
model = gtk.ListStore(gobject.TYPE_STRING)
tree_view = gtk.TreeView(model)
scrolled_window.add_with_viewport (tree_view)
tree_view.show()
cell = gtk.CellRendererToggle()
cell.set_radio(False)
column1 = gtk.TreeViewColumn("Select", cell)
tree_view.append_column(column1)
cell = gtk.CellRendererText()
cell.set_property( 'editable', True )
column = gtk.TreeViewColumn("Computer Name\IP", cell, text=0)
tree_view.append_column(column)

w.add(scrolled_window)
w.show_all()
w.connect("destroy", lambda _: gtk.main_quit())

#This is thread
t = MyThread(model)
t.start()

gtk.main()
t.quit = True

Python supports some very simple optional operations for threading. Suppport for these operations must be requested when Python is built for a particular installation; it is available for most platforms except for Macintosh. In particular, threading is supported for Windows NT and 95, for Unix systems with a POSIX thread implementation (this includes Linux), and for native threads on Sun Solaris and SGI IRIX.

Thanks

Find valid credit card number by mod-10 algorithm in python



Mod-10 algorithm is for find true credit card number  just like as maestro card, master card and American, visa card etc..

Mod-10 algorithm is given below in python. Easily you can use mod-10 algorithm in your script.
Import os
def cardLuhnChecksumIsValid(card_number):
    """ checks to make sure that the card passes a luhn mod-10 checksum """
    sum = 0
    num_digits = len(card_number)
    oddeven = num_digits & 1

    for count in range(0, num_digits):
        digit = int(card_number[count])
        if not (( count & 1 ) ^ oddeven ):
            digit = digit * 2
        if digit > 9:
            digit = digit - 9

        sum = sum + digit
    return ( (sum % 10) == 0 )
x = cardLuhnChecksumIsValid('5400974053274081')
if x:
 print “this card is valid!”
else:
 print “this card is invalid!”
 
Find valid CAS number 

def checkCAS(cas):
    '''Check if a string is a valid CAS number.

    Arguments:
    cas -- string to check
    '''
    nums = cas[::-1].replace('-', '') # all digits in reverse order
    checksum = int(nums[0]) # first digit is the checksum
    som = 0
    # Checksum method from: http://nl.wikipedia.org/wiki/CAS-nummer
    for n, d in enumerate(nums[1:]):
        som += (n+1)*int(d)
    return som % 10 == checksum

x= checkCAS(‘number’)
if x:
 print “this card is valid!”
else:
 print “this card is invalid!”

How to create windows installer msi file in python



We can create window installer msi file from different ways but I prefer cx_freeze library

In previous post “how to create exefile by py2exe”, we have made exe file with library.

Now we will create window installer msi file, msi file is a installer file for window. It will install this application in your system and create desktop shortcut. So when you will double click on icon it will open your sample.exe window

For window installer file you need some file in 1 folder

  • keep exe file only in one folder
  • create setup.py for msi file which is given below
  • keep all image, files which is required for exe
  • install cx_freeze library
Cx_freeze Windows installers (MSI):


setup.py
from cx_Freeze import *

includefiles=["win32api.pyd","smaple.exe,"favicon.ico","pythoncom27.dll","pywintypes27.dll”,"images/cream_dust.png "]
excludes=[]
packages=[]
base = None
if sys.platform == "win32":
    base = "Win32GUI"
    
shortcut_table = [
    ("DesktopShortcut",        # Shortcut
     "DesktopFolder",          # Directory_
     "Tool",           # Name
     "TARGETDIR",              # Component_
     "[TARGETDIR]\sample.exe",# Target
     None,                     # Arguments
     None,                     # Description
     None,                     # Hotkey
     None,                     # Icon
     None,                     # IconIndex
     None,                     # ShowCmd
     "TARGETDIR",               # WkDir
     )
    ]

# Now create the table dictionary
msi_data = {"Shortcut": shortcut_table}

# Change some default MSI options and specify the use of the above defined tables
bdist_msi_options = {'data': msi_data}
setup(
     version = "0.1",
     description = "Demo Tool",
     author = "Ashish",
     name = "Demo Tool",
     options = {'build_exe': {'include_files':includefiles}, "bdist_msi": bdist_msi_options,},
     executables = [
        Executable(
            script="sample.py",
            base=base,
            icon='favicon.ico',
            )
        ]
     )



Shortcut table is for desktop shortcut icon and startup menu.

After creating setup.py then open cmd prompt and go to your directory.  Now type

        Python setup.py py2exe

Then enter, it will create msi file in dist folder , now you can install this msi file in your system and click on desktop icon it will open your app sample window.
 
Thanks guys

How to create exe file by py2exe



We can create exe file of any python script by number of ways. But I will prefer only py2exe for it.
Here are some common ones:
py2exe is better for make windows exe . so first download py2exe from below link

DOWNLOAD  py2exe -----Python2.7 for window 32 bit

DOWNLOAD py2exe------Python 2.7 for window 64 bit
Now  install py2exe in your system and create setup.py for creating exe file.

Sample.py
#!/usr/bin/env python

# base.py
import pygtk
pygtk.require('2.0')
import gtk

class Base:
    def __init__(self):
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.set_icon_from_file('images/logo.png')
        self.window.set_title("Sample window")
        self.window.set_position(gtk.WIN_POS_CENTER)
        self.window.set_size_request(500, 275)
        self.window.set_resizable(False)
        frame=gtk.Frame("Hi guys how are you?")
        self.window.add(frame)
        frame.set_uposition(2,40)
        frame.show()
        self.window.show()

    def main(self):
        gtk.main()

if __name__ == "__main__":
    base = Base()
    base.main()
Setup.py
from distutils.core import setup
import py2exe

dfiles = [('images', ["images/cream_dust.png "])]

excludes = ["pywin", "pywin.debugger"] # there will be more in real life...
option = dict(optimize=2,
           dist_dir="Demo Project",
           excludes=excludes,
           packages=["win32api"])

setup(
    windows=[{'script':'sample.py' }],
    console=[{'script':'sample.py' }],
    data_files=dfiles,
    zipfile=None,
    options={'py2exe':{'bundle_files':1,'compressed':1,"dll_excludes":[ "mswsock.dll", "powrprof.dll" ]}, 'py2exe':option},
)
      

After creating sample.py (for this file we will create exe) and setup.py (this is for exe file creation with distutils library).


dfiles—if any file you want to use in project like as image then u have to mention in dfiles.

Now open command prompt and go through your directory where you have kept files (sample.py , setup.py).


D:\project> Python setup.py install

D:\project> Python setup.py py2exe


It will create one folder name Demo project, this is exe folder where all dependency library files stored. Click on sample.exe then you will see window which you have made in sample.py

Thanks Guys