Finding whether services are open for target using ports specified in a list

In the previous blog, we have created a program that scan target machine for open ports. Used for loop and specified range from 1 to 100

Now we will specify ports using list and then scanning to determine whether ports are open or not.

Import socket module

import socket

Importing time module for setting timeout value on socket connection

import time

Specify target machine

target = '1.1.1.1'

Create a list for ports. Here, we have created a list of 5 ports

port_list = [21,22,23,53,80]

Using for loop and specified which port are to be scan

for p in port_list:

Creating a socket and setting timeout for socket connection to 1 second

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
socket.setdefaulttimeout(1)

Using function socket.connect_ex() and assigning output of this function to result variable

result = s.connect_ex((target,p))

If the result is zero, print port is open otherwise print port is close

if result == 0:
print('Port {} is open'.format(p))
else:
print('Port {} is close'.format(p))

Close the socket connection

s.close()

Output

Port 21 is close
Port 22 is close
Port 23 is close
Port 53 is open
Port 80 is open

Complete Code

import socket
import time

target = '1.1.1.1'
port_list = [21,22,23,53,80]
for p in port_list:
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    socket.setdefaulttimeout(1)
    result = s.connect_ex((target,p))
    if result == 0:
        print('Port {} is open'.format(p))
    else:
        print('Port {} is close'.format(p))
    s.close()

Advertisement

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s