Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
How to Capture udp Packets in Python
Next article icon

How to Get Open Port Banner in Python

Last Updated : 03 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will see how to Get Open Port Banner in Python. Here we will discuss 

What is Port?

Port is a terminology used on computer networks. You might know, that whenever you connect to the internet, your system or any device to which you are connecting is assigned an IP address.  So, when you search for something on the internet, your IP address is sent to the server where your page or response resides. After getting a request, the server sends back the desired page to your system. Now, suppose you have opened various tabs and gone to different websites, like YouTube or chrome or Amazon or any website. Then here, how the computer knows which request is for which tab, this is done with the help of a port number.  Ports are nothing but logical entities used for our system to make connections with the network. There are port ranges and each port functions for a particular work. The port ranges from 1 to 65535. The ports range from 49152 to 65535 and are used by client browsers. So, when you request something on the network, a port number between 49152 and 65535 is assigned and that is unique. This port number can be reassigned again, once the session is closed.

What is Banner? 

Banner is the description that the server returns. It contains a description of the host system like software type, system version, etc. This banner must be kept hidden as attackers or hackers can use this banner to attack by exploiting any loop while using the system description. And banner grabbing is nothing but getting the banner on a system on the network and banner grabbing is a crime if practiced without required permission.

What is Open Port?

Ports are open and closed. If a port is not open, we won’t be able to make a connection between two systems. So, when we do any activity on the network, the required ports are open and, as a result, we get the response in our system. Now, after discussing these three keywords, you will be able to understand what we are actually trying to do. To get an open port banner we will use a socket module. The socket is a way of connecting two nodes on a network to communicate with each other. One node listens on a particular port at an IP, while the other socket reaches out to the other to form a connection. The server forms the listener socket while the client reaches out to the server. 

Example 1

First, let’s see how we can see which ports are open for our system for that we are using threading for fast computation. We can get the IP address of the localhost by passing the host variable to the gethostbyname() function of the socket module. Here AF_INET specifies the IP address is IPV4(Internet Protocol version 4) and SOCKET_STREAM  specifies it's a TCP socket.  Next, we have set the status=False, which will be true whenever we make a connection. connect() function is used to make connections between host_ip and port. 

Python3
import socket import threading import time  # function to scan ports and see which ports are open def scan_port(port):     # we will check port of localhost     host = "localhost"     host_ip = socket.gethostbyname(host)          # print("host_ip = {}".format(host_ip))     status = False      # create instance of socket     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)      # connecting the host ip address and port     try:         s.connect((host_ip, port))         status = True     except:         status = False      if status:         print("port {} is open".format(port))   start_time = time.time()  for i in range(0, 100000):     thread = threading.Thread(target=scan_port, args=[i])     thread.start()  end_time = time.time() print("To all scan all ports it took {} seconds".format(end_time-start_time)) 
How to Get Open Port Banner in Python
 

Example 2

Here you can see we have added s.recv(1024).decode(). This means the socket will return the banner in 1024 bytes of buffer size and then we decode it to a string. Now to get banners on these open ports, we need to add just one more line after making the connection, banner = s.recv(1024).decode().

Python3
import socket import threading import time  def scan_port(port):     try:         host = "localhost"         host_ip = socket.gethostbyname(host)         status = False          # create instance of socket         s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)          # connecting the host ip address and port         s.connect((host_ip, port))         try:             banner = s.recv(1024).decode()             print("port {} is open with banner {}".format(port, banner))          except:             print("port {} is open ".format(port))      except:         pass   start_time = time.time()  for i in range(0, 100000):     thread = threading.Thread(target=scan_port, args=[i])     thread.start()  end_time = time.time() print("To scan all ports it took {} seconds".format(end_time-start_time)) 

Output:

How to Get Open Port Banner in Python
We can see that port 22 is open with its banner information.

Next Article
How to Capture udp Packets in Python

P

preetimurmu8967
Improve
Article Tags :
  • Python
Practice Tags :
  • python

Similar Reads

  • How to Capture udp Packets in Python
    Capturing UDP (User Datagram Protocol) packets is a fundamental skill for network programmers and security enthusiasts. Python, being a versatile and powerful programming language, offers various libraries and tools to facilitate packet capture. In this article, we'll explore how to capture UDP pack
    3 min read
  • Python PIL | Image.open() method
    PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files,
    3 min read
  • How to check if an application is open in Python?
    This article is about How to check if an application is open in a system using Python. You can also refer to the article Python – Get list of running processes for further information. In the below approaches, we will be checking if chrome.exe is open in our system or not. Using psutil The psutil is
    2 min read
  • Get OS name and version in Python
    Python programming has several modules that can be used to retrieve information about the current operating system and the version that is running on the system. In this article we will explore How to get the OS name and version in Python. Let us see a simple example to get the OS name and version i
    2 min read
  • How to Check Open Ports Using CMD in Windows?
    Open ports on your Windows computer act like doors for data-letting information in and out. While necessary for apps and services, unprotected ports can become security risks. Checking which ports are open helps you spot vulnerabilities, fix connection issues, and keep your system safe. Using Comman
    5 min read
  • How to open an image from the URL in PIL?
    In this article, we will learn How to open an image from the URL using the PIL module in python. For the opening of the image from a URL in Python, we need two Packages urllib and Pillow(PIL). Approach:Install the required libraries and then import them. To install use the following commands:pip ins
    1 min read
  • How to Open URL in Firefox Browser from Python Application?
    In this article, we'll look at how to use a Python application to access a URL in the Firefox browser.  To do so, we'll use the webbrowser Python module. We don't have to install it because it comes pre-installed. There are also a variety of browsers pre-defined in this module, and for this article,
    2 min read
  • Python | os.openpty() method
    OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.openpty() method in Python is used to open a new pseudo-terminal pair. This me
    1 min read
  • How to Install and use SSL Certificate In Python
    A secure Socket Layer (SSL) Certificate is a Digital certificate that can be used for the authentication of a website and it helps to establish an encrypted connection between the user and server. SSL is a secure layer that creates an encrypted link between a web server and a web browser. SSL keeps
    2 min read
  • Telnet with ipaddress and port in Python
    Telnet is a protocol that allows you to connect to a remote computer and execute commands. Python provides a built-in module called "telnetlib" that enables us to use Telnet in our code. What is Telnet in Python?Telnet clients let you connect to other Telnet Servers. You cannot connect to your own s
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences