Archive

Archive for the ‘Python’ Category

Python 2.5 Released

This is just a short post... Python 2.5 has been released... There are a few syntax changes that look like they're for the better... I'm interested to sit and play with it later.

From the release notes:

Python Introduction — Part 3

The third installment -- originally posted here.

Before I jump into those there is another chart I would like to add. In my last tutorial I mentioned a new way to use the print command, to make it a little more C/C++ like. However I didn't realize that some users may not have C/C++ experience and not know about the % options. So here is a chart with all of your options.

quote:
Source: Python 101 - Beginning Python

d Signed integer decimal.
i Signed integer decimal.
o Unsigned octal.
u Unsigned decimal.
x Unsigned hexidecimal (lowercase).
X Unsigned hexidecimal (uppercase).
e Floating point exponential format (lowercase).
E Floating point exponential format (uppercase).
f Floating point decimal format.
F Floating point decimal format.
g Same as "e" if exponent is greater than -4 or less than precision, "f" otherwise.
G Same as "E" if exponent is greater than -4 or less than precision, "F" otherwise.
c Single character (accepts integer or single character string).
r String (converts any python object using repr()).
s String (converts any python object using str()).
% No argument is converted, results in a "%" character in the result.

Now on to our new lesson.

I would like to look at executing files located on your system. As I mentioned in the first tutorial I would like to keep this OS inspecific so we will deal with the ping command as it is universal. I will be using the count flag and I will use the windows flag which is -n, so *nix users must remember to change it to -c or they will get an error.

********************
Step-by-Step Process
********************
1. Open your favourite editor (Vi, Pico, Notepad, Wordpad, Textpad, DOS Edit).
2. Type

code:

from os import * count = input("Number of times to ping host: ") host = raw_input("IP of host to ping: ") pingcmd = "ping -n %i %s" % (count, host) execute = popen(pingcmd) results = execute.readlines() execute.close() length = len(results) for x in range (length) : print results[x]


3. Save the script as pingtest.py
4. Open a command prompt and type python pingtest.py
5. This one is a little more difficult to walk you threw. First you will see Number of times to ping host: . Enter a number and press enter. Then you will see IP of host to ping: . Enter an IP and again press enter. There will be a pause (the length of which will depend on how many times you told it to ping). Then you will see the standard output of a ping command written to the screen.

Now to walk you threw this script. We import the OS module and then query the user for the number of pings and the host to ping. Then we define our ping command using the same format as the print command. The next line actually executes the command followed by a line which reads the output of the command into a variable. We then close the variable which executed the command. The next line introduces another new command the len command, which returns the length. In this case since results in an array it returns the number of lines in the array. We then make use of the for command we learned in our last tutorial and have it print the actual content of the array, line by line. Notice the use of the whitespace again for the for command.

Alrighty.... moving on, I believe I promised you file reading/writing next. We'll work with a simple txt file.

********************
Step-by-Step Process
********************
1. Open your favourite editor (Vi, Pico, Notepad, Wordpad, Textpad, DOS Edit).
2. Type

code:

print "File Write/Create Example." filename = raw_input("File to Write To/Create: ") openfile = file(filename, 'w') print "Enter text to write to file (Type 'quit' to quit):" line = "" alllines = "" while 1 : line = raw_input() if line == 'quit' : break alllines = alllines + line + "n" file.write(openfile, alllines) file.close(openfile) print "You just wrote to a file, Now Let's see what you wrote." print "File Read Example." openfile = file(filename, 'r') filedata = openfile.readlines() length = len(filedata) for x in range(length) : print filedata[x] openfile.close


3. Save the script as filetest.py
4. Open a command prompt and type python filetest.py
5. When you run this program you will be prompted to enter a filename. Call the file anything you want. The next line of code then open's that file in write ('w') mode (will create it if it doesn't exist). The code then tells you to type your text, and declares to blank variables. The while 1 : is just a way of creating an infinite loop, so that every time the user hits enter, it moves to a new line of the file. The line is used to receive input, but we aren't prompting the user each time. The if statement introduces another new command, break. This will exit the loop upon seeing the string 'quit'. The next line of code simply concatenates the previous lines with the new line and then adds a newline character. After the user has entered quit we write to the file and close the file. You then see a few lines of text. The script them opens the file in read ('r') mode. We read the lines into an array and determine the number of lines like we did in our ping tutorial. We then enter a fore statement and print each line until we get to the end of the file. Then we close the file.

