Sunday 22 December 2013

Get installed software and running process information in local and remote system

Here we can get all the information about local system and remote system through the module. From this module you can connect by remote computer and by below code you can get all information about it.

you have heard about this module in previous post. this module is nothing but WMI module.
you can download from here 

Subversion: http://svn.timgolden.me.uk/wmi/trunk/ 
Windows installer and zip: http://pypi.python.org/pypi/WMI/#downloads 
Older Versions: http://timgolden.me.uk/python/downloads

List all running processes in the current system.

import wmi
c = wmi.WMI ()

for process in c.Win32_Process ():
  print process.ProcessId, process.Name

you can see all running process in remote system also like as below,
List all running processes in the Remote system.

import wmi
c= wmi.WMI(ip, user=username, password=password)

for process in c.Win32_Process ():
  print process.ProcessId, process.Name

Show the percentage free space for each fixed disk in your system,

import wmi
c = wmi.WMI ()

for disk in c.Win32_LogicalDisk (DriveType=3):
  print disk.Caption, "%0.2f%% free" % (100.0 * long (disk.FreeSpace) / long (disk.Size))

Reboot a remote machine,

import wmi
# other_machine = "machine name of your choice"
c = wmi.WMI (computer=other_machine, privileges=["RemoteShutdown"])

os = c.Win32_OperatingSystem (Primary=1)[0]
os.Reboot ()

Shutdown a remote machine,


import wmi
# other_machine = "machine name of your choice"
c = wmi.WMI (computer=other_machine, privileges=["RemoteShutdown"])

os = c.Win32_OperatingSystem (Primary=1)[0]
os.shutdown ()

Show the IP and MAC addresses for IP-enabled network interfaces

import wmi
c = wmi.WMI ()

for interface in c.Win32_NetworkAdapterConfiguration (IPEnabled=1):
  print interface.Description, interface.MACAddress
  for ip_address in interface.IPAddress:
    print ip_address

What’s running on startup and from where in your system,?

import wmi
c = wmi.WMI ()

for s in c.Win32_StartupCommand ():
  print "[%s] %s <%s>" % (s.Location, s.Caption, s.Command)

Watch for errors in the event log in your system,
import wmi
c = wmi.WMI (privileges=["Security"])

watcher = c.watch_for (
  notification_type="Creation",
  wmi_class="Win32_NTLogEvent",
  Type="error"
)
while 1:
  error = watcher ()
  print "Error in %s log: %s" %  (error.Logfile, error.Message)
  # send mail to sysadmin etc.

List registry keys in your system,

import _winreg
import wmi

r = wmi.Registry ()
result, names = r.EnumKey (
  hDefKey=_winreg.HKEY_LOCAL_MACHINE,
  sSubKeyName="Software"
)
for key in names:
  print key

Add a new registry key in system,

import _winreg
import wmi

r = wmi.Registry ()
result, = r.CreateKey (
  hDefKey=_winreg.HKEY_LOCAL_MACHINE,
  sSubKeyName=r"Software\TJG"
)

Add a new registry value in system,

import _winreg
import wmi

r = wmi.Registry ()
result, = r.SetStringValue (
  hDefKey=_winreg.HKEY_LOCAL_MACHINE,
  sSubKeyName=r"Software\TJG",
  sValueName="ApplicationName",
  sValue="TJG App"
)

Show shared drives in system,

import wmi
c = wmi.WMI ()

for share in c.Win32_Share ():
  print share.Name, share.Path

Show disk partitions in local system,
import wmi
c = wmi.WMI ()

for physical_disk in c.Win32_DiskDrive ():
  for partition in physical_disk.associators ("Win32_DiskDriveToDiskPartition"):
    for logical_disk in partition.associators ("Win32_LogicalDiskToPartition"):
      print physical_disk.Caption, partition.Caption, logical_disk.Caption

Install a product in local system,

import wmi
c = wmi.WMI ()

c.Win32_Product.Install (
  PackageLocation="c:/temp/python-2.4.2.msi",
  AllUsers=False
)
Find Drive Types in your system,

import wmi

DRIVE_TYPES = {
  0 : "Unknown",
  1 : "No Root Directory",
  2 : "Removable Disk",
  3 : "Local Disk",
  4 : "Network Drive",
  5 : "Compact Disc",
  6 : "RAM Disk"
}

