Tag: Python

Starting up with Python – Part13

In this article, i will get in brief into objects. As usual here are all the articles related to Python:


30. Object Oriented Program

An object contains data and also has methods. A method in an Object is just like a function and it is called when it is inside an Object and it will use data from the very same object. An example of using a method in an object can be Mauritius.hacks() However, before building objects, classes need to be build. Let’s build a class.

>> class hackersClass:
 ... country="mauritius"
 ... members=8
 ... def thisMethod(self):
 ... return 'This method worked'
 >>> hackersClass
 <class __main__.hackersClass at 0xb721e32c>

A class has been build and it even shows us that it works. Let’s now make an object. I need the object to get the data from the class. We start by making an object set equal to the class.

>> hackersObject=hackersClass()
 >>> hackersObject.country
 >>> hackersObject.members
>> hackersObject.thisMethod()
 'This method worked'

So many objects can be build to refer to the same class. Cool isn’t it?

31. Classes and Self

The keyword class will be needed. This is a like a blueprint which is made to create methods and the “self” is made as we do not now the object name

>> class classname:
... def createName(self,name):
... self.name=name
... def displayName(self):
... return self.name
... def saying(self):
... print "hello %s" % self.name
>>> classname
<class __main__.classname at 0xb722d32c>
>>> first=className()

Lets now use the objects. Now it take self and replace it with the object name.

>>> second=classname()
>>> first.createName('nitin')
>>> second.createName('test')
>>> first.displayName()
>>> first.saying() 
hello nitin

Starting up with Python – Part12

In the last Python post, we have seen Default parameters. In this article, it will be dedicated to Multiple Parameters, Parameter types, and tuples as parameters. Here is a recap from the last article on Python


27. Multiple Parameters

Now, we will see how to put multiple parameters in functions. A simple example where we want to make a profile for manager’s name having different ages. In the example below, we have the asterisk in front of ages to be able to define as many age we want.

>> def profile(name, *ages):
 ... print name
 ... print ages

The first value will be treated as a name and everything else after it will be considered as ages. Now, we can call the profile function.

>> profile ('toto', 20,30,40)
 (20, 30, 40)

The parameter ‘toto’ is treated as a name and other as ages.

28. Parameter types

Now, will we see how to use parameters to convert it into a dictionary? Let’s create a function. Imagine we have a hackers group in Mauritius and we will need to categorized how many are there in the south, center, east, west and north. The idea is to use a double asterisk in from of Mauritius.

>> def hackers(**mauritius):
 ... print mauritius
>> hackers(south=1,center=3,east=1,west=0,north=0)
 {'west': 0, 'east': 1, 'north': 0, 'center': 3, 'south': 1}

This is how we get a dictionary instead of a tuple. Let’s now combine both to use a dictionary inside a parameter.

> def hackers(country,nickname,*age,**projects):
 ... print country, nickname
 ... print age
 ... print projects
 >>> hackers('mauritius', 'TheTunnelix', 29,30, tarsnap=2, kernel=1)
 mauritius TheTunnelix
 (29, 30)
 {'kernel': 1, 'tarsnap': 2}

29.Tuples as Parameters

Now, we will gather information from a dictionary and tuples and use that information as parameters. Instead of creating dictionaries, we can use pre-existing ones as parameters. Let’s look at the code below

>> def country(a,b,c):
... return a+b+c

Consider, I already have a tuple as indicated below and we can place the tuple inside the parameter.

>> sum=(4,2,7)
>>> country(*sum)

As you can see it output the sum of it. The first star in front sum means that I am working with a tuple and 2 stars means working with a dictionary. In the example below, it gives an example of using the 2 stars.

>> def test(**hello):
... print hello
>>> hackers={'mauritius':5,'india':2,'usa':10}
>>> test(**hackers)
{'mauritius': 5, 'india': 2, 'usa': 10}

This is useful when gathering data from an outside source.

Getting started with Ansible Deployment

Ansible is on open source IT orchestration engine that manages on-premise and in the cloud remote devices in a coordinated fashion. These are servers, networking hardware, and storage devices. Ansible can be used to talk to typical load balances, firewalls switches or any Linux machines. Continuous deployment in any environment is important as to whether the tools are predictable. Undefined behavior should be taken into consideration. Ansible is a human-readable playbook format. There is a minimum jargon in the system.


How Ansible is different compared to Puppet and Chef?

Compared to Puppet or Chef which need to have an agent installed on remote machines and the controller on the main server, but, with Ansible, you do not need to install anything on the remote machine as it relies on SSH connection and a simple push mechanism. On the other side, Puppet and Chef would use a Pull mechanism.

Let’s deploy Ansible

You would normally find lots of pretty documentation on the official website. If you want to adventure a bit around Ansible here are some tips to get started on a Centos 6 machine. I have created 2 machines called ansible1 and ansible2. Each can ping each other and Port 22 – SSH is listening. There are several dependencies needed to install Ansible. I would advise you to edit the /etc/hosts file and point the IP on the hostname if you do not have any DNS.

On ansible1, simply enable the epel repo and do a yum install ansible. However, you can also compile from source. Different Python version would be required. Those are usually the packages needed:

 python-keyczar noarch
 python-paramiko noarch
 python-pyasn1 noarch 
 python-simplejson i686