The last thing I promised for this tutorial was error handling. This is useful for small things like if you've forgotten to declare a variable and other such events. I can't think of a useful example at the moment, so I'll just go over the commands and if I think of some code later I'll add it.

Basically the commands are try and except.

Instead of just issuing the code, you try it. For example if you were attempting to read a file that didn't exist. The program would exit and return an error. However if you try and have an except...

code:

try : except : print "File doesn't exist."

Now if the file doesn't exist it will simple print File doesn't exist and continue on with the program.

Peace,
HT

Categories: IT, Python, Tutorials Tags:

Python Introduction — Part 2

The second in my line of imported tutorials... This was originally posted here.

This tutorial will assume you have already read my first Python Tutorial (Python Introduction).

I'm not real sure yet what I'm going to cover, I figure I'll pick at these for a couple of days and post it at the end of the weekend. Unless I get really ambitious tonight.

Before I get into some examples, I'm going to include a few charts

quote:
Source: Python Reference Manual - 2.4.1 String Literals

Escape Sequences

\newline Ignored
\\ Backslash (\)
' Single quote (')
\" Double quote (")
\a ASCII Bell (BEL)
\b ASCII Backspace (BS)
\f ASCII Formfeed (FF)
\n ASCII Linefeed (LF)
\N{name} Character named name in the Unicode database (Unicode only)
\r ASCII Carriage Return (CR)
\t ASCII Horizontal Tab (TAB)
\uxxxx Character with 16-bit hex value xxxx (Unicode only)
\Uxxxxxxxx Character with 32-bit hex value xxxxxxxx (Unicode only)
\v ASCII Vertical Tab (VT)
\ooo ASCII character with octal value ooo
\xhh ASCII character with hex value hh

quote:
Python Operators

+ addition
- subtraction
* multiplication
/ division
% module
** To the Power Of
& Bitwise And
| Bitwise Or
== equals
!= Does not Equal
<> Does not Equal (Outdated)
< Less Than
> Greater Than
< = Less Than or Equal To
>= Greater Than or Equal To
not Logical Negation
and Logical And
is, is not, in, not in Comparison

Now for some examples..

Let's start with the while statement.

********************
Step-by-Step Process
********************
1. Open your favourite editor (Vi, Pico, Notepad, Wordpad, Textpad, DOS Edit).
2. Type

code:

from random import * answer = randint(1,25) guess = 0 counter = 0 print "Welcome to the Number Guessing Game" while guess != answer : guess = input("Please Guess a Number between 1 and 25: ") if guess < answer : print "To low." elif guess > answer : print "To high." counter = counter + 1 print "Congrats you guessed the correct number (",answer,") in",counter,"tries."


3. Save the script as numberguess.py
4. Open a command prompt and type python numberguess.py
5. You will see Welcome to the Number Guessing Game, followed by a new line which states Please Guess a Number between 1 and 25. I can't walk you though this, since it uses a random number but as you guess you will see To low. or To high. Until you guess the correct number, when it will then display Congrats you guessed the correct number ( ) in

tries.

This program incorporates a lot of firsts. We've made use of the Random module which allows us to call the command randint(bottom number, top number) to randomly generate an integer. We've created a few additional variables to store values and entered into a While Statement. This is also the first time we've looked at white space. Python makes use of white space quite frequently. As you notice there is no End while or End if statements, instead the tabs (white space) tell the interpreter where each statement ends.
The while statement follows the format while : .

This next example will be relatively small as I just want to introduce the for statement and nothing else.

********************
Step-by-Step Process
********************
1. Open your favourite editor (Vi, Pico, Notepad, Wordpad, Textpad, DOS Edit).
2. Type

code:

print "This program will list the first 10 powers of a number." usednum = input("Enter the number to use: ") for x in range(10) : print usednum, "^", x, "=", usednum ** x


3. Save the script as powers.py
4. Open a command prompt and type python powers.py
5. You will see This program will list the first 10 powers of a number.. Followed by Enter the number to use: . For this example, enter the number 2 and press enter. You will then see.

2 ^ 0 = 1
2 ^ 1 = 2
2 ^ 2 = 4
2 ^ 3 = 8
2 ^ 4 = 16
2 ^ 5 = 32
2 ^ 6 = 64
2 ^ 7 = 128
2 ^ 8 = 256
2 ^ 9 = 512