c = wmi.WMI ()
for drive in c.Win32_LogicalDisk ():
  print drive.Caption, DRIVE_TYPES[drive.DriveType]

   
 Thanks Guys

Friday 20 December 2013

Listing all installed applications on Windows with python

The following code is a small script that contains the functions to query the installed software in the system which is very similar to the script found in WiLstPrd.vbs but using python instead of VB and ctypes.

this python script will show list of installed application on windows os.

# This scripts allows to get a list of all installed products in a windows
# machine. The code uses ctypes becuase there were a number of issues when
# trying to achieve the same win win32com.client
from collections import namedtuple
from ctypes import byref, create_unicode_buffer, windll
from ctypes.wintypes import DWORD
from itertools import count
 
# defined at http://msdn.microsoft.com/en-us/library/aa370101(v=VS.85).aspx
UID_BUFFER_SIZE = 39
PROPERTY_BUFFER_SIZE = 256 
ERROR_MORE_DATA = 234
ERROR_INVALID_PARAMETER = 87
ERROR_SUCCESS = 0
ERROR_NO_MORE_ITEMS = 259 
ERROR_UNKNOWN_PRODUCT = 1605 
 
# diff propoerties of a product, not all products have all properties
PRODUCT_PROPERTIES = [u'Language',
                      u'ProductName',
                      u'PackageCode',
                      u'Transforms',
                      u'AssignmentType',
                      u'PackageName',
                      u'InstalledProductName',
                      u'VersionString',
                      u'RegCompany',
                      u'RegOwner',
                      u'ProductID',
                      u'ProductIcon',
                      u'InstallLocation',
                      u'InstallSource',
                      u'InstallDate',
                      u'Publisher',
                      u'LocalPackage',
                      u'HelpLink',
                      u'HelpTelephone',
                      u'URLInfoAbout',
                      u'URLUpdateInfo',] 
 
# class to be used for python users :)
Product = namedtuple('Product', PRODUCT_PROPERTIES)
 
 
def get_property_for_product(product, property, buf_size=PROPERTY_BUFFER_SIZE):
    """Retruns the value of a fiven property from a product."""
    property_buffer = create_unicode_buffer(buf_size)
    size = DWORD(buf_size)
    result = windll.msi.MsiGetProductInfoW(product, property, property_buffer,
                                           byref(size))
    if result == ERROR_MORE_DATA:
        return get_property_for_product(product, property,
                2 * buf_size)
    elif result == ERROR_SUCCESS:
        return property_buffer.value
    else:
        return None
 
 
def populate_product(uid):
    """Return a Product with the different present data."""
    properties = []
    for property in PRODUCT_PROPERTIES:
        properties.append(get_property_for_product(uid, property))
    return Product(*properties) 
 
 
def get_installed_products_uids():
    """Returns a list with all the different uid of the installed apps."""
    # enum will return an error code according to the result of the app
    products = []
    for i in count(0):
        uid_buffer = create_unicode_buffer(UID_BUFFER_SIZE)
        result = windll.msi.MsiEnumProductsW(i, uid_buffer)
        if result == ERROR_NO_MORE_ITEMS:
            # done interating over the collection
            break
        products.append(uid_buffer.value)
    return products
 
 
def get_installed_products():
    """Returns a collection of products that are installed in the system."""
    products = []
    for puid in  get_installed_products_uids():
        products.append(populate_product(puid))
    return products 
 
 
def is_product_installed_uid(uid):
    """Return if a product with the given id is installed.
 
    uid Most be a unicode object with the uid of the product using
    the following format {uid}
    """
    # we try to get the VersisonString for the uid, if we get an error it means
    # that the product is not installed in the system.
    buf_size = 256
    uid_buffer = create_unicode_buffer(uid)
    property = u'VersionString'
    property_buffer = create_unicode_buffer(buf_size)
    size = DWORD(buf_size)
    result = windll.msi.MsiGetProductInfoW(uid_buffer, property, property_buffer,
                                           byref(size))
    if result == ERROR_UNKNOWN_PRODUCT:
        return False
    else:
        return True

apps=get_installed_products()
for app in apps:
    print app.InstalledProductName

The above code will allow a python developer to check which products are installed on Windows as well as to know if a product with the given UID is indeed installed.

Thanks

Thursday 19 December 2013

Connect to MySQL database and retrieve data in python

I have implemented this program which will connect to Mysql and retrieve all the database, tables and containing data. we can read all column row data from this program.

