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