This for statement uses and undeclared variable (which initializes to 0) and then cycles threw 10 times, leaving us with a last value of 9. Each time threw the cycle it prints the resulting power.

Many of you who have used C/C++ in the past have probably noticed a few similarities and this is because they exist. I have already shown you the print statement, but I will now show you another way to accomplish the same thing that is closer to the way C/C++ works.

********************
Step-by-Step Process
********************
1. Open your favourite editor (Vi, Pico, Notepad, Wordpad, Textpad, DOS Edit).
2. Type

code:

name = raw_input("What is your name: ") print "Your name is %s?" % name


3. Save the script as print.py
4. Open a command prompt and type python print.py
5. You will see a prompt which reads What is your name: . After Entering your name and pressing enter. You will see Your Name is ?.

This is a great method for joining text and variables because it doesn't add a single space like the comma did in past print statements.

Peace,
HT

Categories: IT, Python, Tutorials Tags:

Python Introduction

I've been thinking about it quite a bit lately, and I've decided to repost some of my older articles and tutorials written for ther sites.. Some of this stuff is rather basic... but it could prove useful for a number of peole out there...

This first article is a very simply python introduction that I wrote for the site AntiOnline.com. The original posting can be found here.

I'm going to pass on describing Python to you and instead let Webopedia do it for me.

quote:
Source: Webopedia Term: PythonAn interpreted, object-oriented programming language developed by Guido van Rossum. The name comes from one of van Rossum's favorite television shows, Monty Python's Flying Circus. Python is very portable since Python interpreters are available for most operating system platforms. Although Python is copyrighted, the source code is open source, and unlike GNU software, it can be commercially re-sold.

For those of you who do not have a Python interpreter, they are available on the net for download

Python.org Download Page
ActivePython from ActiveState

Now for the tutorial.

I'll try and make this as OS inspecific as possible. All these walk-throughs assume you have installed Python already.

Let's start with the most basic of programs. The obvious Hello World! Program.

********************
Step-by-Step Process
********************
1. Open your favourite editor (Vi, Pico, Notepad, Wordpad, Textpad, DOS Edit).
2. Type

code:

print "Hello World!"


3. Save the script as helloworld.py
4. Open a command prompt and type python helloworld.py
5. Voila! Hello World! is displayed on the screen.

This simply demonstrates the print command in Python. Now let's look at variables and user input.

********************
Step-by-Step Process
********************
1. Open your favourite editor (Vi, Pico, Notepad, Wordpad, Textpad, DOS Edit).
2. Type

code:

age = input("What is your age: ") print "So you are",age,"?"


3. Save the script as age.py
4. Open a command prompt and type python age.py
5. You will see an prompt which says What is your age:. Enter your age and press return. You will now see So you are 21 ?.

You will notice you do not have to declare variables in Python, simply reference them. In this example you also see how the input command is used. To input a value simply define a variable name for the value and then set it equal to the input command. The structure of the input command is

code:

input("Question to prompt with")

. You also see how to output more than one string of data, using the , to concatenate the strings. However use of the comma also automatically inserts a space. You MUST remember that input only works with numbers

Now we will attempt a simple text calculator with 4 commands (add, subtract, multiply and divide).

********************
Step-by-Step Process
********************
1. Open your favourite editor (Vi, Pico, Notepad, Wordpad, Textpad, DOS Edit).
2. Type

code:

calc = raw_input("Which function would you like to execute - [a]dd, [s]ubtract, [d]ivide, [m]ultiply: ") firstnum = input("Enter the first number: ") secondnum = input("Enter the second number: ") if calc == "a" : print firstnum,"+",secondnum,"=",firstnum+secondnum elif calc == "s" : print firstnum,"-",secondnum,"=",firstnum-secondnum elif calc == "d" : print firstnum,"/",secondnum,"=",firstnum/secondnum elif calc == "m" : print firstnum,"*",secondnum,"=",firstnum*secondnum else : print "Error: Unknown Function Entered"


3. Save the script as calc.py
4. Open a command prompt and type python calc.py
5. You will see a prompt which says Which function would you like to execute - [a]dd, [s]ubtract, [d]ivide, [m]ultiply: . For the sake of demonstration enter a and press enter. You will then see Enter the first number: . Enter 5 and press enter. Now Enter the second number: " appears. Enter 7 and hit enter. The screen will now display 5 + 7 = 12. Feel free to experiment with other functions and numbers now.

