Monday, January 7, 2013

Python Fundamentals (variables and data types)

These are my ongoing notes as I start developing penetration tools with Python.  The blog series will encompass basic Python syntax to actual examples of developed code.

Pythons variables (names) are references to objects not strings; similar to pointers.  To learn more about Python objects, please click here.

An example of setting a variable to reference memory locations:
>>> name = "bob"
>>>
>>> id(name)
140195719219888
>>>
>>> hex(id(name))
'0x7f81dc0b0ab0'
>>>
>>> name.__repr__
<method-wrapper '__repr__' of str object at 0x7f81dc0b0ab0>
>>>


Python strings are a sequence of characters or some kind of variable.  Examples:

  • name = "bob"
  • name = 'bob'
  • name = "bob's"
  • name = 'bob\nsmith' (adds a new line when printed)
  • name = r'chris\nmaenner' (Raw string)

Unicode Strings are used for Internationalization.  "Wide characters" are used to encode multiple languages and characters for a international purpose.

>>> name =u'chris'
>>> str(chris) "unicode to regular string conversion."
>>> str(name) "regular string to unicode conversion."
'chris'
>>> unicode(name)
u'chris'


String Operations: strings are immutable objects in Python; once you create a string you cannot change them anymore.  For example:

>>> name = "chris"
>>> name[0]
'c'
>>> name[0] = 'a'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> 
>>> name
'chris'
>>> a = "bob"
>>> name = a
>>> name
'bob'
>>> a
'bob'
>>> a = "chris"
>>> a
'chris'
>>> name
'bob'
>>>


A quick method for causing a buffer overflow:
>>> buffer = "f00"*25
>>> buffer
'f00f00f00f00f00f00f00f00f00f00f00f00f00f00f00f00f00f00f00f00f00f00f00f00f00'
>>>


Python slice indices:
>>> name = "bob smith"
>>>
>>> name[2:7] (grabs the character in the 2nd position and everything up to the 7th position)
'b smi'
>>>

So to display how slices work from the example above, the 2nd position is "b" and all characters up until the 7th position which is "t" will be displayed in the Python interrupter.
+---+---+---+---+---+---+---+---+---+
| b | o | b |   | s | m | i | t | h |
+---+---+---+---+---+---+---+---+---+
    0   1   2   3   4   5   6   7   8

String Formatting:

>>> ip = "10.0.0.100"
>>> line = "crack this IP: %s" % ip
>>> line
'crack this IP: 10.0.0.100'
>>>
>>> line = "Crack this IP: %s and name %s" % (ip, "bunny")
>>> line
'Crack this IP: 10.0.0.100 and name bunny'

No comments:

Post a Comment