Creating a ping program using Python in Kali Linux

We will a create simple ping program using Python in Kali Linux. Asking user to enter any IP address and pinging to that IP address to check reachability and displaying the result.

First of all, open Linux terminal and type nano followed by name of the file.

Our file name is ping_host.py

root@kali:~# nano ping_host.py

Now entering Python3 commands after moving into nano editor.

Importing OS module so that we can be able to run operating system commands, such as we use ping command from terminal in Kali Linux to know whether host is alive.

import os

Asking user to enter IP Address using input() function

host =  input('Please enter IP address : ')

Creating below variable and assigning complete command to it.

cmd = 'ping -c 1 ' + host

-c is the number of count. We are sending only single ICMP packet to destination.

Now using os.popen() function. This function takes OS command as the argument. We will be submitting Kali Linux terminal command which is assigned to cmd variable and using result variable to store the output. Below is the command.

result = os.popen(cmd)

Using for loop to print each line of result variable.

for line in result.readlines():
        print(line)

Saving and exiting the editor.

Using below command at the terminal to run the file ping_host.py

root@kali:~# python3 ping_host.py

Below is the output.

Please enter IP Address : 192.168.56.100
PING 192.168.56.100 (192.168.56.100) 56(84) bytes of data.
64 bytes from 192.168.56.100: icmp_seq=1 ttl=255 time=0.247 ms
--- 192.168.56.100 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.247/0.247/0.247/0.000 ms
Below is the output if we try to ping ip which is not reachable to our Kali Linux
Please enter IP Address : 1.1.1.1
ping: connect: Network is unreachable

 

 

 

Leave a Reply

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 )

Google photo

You are commenting using your Google 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