for retrieving the MYSQL server data 1st we have to install one library which is mysqldb  library. Download this library from here Download.

Through this library, it will connect to Mysql server by hostname, username, password and fetch all data like database, tables and tables data.


import re
import MySQLdb

db = MySQLdb.connect("localhost","root","root@123")
cur = db.cursor() 
cur.execute("show databases")
for ro in cur.fetchall() :
    cur.execute("use "+ro[0])
    cur.execute("show tables")
    for rem in cur.fetchall() :
        cur.execute("select * from "+rem[0])
        for row in cur.fetchall():
            for x in range(0,len(row)):
                data=str(row[x])

db.close()

This username & password are MySQL credentials
If you want to connect remote MySQL then you have to use below code for it. it will connect through ip address.
import re
import MySQLdb

db = MySQLdb.connect("\\\\192.168.1.18","root","root@123")
cur = db.cursor() 
cur.execute("show databases")
for ro in cur.fetchall() :
    cur.execute("use "+ro[0])
    cur.execute("show tables")
    for rem in cur.fetchall() :
        cur.execute("select * from "+rem[0])
        for row in cur.fetchall():
            for x in range(0,len(row)):
                data=str(row[x])

db.close()
try it, Thanks guys.

Connect to SQL server and retrieve data in python

I have implemented this program which will connect to sql server and retrieve all the database, tables and containing data. we can read all column row data from this program.

for retrieving the SQL server data 1st we have to install one library which is mssql library. Download this library from here Download.

Through this library, it will connect to sql server by SERVER name, username, password and fetch all data like database, tables and tables data.

#!/usr/bin/python
import re
import pymssql
conn = pymssql.connect(host='Ashish', user='Ashish\ashishsql', password='ashish@123')
cur = conn.cursor()
cur.execute("Select * from Sys.databases")
row = cur.fetchall()
print "Database----------Tables------------Data"
for ro in row:
    cur.execute("USE "+ro[0]+" SELECT name FROM sys.tables")
    rew = cur.fetchall()
    for rem in rew:
        if ro[0]!='tempdb':
            cur.execute("USE "+ro[0]+" SELECT * FROM "+rem[0])
            rows = cur.fetchall()
            for row in rows:
                for x in range(0,len(row)):
                    data=str(row[x])
                    print data
conn.close()

This username & password are SQL server credentials
If you want to connect remote SQL server then you have to use below code for it. it will connect through ip.

#!/usr/bin/python
import re
import pymssql
conn = pymssql.connect(server='\\\\192.168.1.18\\SQL Server', host='Ashish', user='Ashish\ashishsql', 

password='ashish@123')
cur = conn.cursor()
cur.execute("Select * from Sys.databases")
row = cur.fetchall()
print "Database----------Tables------------Data"
for ro in row:
    cur.execute("USE "+ro[0]+" SELECT name FROM sys.tables")
    rew = cur.fetchall()
    for rem in rew:
        if ro[0]!='tempdb':
            cur.execute("USE "+ro[0]+" SELECT * FROM "+rem[0])
            rows = cur.fetchall()
            for row in rows:
                for x in range(0,len(row)):
                    data=str(row[x])
                    print data

conn.close()



Thanks guys

Tuesday 17 December 2013

How to generate PDF file in python

In python you can generate PDF with ReportLab module which provide number of library for designing pdf file. For creating PDF in python you have to download ReportLab module
from here

Download Module ReportLab 
For more information about ReportLab library click on this link 
Code For creating only PDF file

