In this article, I will show you how to create the simplest Port Scanner in Python. The program will use 2 very popular libraries: socket and sys. If you don’t know what python is, you can read it Python knowledge lesson for newbies Learn the basics of python quickly. In this article, we will write a program to scan network ports to see which ports are open using python
Join the channel Telegram of the AnonyViet 👉 Link 👈 |
Sockets Library
This is one of the standard libraries used for low level network interaction. The socket() function returns a socket object with various socket system calls. Parameter types are somewhat more flexible in the C interface.
Basic Functions
Some of the basic functions that we will use throughout this article will have the following functions:
socket.gethostbyname
: Gets the website domain name from the user and returns the host’s IP. Eg:
>>> import socket >>> socket.gethostbyname("www.google.com") '216.58.199.132'
OOP function
socket.socket (AF_INET, SOCK_STREAM)
: This is an OOP function class, which means you need to provide objects (data) for the class to process.
Eg:
>>> from sockets import * >>>s = socket(AF_INET, SOCK_STREAM)
s.connect (host, port)
:s is a variable used to call classes in the socket library. This command will connect to the specified server’s port. Eg:
>>> from socket import * >>> s = socket(AF_INET, SOCK_STREAM) >>> s.connect(('216.58.199.132',80))
s.recv
: This command will receive data from the server.
Create Port Scanner in Python
Apply the above knowledge to create port scanner:
from socket import * def port_scan(host, port): s = socket(AF_INET, SOCK_STREAM) # Thiết lập giao thức TCP try: # Exception Handling s.connect((host, port)) # Kết nối với port print("[+] {} port is open".format(port)) except: # If connection fails print("[+] Port is closed")
How it works
First the program will import all the functions/classes from the library socket. def port_scan function definition port_scan and it has two parameters host and portthen the program will set up the TCP protocol and try….except will handle error/exception cases. s.connect will try to connect to the server port.
Optimize the code for the 1st time
Save the file as port_scan.py
from socket import * def port_scan(host, port): s = socket(AF_INET, SOCK_STREAM) # Thiết lập giao thức TCP try: # Exception Handling s.connect((host, port)) # Kết nối với port print("[+] {} port is open".format(port)) except: # If connection fails print("[+] Error Occured") def main(): host = input("Enter Host: ") port = input("Enter Port: ") port_scan(host, port) # Gọi hàm port_scan if __name__ == '__main__': main()
We added the main function to ask the user for input host and port then will call the function port_scan. Jaw port_scan will execute the commands contained in the function.
Optimize the code for the 2nd time
Now, I will show you how to add parameters in terminal and scan various ports.
from socket import * import sys def port_scan(host): for i in range(1, 1025): s = socket(AF_INET, SOCK_STREAM)# Thiết lập giao thức TCP res = s.connect_ex((str(host), i)) if res == 0: # Nếu kết nối thành công print("Port {} is open.".format((i))) s.close() # Đóng kết nối if __name__ == '__main__': port_scan(sys.argv[1])
How it works
Same as above but it has command s.connec_ex
new, like s.connect
but it gives the result as a number, for example 1 means an error has occurred and 0 means success. The first two lines are import sockets
and sys
. Then we will scan from port number 1 to port 1024. After scanning 1 port, we have to close the connection because it will create a socket associated with the server.
Note: I import sys to read the parameters on the terminal with sys.argv [1] because 1 is the location of the server.
How to use file port_scan.py
Now, run the port_scan file and remember to add the host ip parameter. The host ip is the ip of the machine you are using.
robin@oracle:/Projects$ python3 port_scan.py 192.168.43.172 Port 22 is open.
So you have successfully created a port scanner using python. Alternatively, you can also create a Keylogger using python here.