Search This Blog

Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Using Python to generate configuration file from Excel data

Here it is example how to generate configuration script, e.g. for Cisco or Ericsson, from excel data file. It require xlrd python module for Excel file reading.

import re
import xlrd

def replace_words(text, word_dic):
    """
    take a text and replace words that match a key in a dictionary with
    the associated value, return the changed text
    """
    rc = re.compile('|'.join(map(re.escape, word_dic)))
    def translate(match):
        return word_dic[match.group(0)]
    return rc.sub(translate, text)

"""
preparing the Excel workbook
"""
workbook = xlrd.open_workbook('Book1.xlsx')
worksheet = workbook.sheet_by_name('Sheet1')
num_rows = worksheet.nrows -1
curr_row = 1

while curr_row < num_rows:
    curr_row += 1
    row = worksheet.row(curr_row)
   
    """
    seting up the cell
    """
    hostname = row[0].value
    loopback0 = row[1].value
    ip_address = row[2].value
    netmask = row[3].value
   
    """
    preparing the tamplate
    """
    t = open('Template1.txt')
    tempstr = t.read()
    t.close   
       
    values = {
        '[Hostname]':hostname,
        '[Loopback0]':loopback0,
        '[IP_Address]':ip_address,
        '[Netmask]':netmask,
        }
   
    """
    seting up the output script name,
    replace the variable in template with data, then write it out ...
    """
    outputfile = hostname + "_CONFIG.txt"
    output = replace_words(tempstr, values)
    fout = open(outputfile, "w")
    fout.write(output)
    fout.close
       


Example excerpt from Cisco configuration script, note the bold text that will be replace by script:     

version 12.4

service timestamps debug datetime msec

service timestamps log datetime msec

no service password-encryption

!

hostname [Hostname]

ip cef

!

interface Loopback0

ip address [Loopback0] 255.255.255.0

!

interface GigabitEthernet0/0

ip address [IP_Address] [Netmask]

duplex auto

speed auto

!


Example data IP


where:
-Book1.xlsx is our database
-Template1.txt is our template

Get exercise file here.

I hope you found it useful :)

Python: Object Oriented Programming

Introduction
In all the programs we wrote till now, we have designed our program around functions i.e. blocks of statements which manipulate data. This is called the procedure-oriented way of programming. There is another way of organizing your program which is to combine data and functionality and wrap it inside something called an object. This is called the object oriented programming paradigm. Most of the time you can use procedural programming, but when writing large programs or have a problem that is better suited to this method, you can use object oriented programming techniques.

C# free ebook

Are you looking for free C# ebook? Try download it for free here.

The Programmer's Heaven C# School book covers the .NET framework and the C# language. Starting with the basics of the language, it goes on to cover object oriented programming techniques and a wide range of C# languages features including interfaces, exceptions and delegates. Later chapters cover practical topics including database access with ADO.NET, building Windows forms applications, multi-threading and asynchronous I/O. The final chapter covers new features in C# 2.0, including generics.

Python: Data Structures

Introduction
Data structures are basically just that - they are structures which can hold some data together. In other words, they are used to store a collection of related data. There are four built-in data structures in Python - list, tuple, dictionary and set. We will see how to use each of them and how they make life easier for us.

Python: Modules

Introduction
You have seen how you can reuse code in your program by defining functions once. What if you wanted to reuse a number of functions in other programs that you write? As you might have guessed, the answer is modules. There are various methods of writing modules, but the simplest way is to create a file with a .py extension that contains functions and variables. Another method is to write the modules in the native language in which the Python interpreter itself was written. For example, you can write modules in the C programming language (http:/ / docs. python. org/ extending/ ) and when compiled, they can be used from your Python code when using the standard Python interpreter.

Python: Functions

Introduction
Functions are reusable pieces of programs. They allow you to give a name to a block of statements and you can run that block using that name anywhere in your program and any number of times. This is known as calling the function. We have already used many built-in functions such as the len and range. The function concept is probably the most important building block of any non-trivial software (in any programming language), so we will explore various aspects of functions in this chapter.

Python: Control Flow if, while and for

Introduction
In the programs we have seen till now, there has always been a series of statements and Python faithfully executes them in the same order. What if you wanted to change the flow of how it works? For example, you want the program to take some decisions and do different things depending on different situations such as printing 'Good Morning' or 'Good Evening' depending on the time of the day?

Python: Basics

Just printing 'Hello World' is not enough, is it? You want to do more than that - you want to take some input, manipulate it and get something out of it. We can achieve this in Python using constants and variables.

Python: First Steps

Introduction
We will now see how to run a traditional 'Hello World' program in Python. This will teach
you how to write, save and run Python programs.

Python: Installation

If you have Python 2.x installed already, you do not have to remove it to install Python 3.0.
You can have both installed at the same time.

How To Create Wordpress Theme From Scratch #2

We've successfully create our first Wordpress theme. Actually, we didn't create real theme, that just static HTML and CSS that identified as theme by Wordpress. Now, we will make that static script to become real Wordpress theme.

How To Create Wordpress Theme From Scratch

Wordpress is popular bloging platform that evolve into self-publishing-site platform. And you may be wonder how to create Wordpress theme. I share my experience learning Wordpress theme here.

PHP array() syntax into Python

Here are some comparison PHP array() into Python. In Python, there are list, dict and tuple -- or sequence in general -- as data structure format.

Free programing e-learning: www.openbookproject.net

I'm Python fan, although I learn it just for fun. And read its official documentation make a lot of headache :). I try to looking around simpler, cleaner documentation or tutorial. One of good resource to learn Python is www.openbookproject.net.

This web site provides easy to learn free book for Python, you may download it using web page copier such a HTTrack to save a copy to your computer. From ground up basic programming with Python, and a lot of examples, into advance Object-Oriented Programming concept and practical.

Chapter-by-chapter will guide you into more deep understanding, -- be problem solving programmer-- with real-world sample application. I highly recommend this web site as your Python knowledge source.