#!/usr/bin/env python
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch
from reportlab.lib.colors import magenta, red
from reportlab.platypus import SimpleDocTemplate
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.units import inch
from reportlab.lib.pagesizes import A4
from reportlab.platypus import Paragraph
from reportlab.lib.utils import simpleSplit
from reportlab.pdfbase.pdfmetrics import stringWidth
from reportlab.lib.enums import TA_CENTER
import subprocess
import os
import gtk

   def shrink_font_size(aW, aH, text, style):
        """Wrap pdf text and Shrinks font size by using pdfmetrics to calculate the height
        of a paragraph, given the font name, size, and available width."""

        def break_lines(text, aW):
            # simpleSplit calculates how reportlab will break up the lines for
            # display in a paragraph, by using width/fontsize.
            return simpleSplit(text, style.fontName, style.fontSize, aW)
    
        def line_wrap(lines, style):
            # Get overall width of text by getting stringWidth of longest line
            width = stringWidth(max(lines), style.fontName, style.fontSize)
            # Paragraph height can be calculated via line spacing and number of lines.
            height = style.leading * len(lines)
            return width, height
    
        lines = break_lines(text, aW)
        width, height = line_wrap(lines, style)
    
        while height > aH or width > aW:
            style.fontSize -= 1
            lines = break_lines(text, aW)
            width, height = line_wrap(lines, style)
            
   def genpdf():
          doc = SimpleDocTemplate(os.path.join(os.path.expanduser('~'), 'Desktop')+"\hello.pdf")
          parts = []
          txt = 'We would like to welcome you to our subscriber base for Magazine! \
          You will receive issues at the excellent introductory price. Please respond by\
          to start receiving your subscription and get the following free gift.'
          PAGE_WIDTH, PAGE_HEIGHT = A4
          aW = PAGE_WIDTH - 1*inch  
          aH = PAGE_HEIGHT - 1*inch
          style = ParagraphStyle(name='Times New Roman')
          style.fontSize = 12
          style.leading = 20
          shrink_font_size(aW, aH, txt, style)
          p = Paragraph(txt, style)
          style1 = ParagraphStyle(name='Times New Roman')
          style1.fontSize = 16
          style1.leading = 20
          style1.textColor = 'red'
          style1.alignment = TA_CENTER
          q=Paragraph("Report", style1)
          parts.append(q)
          parts.append(p)
          doc.build(parts)
genpdf()

for Demo pupose i have created dialog box, it will ask to choose format of document and save as you wish like PDF, DOC, XLSX, TXT, CSV etc...

first i am creating dialog box for giving me which type of document you want to save.

This whole code is for choosing the document format and generate PDF.


#!/usr/bin/env python
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch
from reportlab.lib.colors import magenta, red
from reportlab.platypus import SimpleDocTemplate
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.units import inch
from reportlab.lib.pagesizes import A4
from reportlab.platypus import Paragraph
from reportlab.lib.utils import simpleSplit
from reportlab.pdfbase.pdfmetrics import stringWidth
from reportlab.lib.enums import TA_CENTER
import subprocess
import os
import gtk

