Python program to get the OS information, Active Ports and Public and Private IP address in Linux

  • Display OS information using Python script.

Python being one of the easiest way to learn programming it has various features longing from use cases in Data structures programming to automation.

Python provides various modules and one of module “platform” can be used to access the underlying platform’s data, such as, hardware, operating system, and interpreter version information.

To Display information about underlying operating system following script can be used:


#code starts here
import platform
osType=platform.system()
print("OS TYPE: " + osType)
osInfo=platform.linux_distribution()
print("Distribution name: " + osInfo[0])
print("OS Version: " + osInfo[1])
print("OS Version Codename(ID): " +osInfo[2])
#code ends here

Insights of the above code:
platform is a module supported by python to access the underlying platform’s data.

platform.system() returns the type of the underlying operating system.

platform.linux_distribution() returns a tuple with default arguments (Distribution_name, version, id)

 

  • View active ports.

Python sports module named “os” which delivers the operating system functionalities. This module can be use to execute commands through python.

This module can be use to view active ports by executing netstat command which is a tool to display network connections information such as Transmission Control  displays, routing tables, number of interface and network protocol statistics.

#Code starts here:
import os
print("All Listening Ports: ")
os.system("netstat -lntu")
#code ends here

import os : Importing os module in the script.

os.system(“netstat  –lntu”) : os.system(“command to execute”) is used to run command passed as parameter.

netstat  –lntu : using netstat tool to view all the active ports and lntu is multiple argument for netstat command.  –l is used to listen –n is used to display all addresses and port numbers in numerical form –t is for TCP connections and –u is for UDP connections.

 

  • View public and private IP address of the system.

The Public and Private IP of the system can be viewed using hostname command and using public server the public IP can be determined. Following is the script to display Private and Public IP of the system:

#code starts here
import os
print("Private IP: ")
os.system("hostname -I")
print("Public IP: ")
os.system("curl bot.whatismyipaddress.com")
#code ends here

os.system(“hostname  –I”) : hostname –I displays all network address of the system.

os.system(“curl bot.whatismyipaddress.com”) : ("curl bot.whatismyipaddress.com") curl is a tool to transfer data from or to a server using various portocols such as HTTP or HTTPS. This returns the public IP of the system.

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: