Learn Python (Part 2)

Learn Python (Part 2)
Python Basics

Read part 1 here :- Learn Python (Part 1)

PYTHON BASICS

In Article 1 (Learn Python Part 1) , we looked at many of the basics of scripting. We covered loops, conditionals, functions, and more. Many of the languages we will use have similar capabilities, but syntax and execution will differ from one language to the next. In this section, we will investigate the syntactical and conceptual differences in the concepts that have already been presented, and how they apply to the Python language.

Getting started

We want to create Python files in a text editor. Text editors are a matter of personal preference. As long as the indentation is consistent, Python won’t mind. For those who do not already have an editor of choice, the Kate editor that was demonstrated in Article 1 (Learn Python Part 1) has a graphical user interface (GUI) and is simple to use. In addition to having syntax highlighting, Kate handles automatic indentation, making it easier to
avoid whitespace inconsistencies that could cause Python to fail. Python scripts are .py files. For example, hello.py might be our first script. To use Kate, try typing kate hello.py to create a simple script.

Formatting Python files

Formatting is important in Python. The Python interpreter uses whitespace indentation to determine which pieces of code are grouped together in a special waydfor example, as part of a function, loop, or class. How much space is used is not typically important, as long as it is consistent. If two spaces are used to indent the first time, two spaces should be used to indent subsequently.

Running Python files

Let’s get comfortable with Python by writing a quick and simple script. Copy the following code into a text editor and save it as hello.py:

#!/usr/bin/python
user = “<your name>”
print “Hello ” + user + “!”

Line one defines this as a Python script. This line is typically not required for scripts written in Windows, but for cross-compatibility it is acceptable to include it regardless of platform. It gives the path to the Python executable that will run our program. In line two, we assign our name to a variable called user. Next, we print
the result, joining the text together using the concatenation operator, a plus sign, to join our variable to the rest of the text. Let’s try it! We can run our script by typing python hello.py in a shell window. Linux or UNIX environments offer a second way to run Python scripts: We can make the script executable by typing chmod u+x hello.py and then ./hello.py. So now, using Back-Track, let’s make it happen! See Figure  for an example of expected output from Back-Track.

Two Ways to Run a Python Script in Linux
Two Ways to Run a Python Script in Linux

If you Write that code Congratulations! You have just written your first Python script. Chances are good
that this will be the only time you write a Python script to say hello to yourself, so let’s move on to more useful concepts.

Variables

Python offers a few noteworthy types of variables: strings, integers, floating-point numbers, lists, and Dictionaries.

#!/usr/bin/python
myString = “This is a string!” # This is a string variable
myInteger = 5 # This is an integer value
myFloat = 5.5 #This is a floating-point value
myList = [ 1, 2, 3, 4, 5] #This is a list of integers
myDict = { ‘name’ : ‘Python User’, ‘value’ : 75 } #This is a dictionary
with keys representing # Name and Value

Everything after the # on a line is not interpreted by Python, but is instead considered to be a comment from the author about how a reader would interpret the information. Comments are never required, but they sure make it easier to figure out what the heck we did last night. We can create multi-line comments using three double quotes before and after the comment. Let’s look at an example.

#!/usr/bin/python
“””
This is a Python comment. We can make them multiple lines
And not have to deal with spacing
This makes it easier to make readable comment headers
“””
print “And our code still works!”

In Python, each variable type is treated like a class. If a string is assigned to a variable, the variable will contain the string in the String class and the methods and features of a String class will apply to it. To see the differences, we are going to try out some string functions in Python interactive-mode by just typing python at the command prompt. Follow along with Figure 2 by entering information after the >>> marks.

String Manipulation in the Interactive Python Shell
String Manipulation in the Interactive Python Shell

We started by creating a string called myString. Then we used the bracket operators to get the first four characters. We used [:4] to indicate that we want four characters from the beginning of the string. This is the same as using [0:4]. Next, we used the replace function to change the “o” character to the “0” character. Note
that this does not change the original string, but instead outputs a new string with the changes. Finally, we used the split method with a space delimiter to create a list out of our string. We will use this again later in the chapter when parsing input from the network.

TIP
To find out more string functions to test on your own, you can visit the Python reference manual for strings at http://docs.python.org/library/strings.html.

Modules
Python allows for grouping of classes and code through modules. When we use a module, we will “import” it. By importing it, we gain access to the classes, class methods, and functions inside the module. Let’s explore modules more through our interactive Python session in Figure 3. Python makes finding an MD5 hash of text (say, a password, for example) very easy. Notice that Python has no idea what we are trying to do until we
import the module. But, once we do, we get the hash of our original value in hexadecimal.

TIP
The hashlib module has more hash types that can be calculated. The full list of algorithms
and methods is available at http://docs.python.org/library/hashlib.html.

 

Importing a Module Using the Python Interactive Shell
Importing a Module Using the Python Interactive Shell

Arguments

So far the scripts we have created have been static in nature.We can allow arguments to be passed on the command line to make scripts that are reusable for different tasks. Two ways to do this are with ARGV and optparse. The ARGV structure is a list containing the name of the program and all the arguments that were passed to the application on the command line. This uses the sys module. The other option is the opt-parse module. This gives more options for argument handling. We’ll explore each in more detail shortly. While conducting a penetration test, there is always a chance that something we are doing may adversely affect a server. We want to make sure the service we are testing stays up while we are conducting our test. Let’s create a script using the sys module and the httplib module to do Web requests. Follow along by creating the
following file as webCheck.py and make it executable with chmod u+x webCheck.py.

#!/usr/bin/python
import httplib, sys
if len(sys.argv) < 3:
sys.exit(“Usage ” + sys.argv[0] + ” <hostname> <port>n”)
host = sys.argv[1]
port = sys.argv[2]
client = httplib.HTTPConnection(host,port)
client.request(“GET”,”/”)
resp = client.getresponse()
client.close()
if resp.status == 200:
print host + ” : OK”
sys.exit()
print host + ” : DOWN! (” + resp.status + ” , ” + resp.reason + “)”

This script shows how to import modules inside a script. It is possible to import multiple modules by separating them with a comma. Then we do some basic error checking to determine that our argument list from ARGV is at least three elements long. The name of the script you are running is always in sys.argv[0]. In this script, our
other arguments are our host and the port we want to connect. If those arguments are absent, we want to throw an error and exit the script. Python lets us do this in one line. The return code for sys.exit is assumed to be 0 (no error) unless something else is specified. In this case, we are asking it to display an error, and Python will assume it should return a code of 1 (error encountered) since we have done this.We can use any number in this function if we want to make custom error codes.
Once we have assigned our remaining list items into appropriate variables, we need to connect to our server, and request our URL. The method client. getresponse() retrieves an object which contains our response code, the reason for the code, and other methods to retrieve the body of the Web page we requested. We want to make sure the page returned a 200 message, which indicates that everything executed successfully. If we did receive a 200 message, we print that the site is okay and exit our script successfully. If we did not receive a 200 code, we want to print that the site is down and say why. Note that we did not tell sys.exit() a number here. It should assume 0 for OK. However, it’s a good practice not to assume and make a habit of always putting in a number. The resp.status will have our return code in it, and the resp.reason will explain why the return code was what it was. This will allow us to know the site is down.

Information
To be continue….. In next Article We discuss more..
You guys get part 1 Here
link:- https://thehacktoday.com/learn-python-part-1/

 

Back to top button
Close