Tags

, , , , , , ,

Python is mentioned at least once at every SWLUG meetup, along with Perl and Ruby, and apparently Python scripting is one of the important sysadmin/infosec skills. With my original plans for the last several days being scuppered on account of bad weather, I finally got round to learning the basics of this language with the help of CodeAcademy. As always, I’ve uploaded some of my work to SourceForge.

Okay, what is Python? It’s an interpreted language with a syntax probably best described as a hybrid of C++ and BASH scripting, and like any language it has advantages and disadvantages. A Python interpreter is easy to install, and a typical web hosting plan will provide one as standard, so it’s portable to some extent.
The downside, if we want Python to be portable(ish), is being limited to what the common Python interpreter allows – that is scripts/programs can’t be compiled with fancy ingredients outside the standard interpreter into a nice little executable. A cake recipe is no good if most readers don’t have the materials in their kitchen. If the readers were given the finished cake (a compiled executable) instead, that’s no longer a problem.

Python Interpreter

Python Interpreter

An Executable Script
Just like a BASH script, a Python executable starts with the following line to retrieve the interpreter’s environment data from /usr/bin/env:
#! /usr/bin/env python

To output a text string:
print "Hello World"

Now save the file as example.py, open the command line and type ‘python example.py‘ to run it.

Variables and Buffers
People will commonly hear things referred to as ‘variables’, but it’s more useful to think of them as labels assigned to areas of memory used by the script as ‘buffers’. Although the interpreter handles all the specifics, the concept becomes important later in understanding what happens when a program executes.
In Python, variables are declared pretty much the same as with most other languages. e.g.
VariableName = 5

Once a variable is declared, the value it stores can be altered elsewhere in the program. In other words, the contents in the buffer are changed. e.g.
#! /usr/bin/env python
# Place value '7' in VariableName
VariableName = 7
# Change value to '8'
VariableName = 8
#Now we'll output contents of VariableName to screen.
print VariableName

Of course, if a sufficiently large value is stored in a buffer, we get a ‘buffer overflow’.

Data Types
Python has three main data types, or at least three I’ve come across so far:
* Integer
* Float
* Boolean (True/False)

Notice ‘real’ numbers aren’t defined as single or double, so we can’t define the buffer sizes for the variables here as with C++.
Unfortunately numerical and Boolean values can’t be included directly in text output, as we can in other programming languages. They must first be read as a string with the str() function. e.g.
print "The answer is: " + str(VariableName)

Arithmetic Operators
I’ve tried skipping over the usual arithmetic stuff, to focus on more practical features. Python has basic operators that are the same across most other languages, plus another two that later become useful for writing cryptographic programs. The exponentiation operator (**) raises the base number to the power of its exponent. For example, 2e5 would be:

2 ** 5
which is the same as:
2*2*2*2*2

The modulo operator (%), gives us the remainder of an integer division.

User I/O, Strings and Buffers
The following code does two things: 1) It stores the user’s text input in three buffers called ‘name’, ‘quest’ and ‘colour’. 2) The buffers are read in sequence from a one-dimensional array and inserted into the text output:

name = raw_input("What is your name?")
quest = raw_input("What is your quest?")
colour = raw_input("What is your favorite colour?")

print "Ah, so your name is %s, your quest is %s, \
and your favorite color is %s." % (name, quest, colour)

There are other built in functions for manipulating text, including:
str(): Turns the contents into a string.
print len(my_string): Print length of the string.
string.upper(): Turns string into upper case.
string.lower(): Turns all characters in a string to lower case.
%s: Read variable as string.

Basic Length Conversion Program using Input and Output
As mentioned, I’ve skipped over the arithmetic stuff, but here’s an example that combines a calculation and user I/O:

#! /usr/bin/env python
centimetre = float(raw_input("Please enter the length in centimetres: "))
inch = centimetre/2.5
print inch

Importing Python Modules
Here’s where Python starts to get interesting. As with certain other programming languages, Python calls functions from external modules for certain tasks.

# Import Python modules
import math

# Let's see what functions are imported from the math module
everything = dir(math)
print everything

# Use the sqrt() function from the imported math module
print math.sqrt(25)

The same principle applies when importing from the datetime Python module. Since a program can’t work directly with the data received by the datetime.now() function, the data must be stored in a buffer called ‘CurrentTime‘:

#! /usr/bin/env python
from datetime import datetime

# Put local timer information into buffer.
# CurrentTime also becomes a namspace for other data sources
CurrentTime = datetime.now()

# Print contents of buffer
print CurrentTime

# Print day, month and year separately as strings
print "The month is: " + str(CurrentTime.month)
print "The day is: " + str(CurrentTime.day)
print "The year is: " + str(CurrentTime.year)

So, this is basically what I’ve learned so far. There might be more stuff to post here over the next several months.

Advertisements