class form:
    #This is for wrap pdf text in pdf file

    def shrink_font_size(self, aW, aH, text, style):
        """Shrinks font size by using pdfmetrics to calculate the height
        of a paragraph, given the font name, size, and available width."""
        def break_lines(text, aW):
            # simpleSplit calculates how reportlab will break up the lines for
            # display in a paragraph, by using width/fontsize.
            return simpleSplit(text, style.fontName, style.fontSize, aW)
    
        def line_wrap(lines, style):
            # Get overall width of text by getting stringWidth of longest line
            width = stringWidth(max(lines), style.fontName, style.fontSize)
            # Paragraph height can be calculated via line spacing and number of lines.
            height = style.leading * len(lines)
            return width, height
    
        lines = break_lines(text, aW)
        width, height = line_wrap(lines, style)
    
        while height > aH or width > aW:
            style.fontSize -= 1
            lines = break_lines(text, aW)
            width, height = line_wrap(lines, style)
            
    def __init__(self):
       #this is dialog box for choosing format and generate pdf file and docx file text file xlx file etc....
        dialog = gtk.MessageDialog(
            None,
            gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
            gtk.MESSAGE_QUESTION,
            gtk.BUTTONS_OK_CANCEL,
            None)
        dialog.set_position(gtk.WIN_POS_CENTER)
        dialog.set_markup('In which format you want to save')
        hbox = gtk.VBox()
        hbox.set_uposition(80,60)
        entry = gtk.RadioButton(None, label="PDF")
        hbox.pack_end(entry)
        entry = gtk.RadioButton(entry, label="TXT")
        hbox.pack_end(entry)
        entry = gtk.RadioButton(entry, label="XLS")
        hbox.pack_end(entry)
        entry = gtk.RadioButton(entry, label="CSV")
        hbox.pack_end(entry)
        entry = gtk.RadioButton(entry, label="DOC")
        hbox.pack_end(entry)
        dialog.vbox.pack_end(hbox, True, True, 0)
        dialog.show_all()
        act=dialog.run()
        if act==-5:
            for r in entry.get_group():
                if r.get_active():
                    text=r.get_label().lower()
                    print text
            dialog.destroy()
            txt="Lorem Ipsum is simply dummy text of the printing and type setting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
            if text=="pdf":
                doc = SimpleDocTemplate(os.path.join(os.path.expanduser('~'), 'Desktop')+"\hello1.pdf")
                parts = []
                PAGE_WIDTH, PAGE_HEIGHT = A4
                aW = PAGE_WIDTH - 1*inch  
                aH = PAGE_HEIGHT - 1*inch
                style = ParagraphStyle(name='Times New Roman')
                style.fontSize = 12
                style.leading = 20
                self.shrink_font_size(aW, aH, txt, style)
                p = Paragraph(txt, style)
                style1 = ParagraphStyle(name='Times New Roman')
                style1.fontSize = 16
                style1.leading = 20
                style1.textColor = 'red'
                style1.alignment = TA_CENTER
                q=Paragraph("Report", style1)
                parts.append(q)
                parts.append(p)
                doc.build(parts)
            else:
                file = open(os.path.join(os.path.expanduser('~'), 'Desktop')+"\hello1.pdf", "wb")
                file.write(txt)
                file.close()
            path_to_pdf = os.path.abspath(os.path.join(os.path.expanduser('~'), 'Desktop')+'\hello1.pdf') 
            process = subprocess.Popen([path_to_pdf], bufsize=2048, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
            process.wait()
        else:
            text=None
            dialog.destroy()
        
    def main(self):
        gtk.main()
if __name__ == '__main__':
    first = form()
    first.main()
    

Thanks Guys

Sunday 8 December 2013

Install Python Plugin in Eclipse

If you have any Eclipse and you want to python environment in eclipse then you have to install plugin in eclipse then you can achieve environment of python and python related all module.

Because this plugin takes all software update which is installed in python. it will automatically configure when u install plugin.

Go through below steps
Step 1: Install python plugin in eclipse

Note: Instructions are targeted at Eclipse 3.5 onwards
To install Aptana plugin Extensions using the Eclipse Update Manager, you need to use the Help > Install New Software... menu
image0







To install PyDev and PyDev Extensions using the Eclipse Update Manager, you need to use the Help > Install New Software... menu (note that in older versions, this would be the 'Find and Install' menu).
 image0

In the next screen, add the update site(s) you want to work with ( See below for a list with the available update sites).

Main:
Nightly builds:
After entering the update sites, select the update site you entered or select "All available sites" and add a filter for PyDev, so that it shows the contents of all the update sites that have PyDev, then select what you want to install and click 'Next'.
image1
Then, UNCHECK the 'Contact all update sites during install to find required software' and press 'Next' again to confirm your selection.
image2
And finally, read the license agreement and if you accept, select the accept radio button and click 'Finish'.
image3
At that point, Eclipse should automatically download the plugin contents and present you to a dialog asking if you want to restart (to which you should say yes).

 Step 2: Configuration of Eclipse 

You also have to maintain in Eclipse the location of your Python installation. Open in the WindowPreferencePydevInterpreter Python menu.



Press the New button and enter the path to python.exe in your Python installation directory. For Linux and Mac OSX users this is normally /usr/bin/python. 

  1. Click "New..." and type Python32 for the Interpreter name. For the Interpreter executable, browse to your copy of Python (C:\Program Files\Python32\python.exe), and press Open.
     

    Click "OK" and the  Selection Needed Window will appear.

Writing Your First Python Program

    1. Go to Window → Open Perspective → Other and choose PyDev, then click OK. If you look at the upper right corner you will see that the perspective has changed from "Java" to "PyDev".
    2. Perspectives are designed to have the most useful tools within reach for whatever task you are doing (for example writing Java code or writing Python code). If you look in the File→ New menu you will see that there are different options with the different perspective.
      PyDev Perspective Java Perspective
      As you can see, perspectives greatly affect the look of the Eclipse program.
  1. Create a new project
    1. Go to File → New → PyDev Project to start a wizard.
    2. In the next window that appears, enter the name of your project and select "python"  and 3.0"; as the type. Make sure "create default 'src' folder and add it to the pythonpath?" is selected. Click Finish.
    3. If you look at the upper left corner of the workspace (in the Package Explorer view), you should now see your newly created project with a "src" folder inside.
  2. Create a new module
    1. Select the project you just created and go to File → New → PyDev Module. This will launch a new PyDev Module Wizard where you should enter a name for your module and make sure it is in the right location. Leave the Package field blank and select Finish.
    2. Look in the Package Explorer view and you will see an icon of your new file inside the src folder, which Eclipse created when you made the new project before.
      The file should be opened in the open space in the center of the workspace-the Editor view. (If not, right click on the greeting.py icon and select Open.) You will see a tab with the name of your file.
  3. Write and run the program
    1. Here's a program to greet the world. Simply type print('Hello, World!') into the file. You may remove the default doc comment or leave it there; Python ignores it.
    2. Right click on the file and select Save (or press Ctrl+S) to save the file.
    3. Finally, choose the greeting.py icon, and go to Run → Run As → Python Run to run your program. (A quicker alternative is to right-click on the greeting.py icon, and select Run As → Python Run, or press Ctrl+F11.)
    4. Look at the bottom of your screen at the Console view and you will see the message you told the computer to print.
      Congratulations! You have written your first program with Python.

 Thanks guys

How to detect Credit card type based on number in Python?

If you have any credit card number then you can easily find that credit card number is which type of card like as (Visa card, master card, dinner card, JCB, AMX card etc...)

I am showing both ways to finding credit card type 

1) Manual calculation you can find it.
2) Using python code you can find it.