You have now been introduced to the command raw_input. It fuctions the same way as input but is used for alphanumeric entries. You are also introduced to basic mathematical functions in python (+,-,/,*) and if statements. The syntax for an if statement is

code:

if (statement) : elif (statement) : else :

One last example. We will attempt to incorporate a basic introduction to sockets into this example. *Crosses his fingers*

********************
Step-by-Step Process
********************
1. Open your favourite editor (Vi, Pico, Notepad, Wordpad, Textpad, DOS Edit).
2. Type

code:

from socket import * s= socket(AF_INET, SOCK_STREAM) yourip = raw_input("Enter your IP Address: ") yourport = input("Enter a Port Number to Listen on: ") s.bind((yourip, yourport)) s.listen(1) (incomingport, incomingaddress) = s.accept() print "Connection Attempt from", incomingaddress s.close


3. Save the script as server.py
4. Open a command prompt and type python server.py
5. You will see a prompt which reads Enter your IP Address: . Do as it says and press enter. You will then see a prompt which says Enter a Port Number to Listen on: . Answer the question and press enter. Telnet to the port you entered and wait a few seconds. Close the session and return to your python window. You will see the text Connection Attempt from .

In this example we played with sockets a little bit. The first task was to include the socket module. We did this using the statement

code:

from socket import *

. We then defined the type of socket (AF_INET, SOCK_STEAM) and created a variable for the socket to be attached to (s). We could then issue our commands based on the varible s. We bound the socket to the ip and port you had previously entered with the bind command and then started listening on that port. Upon a connection attempt we accepted the connection, printed the intruders IP to the screen and closed the socket.

Peace,
HT

Categories: IT, Python, Tutorials Tags:

Connection Stress Tester

As many of you know I participate regularly on AntiOnline (an online IT/Security Community). Recently, someone was looking for a connection stress tester... There are many available.. Blast by Foundstone comes to mind. I decided that they needed something simpler, all they wanted to do was test the number of connections a server could handle. The result was a little script that I wrote up. It's fairly basic but it does the trick. I've added some basic error checking (let me know if you want specific errors caught) and a usage function and now I'm putting it here for all of you to download (should you desire to). You can download it from here. Let me know what you think and if you want to see any additions... or a tutorial on the subject.

Peace,
HT

Categories: Python Tags:

Python and COM

So I've ventured into Python and COM, using PythonWIN and win32com.client. So far it's been fairly basic stuff... I've been manipulating outlook and dumping emails in plain-text into a file... I thought that I'd like to share the script for this... so here it is... fairly basic... let me know what you think and what I can add... If anyone is interested in any of my Python scripts and would like me to write up explanations, don't hesitate to ask..

Download dumpInbox.py

Peace,
HT

Categories: Python Tags:

gmail from the command prompt

So over the past few weeks I've been playing around with gmail and python... and libgmail.

I've decided that more people should be introduced to this and the functionality of it, so I've created a small program to allow people to play around with it... It should run on any version of python, however, I've written it with Python 2.4 in mind and of course you'll require libgmail from the above link.

My script, checkgmail.py, provides the following functionality:

---Cut from help---
Usage: ./checkgmail.py

Options:
-a All messages
-r Only read messages
-u Only unread messages
-h Display this help message
Parameters:
-L

Only messages from a specific address
-R Read the messages (display message content)
-S Return the subject lines
-C Display a message count
-Q Run the specified query (search)
-N Number of messages to return (default: ALL)
-U GMail username
-P GMail Password (default: prompt)
---End Help---
The idea is that you can pass 1 option and multiple parameters. By default it should, and I say should because I haven't extensively tested this software, prompt for a username and a password, log in and parse all unread mail in your inbox... however it won't display any information.
Some examples you could use:
 
To check and see if your mom has sent you any mail and to check the subjects you could use this command:
checkgmail.py -u -F mom@hotmail.com -S

To read the last message your girlfriend sent you, you could run something like this
checkgmail.py -u -F gf@hotmail.com -R -N 1

One important thing to remember is that whenever you parse unread messages, even if you don't display them... libgmail is still marking them read... don't let this confuse you when you revisit gmail through your browser.

Download checkgmail.py

Peace,
HT

Categories: Python Tags: