Hack Like a Pro: Python Scripting for the Aspiring Hacker, Part 2

Python Scripting for the Aspiring Hacker, Part 2

Welcome back, my fledgling hackers!

In an earlier tutorial, I introduced you to probably the most popular scripting language for hackers, Python. To become a professional hacker, you need to have some scripting skills and Python is a good choice if you want to master just one. In this latest guide, I will expand your background in Python and offer you a tidbit of Python code to whet your appetite for all of the hacking to come.

Please understand that learning any programming language takes time and much hard work. Be patient with yourself and attempt to master each small module I provide you with here on Null Byte. This series is likely to run many, many modules as we attempt to convey the necessary skills to Hack Like a Pro.

Object-Oriented Programming (OOP)

Before we delve deeper into Python, it's probably worth taking a few minutes to discuss the concept of object-oriented programming (OOP). Most programming languages today (C++, Java, Ruby, etc.) try to adhere to this model of coding and Python is no exception. Some of the older programming languages were developed before this coding model was popular and therefore don't adhere to it, but some have been updated attempting to comply with this model.

The image below shows the basic concept behind OOP. We have an object and that object has properties (attributes and states) and methods (something it does).

The idea behind OOP is to create a programming language that kind of acts like things in our real world. A car is an object that has properties (wheels, color, size, engine, windshield) and methods (it moves, doors open). From a the perspective of language, an object is a noun, a property is a adjective, and a method is generally a verb.

A car object with its methods.

Objects are a member of a class. For instance, our car is a member of the class of vehicles. In the image below, you can see that we have a class named "vehicle," a subclass "bike," and a sub-subclass "trike." The "motor" and "pedal" are properties of the bike.

Object-oriented objects inherit the characteristics of their class.

Variables

A variable points to data stored in a memory location. This memory location, in Python, can store different values such as integers, real numbers, strings, floating point numbers, Booleans, lists, and dictionaries.

In Python, each variable type is treated like a class. In the script below, I have attempted to demonstrate a few of them.

Let's create this script in any text editor. Then, let's save it as "secondpythonscript.py" and give ourselves permissions to execute it.

kali > chmod 755 secondpythonscript.py

When we run this script, it prints the value of the string variable (NullByteStringVariable), the integer variable (NullByteIntegerVariable), and and the floating point number variable (NullByteFloatingPointVariable).

Note: In Python, there is no need to declare a variable before assigning a value to it.

Functions

Python has a number of built-in functions that you can immediately import and use. Most of them are available on your default installation of Python in Kali Linux, although many more are available from the downloadable libraries. Let's take a look at a few of the thousands that are available to you.

  • exit() - exits from a program
  • float() - returns its argument as a floating point number
  • help() - displays help on the object specified by its argument
  • int() - returns the integer portion of its argument (truncates)
  • len() - returns the number of elements in a list or dictionary
  • max() - returns the maximum value from its argument (a list)
  • open() - opens the file in the mode specified by its arguments
  • range() - returns a list of integers between two values specified by its arguments
  • sorted() - takes a list as an argument and returns it with its elements in order
  • type() - returns the type of its argument (e.g., int, file, method, function)

Lists

In many programming and scripting languages, we have arrays. Arrays are great for storing a list of objects. Arrays are a list of various values that we can retrieve by referencing the particular value in the array by its position. So, for instance, if we wanted the third value in the array, we could use it by array[2]. Python works similarly, but this functionality is called a "list."

Lists in Python are referred to as being iterable. This means that the list can provide successive elements when we use a looping structure like a "for" statement (see Python 3).

So, let's imagine that we needed to display the fourth element in our list (NullByteList) from our script above. We can access that element and print it by calling the list name, NullByteList, followed by the number of the element we want to access enclosed with brackets. It's important to note that Python, like many other programming environments, assigns the numeral 0 to the first element in a list. For instance, in our list above, the first element is element 0. If we want element 0, we will get 1, if we want element 1 we will get 2, and so on.

