Proj 1: Basic Port Scanning with Python (NETLAB Version)

Purpose

Learn very basic Python networking techniques.

Use your Kali64 Machine

Open the Kali64 virtual machine. Log in as root with the password toor

This machine will perform the attack.

Making A Very Simple Banner Grabber

In Kali Linux, in a Terminal window, execute this command:
nano grab.py
This starts a very old, simple text editor named "nano". It's somewhat clumsy to use because it doesn't use the mouse. However, learning to use it is a good skill because cloud machines, and machines that have been exploited with hacking tools, often allow only text-based control.

In nano, enter this code, as shown below:

import socket
s = socket.socket()

s.connect(("attack.samsclass.info", 22))
print s.recv(1024)
s.close()

Save the file with Ctrl+X, Y, Enter.

Explanation

The first line imports the "socket" library, which contains networking functions.

The second line creates a socket object named "s".

The third line connects to the server "attack.samsclass.info" on port 22.

The fourth line receives data from the server and prints it, up to a maximum of 1024 characters.

The fifth line closes the connection.

Running the Grabber

In a Terminal window, execute this command:
python grab.py
You should see an SSH banner, as shown below (the version number will be different).

Adding a Timeout

Open the grab.py script in nano again.

Change the port number from 22 to 80, as shown below, and save the modified file.

Run the script again. There is no banner from an HTTP server, so it just freezes up, waiting for a banner. To stop the script, press Ctrl+C.

To make it timeout more quickly, add this line to your script, as shown below:

socket.setdefaulttimeout(2)

Run the script again. Now it times out, as shown below.

Using Variables

Execute this command to copy your script to a new script named grab2.py:
cp grab.py grab2.py
Modify grab2.py to use variables for the target and port, as shown below.

Save and run the script--it should time out in a few seconds, just as it did before.

Using User Input

Modify the program to input the target and port from the user, as shown below.

Save and run the script. Enter a URL and port to scan. The script halts with an error saying "TypeError: an integer is required".

To fix that, enclose the raw_input statement for tport in the int() function, as shown below.

Now the port scanner works. Use it to grab the port 22 banner again, as shown below.

Sources

Python Network Programming
17.2. socket -- Low-level networking interface
How can I make a time delay in Python?
Gotcha -- forgetting parentheses | Python Conquers The Universe



Revised for NETLAB 6-8-16

Last updated 6-16-16