1) Manual calculation for credit card type

see below images, it will show how to find credit card type


 1) Using Python code for credit card type

from python code you can find as below.
Actually all cards having some fix prefix and length . according to that we can find which card is which type. see this link List of Issuer Identification Numbers.

for algorithm open this link  Card type Luhn algorithm

This is a  fix prefix and length of card number.

  VISA = [
        {length: [16], prefixes: ['4']}
    ]
    MASTERCARD = [
        {length: [16], prefixes: ['51', '52', '53', '54', '55']}
    ]
    ######## other brands ########
    AMEX = [
        {length: [15], prefixes: ['34', '37']}
    ]

    DINERS = [
        {length: [14], prefixes: ['300', '301', '302', '303', '304', '305', '36']},
    ]

    #There are Diners Club (North America) cards that begin with 5. These are a joint venture between Diners Club and MasterCard, and are processed like a MasterCard
    DINERS_US = [
        {length: [16], prefixes: ['54', '55']}
    ]

    DISCOVER = [
        {length: [16], prefixes: ['6011', '622126', '622127', '622128', '622129', '62213',
                                '62214', '62215', '62216', '62217', '62218', '62219',
                                '6222', '6223', '6224', '6225', '6226', '6227', '6228',
                                '62290', '62291', '622920', '622921', '622922', '622923',
                                '622924', '622925', '644', '645', '646', '647', '648',
                                '649', '65']}
    ]

    JCB = [
        {length: [16], prefixes: ['3528', '3529', '353', '354', '355', '356', '357', '358']}
    ]


    LASER = [
        {length: [16, 17, 18, 19], prefixes: ['6304', '6706', '6771', '6709']}
    ]

    MAESTRO = [
        {length: [12, 13, 14, 15, 16, 17, 18, 19], prefixes: ['5018', '5020', '5038', '6304', '6759', '6761', '6763']}
    ]

    SOLO = [
        {length: [16, 18, 19], prefixes: ['6334', '6767']}
    ]

    UNIONPAY = [
        {length: [16, 17, 18, 19], prefixes: ['620', '621', '623', '625', '626']}
    ]

and code is

def cardType(number):
    number = str(number)
    cardtype = ""
    if len(number) == 15:
        if number[:2] == "34" or number[:2] == "37":
            cardtype = "American Express"
    if len(number) == 13:
        if number[:1] == "4":
            cardtype = "Visa"
    if len(number) == 16:
        if number[:4] == "6011":
            cardtype = "Discover"
        if int(number[:2]) >= 51 and int(number[:2]) <= 55:
            cardtype = "Master Card"
        if number[:1] == "4":
            cardtype = "Visa"
        if number[:4] == "3528" or number[:4] == "3529":
            cardtype = "JCB"
        if int(number[:3]) >= 353 and int(number[:3]) <= 359:
            cardtype = "JCB"
    if len(number) == 14:
        if number[:2] == "36":
            cardtype = "DINERS"
        if int(number[:3]) >= 300 and int(number[:3]) <= 305:
            cardtype = "DINERS"
    return cardtype

print cardType("38507091291997")
 
Thanks guys 

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