Once Ansible is installed on the machine ansible1, even if more machines are connected on the same network, you would not need to install it anything. To make ansible2 part of the ansible1 network, an inventory file need to be configured. This is located at /etc/ansible/hosts

Add the following block in the /etc/ansible/hosts file


Try testing a ping

After adding the block as mentioned above, you carry out a simple test to check for ping via the ansible command.

ansible ansible2 -m ping -u root -k

Here is the result.

Screenshot from 2016-02-20 09:54:33

You might want to set up root password. This can be set up with the command :

ansible ansible2 -m setup -u root -k

Setting up your SSH Key

However, you might want to set up Ansible with a ssh key.

On ansible1, simply create a key with the command ssh-keygen and/or if already got your key send it to the ansible2 using the following commands ssh-copy-id -i ansible2. Also repeat same steps on ansible2 by sending your key to ansible1. The file located at ~/.ssh/authorized_keys would contain the keys. As from here you simply run any command without being prompt each time to enter password.

Screenshot from 2016-02-20 10:14:10

More funs with commands

Let’s say we want to have an information about the /etc/passwd file from the ansible2 server. We simply need to fire this command

ansible ansible2 -m file -a 'path=/etc/passwd'

Screenshot from 2016-02-20 10:20:26

I can also create a directory with Ansible in any directory i want and even setup the user and group permission. For example to create a directory in the /tmp.

ansible ansible2 -m file -a 'path=/tmp/hackers_mauritius state=directory mode=777 owner=root'

Screenshot from 2016-02-20 10:26:50

Errors that can be encountered

However, its very important you test your command before setting it up on production environment. Errors can also be encountered if dependencies packages are not installed. For example let’s send a file from ansible1 to ansible2. The command is

ansible ansible2 -m copy -a 'src=/root/hackers.log dest=/tmp'

Screenshot from 2016-02-20 09:37:59

You might noticed that SELINUX can be disabled or simply set the parameter in the /etc/selinux/config. I have disabled selinux and rebooted the machine. Here is the output

Screenshot from 2016-02-20 10:45:51

Starting up with Python – Part 11

We have now reached yet another interesting part of the Python tutorial on building your own functions and default parameters.

Starting up with Python - Part 11 1

25. Building functions

We have been using several built-in functions in Python. This time we are going to build our own functions. We will start by defining the function – see line1. After having defined the function, we will need to tell the function what to do. Here is an example where a function is created and instructed what to do.

>> def hackers(x):
... return 'whats up mauritius' + x

Now, the function is used just by inserting the following line. As you can see it returns friends by using the function hackers.

>> print hackers(' friends')
whats up mauritius friends

Another example where a function can be created is by adding a specific number.

>> def addition(z):
... return z+10
>>> print addition(10)

26. Default Parameters

Default parameter in the functions is used instead of having a default value. Here is an example of a simple basic function which takes two parameters.

>> def continent(east,west):
... print '%s %s' % (east, west)
>>> continent('australia', 'africa')
australia africa

Now, the function has rewritten a function that already has default values in it. Here is an example. We also noticed that the continent function gave the value Australia and Africa directly.

>> def continent(east='australia', west='africa'):
... print '%s %s' % (east, west)
>>> continent()
australia africa

But what if we want to overwrite Africa and use Madagascar instead? Here is the catch. Whenever a specific value is given, it will overwrite the default value otherwise use the default values

>> continent('australia','madagascar')
australia madagascar
>>> continent()
australia africa 

You can also overwrite default values as such:

>> continent(west='usa')
australia usa

Starting up with Python – Part10

This part will be dedicated to For and While loops in python as well as Infinite loops and Break. Loops allow us to execute a certain block of codes multiple times without really typing it multiple time. Below is a list of topics we have already gone through:

 Starting up with Python - Part10 2

21. The While loop

To make a basic loop, we will need a variable. The code below shows a which is assigned to 1. Then in the second line, it says while 1 is less or equal to 10, let’s print a by adding 1 to it. This will keeps on adding 1 until a is less or equal to 10. If the fourth line is not used, a will be equal to 1 for the whole time because it does not know when a will end.

#! /usr/bin/env python
a = 1
    while a <=10:
print a
 a +=1

22. The For loop

The code below shows a list where the variable country is assigned with values. At line 2 when the for loop starts, it puts every country’s name in the value called a. The code simply said for a in country each time several times by grabbing all values (countries) assigned to country.  So, the output is done by assigning the value of each time to the line it’s printing.

#! /usr/bin/env python
for a in country:
    print 'i want to go to ' + a

23. The Infinite loop

The loop here is going to print the country together with the temperature value.

#! /usr/bin/env python

for a in temperature:
print a, temperature[a]

24. Break a loop

What is most interesting is to break a loop by keeping the prompt until the right answer is found. Here is an example. As you can see the while 1 is a test to keep on looping forever. To stop the unlimited look, we use a break statement at line 2. The variable name is used to test the break statement. So each time a name is going to be inserted, it’s going to store it in raw_input. What is going to happen is that it’s going to loop forever until the name ‘nitin‘ is found.

>>> while 1:
... name = raw_input('My name is: ')
... if name == 'nitin': break
My name is: tim
My name is: what?
My name is: nitin