To test this, let's add a line to our script to print element at position 3 in our NullByteList.

print NullByteList[3]

When we run this script again, we can see that the new print statement prints "4."

Networking with Python

To create a network connection in Python, we need to use the "socket" module. We learned in the previous Python tutorial that Python comes with a library of modules for a multitude of tasks. In this case, we will need the socket module to create a TCP connection.

First, we need to import the socket module (Line 3), then instantiate a new variable from the socket class (Line 7). We will call that new variable "s" here. We then need to use the connect() method (Line 8) to make a network connection to a particular IP and port.

Once we make the connection, there a number of things we can do. We can use the receive (recv) method to read 1024 bytes of data from the socket (Line 10) and store it in a variable named "answer"; we can print the contents of that variable (Line 11); and we close the connection (Line 13).

Let's save this script as "nullbytesocket" and then change its permissions using the chmod command so that you can execute it.

Let's run this script and connect to another Linux system to port 22. If SSH is running on that port, we should be able to read the banner into our "answer" variable and print it to the screen.

Essentially, we have created a simple banner grabbing script!

A Taste of Things to Come

As we explore and expand your capabilities in Python, we will be building a password cracker, port scanner, banner grabber, vulnerability tester, and exploits—all in Python.

Keep coming back, my fledgling hackers, as we further explore the hacker's scripting language of choice, Python.

Just updated your iPhone? You'll find new emoji, enhanced security, podcast transcripts, Apple Cash virtual numbers, and other useful features. There are even new additions hidden within Safari. Find out what's new and changed on your iPhone with the iOS 17.4 update.

Cover image via Shutterstock

18 Comments

I have started to learn python on codecademy. I'm wondering were you learned your coding?

Same here Anonymous. But Codecademy discusses only the basics. I'm looking for more. And I think this series would quench my thirst.

Late response....

Coding Ground by TutorialsPoint is my favorite. With over 100 languages and shells, it makes my #1.

Learn Python the hard way is a fantastic way to learn code to the point where you can teach yourself how to do the really advanced stuff. Theres also a section that teaches you how to use the terminal at the end of the book. Not everything is up to date but the stuff that is can be easily looked up.

I am having some trouble on 'import socket' - I keep getting the "TypeError: 'module' object is not callable"

Could it be possible that my path is screwed up? Any thoughts? I have installed because I can access in the command line python interpreter.

Thank you for your help!

pip install socket

The command above should work
And endeavor your add python to the environment variable.

Can you send a screenshot?

I realize I have the wrong ip and port - but it should still import socket right?

Thanks for all your help!

Your code looks good. Could you run the simple script above?

Yep - I could. I ran multiple scripts - no problem.

I can't see your screenshot anymore, but you named your file 'socket.py', am I right? That is most likely conflicting with your import. Change the name of your file to something that doesn't conflict with a python module, like 'mysockets.py' or something. Hope that works for you.

I really liked the simple explanation of the basic of OOP, and the banner script is great....

I'm learning Python too, maybe you can recommend some books for medium-advanced topics, I will keep an eye over here!!

great tutorial

I finished the basic of python but I still lost which modules will be useful for hacking ..any recommendation ? :)
-the modules that dealing with network but what else ?

thanks :)

Energywolf - that fixed it! Thank you everyone for your help.

Hi there!

Do you currently have any python scripts that could be adapted to perform a specific function (like killav.py or something similar).

I'm adding in python scripts to penetration tests on XP machines, but with little experience with Python, a bit of help may be needed.

Is this something you feel comfortable with helping me?

I don't know if I'm simply missing something or what but i changed the port number to 80 for HTTP but when i execute the script it just sits there idle like its doing nothing. Is there something I'm missing or does this only work with with SSH? Thanks

Daedalus:

First, is there a web server on the target system?

Second, grabbing the web server banner requires different commands.

OTW

Figured I was missing something like that. I'm trying to test the script on other ports because I don't have other Linux system with port 22 open but thanks for the info.

Share Your Thoughts

  • Hot
  • Latest