Monday, April 21, 2025

Crafting Custom Ping in Python

import os

ip_dest = input("Enter IP addr to Check: ")
icmp_num = input("ICMP Echo Number: ")

os.system("ping -n {} {}".format(icmp_num, ip_dest))

This Python code demonstrates how to use the os module to execute a ping command and check the response from a specific IP address. Below is a detailed explanation of how the code works:

  1. First, the code prompts the user to enter the IP address to check and the number of ICMP echo requests to send to the target host.
  2. The os.system() function is then used to execute a ping command to the specified IP address with the number of ICMP echo requests specified by the user.
  3. The ping command sends ICMP echo requests to the specified IP address and waits for a response. If the target host responds, it sends an ICMP echo reply message back to the sender.
  4. The response from the ping command is then printed to the console. If the target host responds to the ICMP echo requests, the output will show the number of packets sent, received, lost, and the response time.
  5. If the target host does not respond to the ICMP echo requests, the output will show that all packets were lost.

In summary, this code demonstrates a simple way to check if a specific IP address is reachable on the network using ICMP echo requests.

Ping multiple IPs from list:

import os

ip_list = ['127.0.0.1', '192.168.0.103']

icmp_num = input("ICMP Echo Number: ")

for x in ip_list:
    os.system("ping -n {} {}".format(icmp_num, x))

This Python code is a simple script that allows the user to enter a list of IP addresses and an ICMP echo number, and then pings each IP address in the list using the specified number of ICMP echoes. Here's a step-by-step explanation of what the code does:

  1. The code imports the "os" module, which provides a way to interact with the operating system.

  2. The code creates a list called "ip_list" containing two IP addresses - '127.0.0.1' and '192.168.0.103'.

  3. The code prompts the user to enter an ICMP echo number using the "input()" function and stores the result in the variable "icmp_num".

  4. The code uses a "for" loop to iterate over each IP address in the "ip_list".

  5. Inside the loop, the code calls the "os.system()" function to execute the "ping" command with the specified number of ICMP echoes and IP address using string formatting.

  6. The output of each "ping" command is printed to the console.

  7. The loop repeats for each IP address in the "ip_list".

In summary, this code allows the user to quickly ping multiple IP addresses with a specified number of ICMP echoes, which can be useful for testing network connectivity or troubleshooting network issues.

How to Ping Multiple IP Addresses

import os, time

with open('ip-source.txt') as file:
    dump = file.read()
    dump = dump.splitlines()

    for ip in dump:
        print('Pinging now: ', ip)
        os.system('ping -n 4 {}'.format(ip))
        print('-' * 60)
        time.sleep(5)

This Python script uses the os and time modules to ping a list of IP addresses stored in a text file. The script performs the following actions:

  1. Opens the text file ip-source.txt using the open() function and reads its contents into a string variable dump.
  2. Splits the string dump into a list of IP addresses using the splitlines() method, and stores it in the same variable dump.
  3. Loops through each IP address in dump.
  4. Uses the os.system() function to execute the ping command for each IP address, with the -n option set to 4 to limit the number of ping requests to 4. This sends 4 ICMP packets to the IP address and waits for a response.
  5. Prints a message indicating which IP address is being pinged.
  6. Prints a line of dashes to separate each ping request for readability.
  7. Uses the time.sleep() function to pause the script for 5 seconds before pinging the next IP address.

This script is useful for network administrators who need to check the availability of multiple IP addresses in a network. It automates the process of pinging each IP address and prints the results to the console. By specifying a list of IP addresses in a text file, the script can be easily customized to suit specific network configurations.

IP Range - List Generator - Python

#Enter any IP from subnet, for example, 192.168.0.1

ip = input('Enter IP: ')
parts = ip.split('.')

print(parts)

a = '.'

start = int(input('Start num:'))
end = int(input('End num: '))

for x in range(start, end + 1):
    print(parts[0] + a + parts[1] + a + parts[2] + a + str(x))

  1. The code imports no external module.
  2. ip is a string that holds the value of the IP address entered by the user.
  3. parts is a list of four strings, where each string is obtained by splitting the ip string using the period character . as the delimiter.
  4. a is a string containing a period character.
  5. start and end are two integers that the user enters to specify the range of numbers to append to the IP address.
  6. The for loop iterates over the range of numbers from start to end (inclusive) and prints out the concatenation of the first three elements of parts separated by a, followed by the current number in the loop converted to a string.

Port Scanner in Python - How To

import socket

ip = '192.168.0.103'
port_list = [20, 80, 8080, 139, 445, 23, 21, 22]

for port in port_list:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    result = s.connect_ex((ip, port))
    if result == 0:
        print('-' * 60)
        print('Port: ', port, 'open')
        print('-' * 60)
    else:
        print('Port: ', port, 'closed')

  1. The first line imports the socket module.
  2. The second line sets the ip variable to '192.168.0.103'.
  3. The third line creates a list of ports to be scanned. The list contains 8 ports: 20, 80, 8080, 139, 445, 23, 21, and 22.
  4. The for loop iterates over each port in the port_list.
  5. For each port in the port_list, the following code is executed: a. A new socket is created using the socket.socket() method with the parameters socket.AF_INET and socket.SOCK_STREAM. b. The connect_ex() method is used to connect to the IP address ip and the current port. c. If the connect_ex() method returns 0, then the port is open and the following is printed:
    • A line of 60 hyphens (-)
    • The port number followed by the word "open"
    • Another line of 60 hyphens d. If the connect_ex() method returns anything other than 0, then the port is closed and the following is printed:
    • The port number followed by the word "closed".

Sunday, April 20, 2025

FTP Directory Listing with ftplib - Python

from ftplib import FTP

ftp = FTP('ftp.fi.debian.org')

print("FTP RootDir Listing")
print("Logging in.")

ftp.login()

print(ftp.retrlines('LIST'))

print('Closing FTP Connection')
ftp.close()

Here's a detailed explanation of the code:

  1. The code begins by importing the FTP module from the ftplib library, which provides a range of functions for working with FTP servers.
  2. The next line creates an FTP object and connects it to the server located at "ftp.fi.debian.org". This establishes a connection to the server so that we can send commands to it.
  3. The code then prints a message to indicate that the FTP root directory is being listed.
  4. A call to the login method is made to authenticate the user on the FTP server.
  5. The retrlines method is used to retrieve a listing of the files and directories in the root directory of the FTP server. This method sends the "LIST" command to the server and prints the response to the console.
  6. Finally, the FTP connection is closed using the close method.

Overall, this code retrieves a list of files and directories from an FTP server using Python's built-in FTP functionality.

How to Ping IP Address - Python

import os

os.system('cls')

print("#" * 60)
ip_to_check = input('IP to Check: ')

print('-' * 60)
os.system('ping {}'.format(ip_to_check))

print('-' * 60)

input('Press any Key to Exit')

This Python code demonstrates how to use the os module to clear the console and execute a ping command to check if an IP address is reachable.

First, the os.system() function is used to run the "cls" command on Windows, which clears the console screen to make it easier to read the output of the program. The # character is printed 60 times to create a visual divider before the user is prompted to input an IP address to check.

Once an IP address is entered, another divider made up of the - character is printed to separate the input from the output. The os.system() function is then used again to execute the ping command followed by the IP address entered by the user using Python's string formatting syntax. This will send ICMP packets to the specified IP address and display the result of the ping command.

Finally, another divider is printed, and the program pauses using the input() function until the user presses any key to exit the program.

Here's an explanation of the script step by step:

  1. import os: This imports the "os" module in Python, which provides a way of using operating system dependent functionality like reading or writing to the file system, starting or stopping processes, etc.

  2. os.system('cls'): This line clears the console screen (in Windows) before running the script, by calling the "system" method of the "os" module with the argument 'cls'. 'cls' is the command to clear the screen in Windows, and this line will only work in a Windows environment.

  3. print("#" * 60): This line prints a separator of 60 "#" symbols to visually separate the output of the different parts of the script.

  4. ip_to_check = input('IP to Check: '): This line prompts the user to input an IP address to check for availability. The input value is assigned to the "ip_to_check" variable.

  5. print('-' * 60): This line prints another separator of 60 "-" symbols to visually separate the previous input prompt from the output of the ping command.

  6. os.system('ping {}'.format(ip_to_check)): This line runs the "ping" command with the IP address entered by the user as the argument. The "ping" command sends an Internet Control Message Protocol (ICMP) echo request to the specified IP address and waits for a response. The output of the command is displayed in the console.

  7. print('-' * 60): This line prints another separator of 60 "-" symbols to visually separate the output of the ping command from the exit prompt.

  8. input('Press any Key to Exit'): This line waits for the user to press any key before exiting the script.

Split an IP Address into Four Parts - Python

ip = '192.168.5.5'

parts = ip.split('.')

part_0 = parts[0]
part_1 = parts[1]
part_2 = parts[2]
part_3 = parts[3]

print("-" * 60)

print('Part: 0', part_0)
print('Part: 1', part_1)
print('Part: 2', part_2)
print('Part: 3', part_3)

print("-" * 60)

sep = '.' 

for x in range(1, 256):
	print(part_0 + sep + part_1 + sep + part_2 + sep + part_3 + sep + str(x))

This code takes an IP address (in this case, 192.168.5.5) and splits it into its four parts (part_0, part_1, part_2, and part_3) using the "." character as a delimiter. It then prints each part on a separate line.

After that, it enters a loop that generates a list of IP addresses that have the same first three parts as the original IP address (192.168.5), but with the fourth part ranging from 1 to 255. These IP addresses are printed to the console, each on a separate line, using the same separator "." as before.

This code generates a list of IP addresses that can be used to scan a local network for connected devices.

Download a File From Public FTP Server - Python

import ftplib

path = '/debian/'
filename = 'README.html'

ftp = ftplib.FTP("ftp.fi.debian.org") 
ftp.login()
ftp.cwd(path)
ftp.retrlines('LIST')
ftp.retrbinary("RETR " + filename ,open(filename, 'wb').write)
ftp.quit()

This script uses the ftplib library to download a file named README.html from an FTP server located at 'ftp.fi.debian.org', within the /debian/ directory.

Here's what the code does:

  1. Imports the ftplib library.
  2. Sets the path variable to /debian/ and the filename variable to README.html.
  3. Creates an FTP object using the FTP constructor from the ftplib library, passing in the hostname ("ftp.fi.debian.org") as an argument.
  4. Calls the login() method of the ftp object to log in to the FTP server.
  5. Calls the cwd() method of the ftp object to change the current working directory to /debian/.
  6. Calls the retrlines() method of the ftp object to list the files in the current directory.
  7. Calls the retrbinary() method of the ftp object to download the README.html file in binary mode, using the open() function to create a file object for writing, and the write() method to write the downloaded data to the file.
  8. Calls the quit() method of the ftp object to disconnect from the FTP server.

After running this script, the README.html file will be downloaded and saved in the current working directory.

Simple HTTP Server with Python

import os
import http.server
import socketserver

os.chdir('c:\\Python37')

PORT = 80

Handler = http.server.SimpleHTTPRequestHandler

with socketserver.TCPServer(("192.168.0.103", PORT), Handler) as httpd:
    print("Serving files from: c:\Python37, on port: ", PORT)
    
    httpd.serve_forever()

This script creates a simple HTTP server that serves files from a specified directory on a specified port. Here's what the code does:

  1. Imports the os, http.server, and socketserver modules.
  2. Changes the current working directory to 'c:\\Python37' using the chdir() function from the os module.
  3. Sets the variable PORT to 80, which is the default port number for HTTP traffic.
  4. Defines a variable Handler to use the SimpleHTTPRequestHandler class from the http.server module.
  5. Uses the TCPServer class from the socketserver module to create an instance of a server, passing in a tuple of the IP address and port number as the first argument and the Handler variable as the second argument. This creates a TCP server that listens for incoming requests on the specified IP address and port number, and uses the specified Handler to handle each request.
  6. Prints a message to the console to indicate that the server is ready and listening for requests.
  7. Calls the serve_forever() method on the httpd object, which starts the server and listens for incoming requests indefinitely, until the server is shut down.

Once the server is running, any files in the 'c:\\Python37' directory can be accessed by navigating to the server's IP address in a web browser, using the port number specified in the script (in this case, 80).

TCP Port Checker - Check If Remote Port is Open and Listening

import socket
from datetime import datetime

#how to check if tcp port is active

ip = input('Target IP: ')
port_target = input("Port to check: ")

#time_start = datetime.now()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.setdefaulttimeout(1)
res = s.connect_ex((ip, int(port_target)))

if res == 0:
	print('Port Open')
else:
	print('Port Closed')

#time_stop = datetime.now()
#time_used = time_stop - time_start
#print('Done in:', time_used)

This script allows you to check whether a TCP port on a remote host is open or closed. Here is what the code does:

  1. Imports the socket module for socket programming, and datetime module for measuring the time taken to check the port.
  2. Prompts the user to enter the IP address of the target and the port number they want to check.
  3. Creates a socket object with the AF_INET family (IPv4) and SOCK_STREAM type (TCP protocol).
  4. Sets the default timeout for the socket object to 1 second.
  5. Calls the connect_ex() method on the socket object, passing in the target IP and port number as a tuple. The method returns an error code, which is stored in the variable res.
  6. Checks the value of res. If it is 0, then the port is open. Otherwise, the port is closed.
  7. Prints the result to the console.

Note that the script uses connect_ex() instead of connect(). The difference between the two is that connect() raises an exception if the connection fails, while connect_ex() returns an error code instead. In this case, using connect_ex() allows the script to handle connection failures more gracefully.

Sockets with Python - 5 - Two Way Chat

Source code in this tutorial is same as in last one. Just run 2 server scripts, at different port, and than change corresponding ports in client scripts. For example, for first server/client combo use port: 54321, and for other server/client use port 12345.

Note: If you use one PC, run scripts in 4 different terminals/IDLEs or you will run into IDLE clashes.

Sockets with Python - 4 - One Way Chat - Server to Client

Server Script

import socket 

msg = "Meeting at 14h, Office 279"

#Local IP Data

host = "192.168.0.103"
port = 54321
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Preparing for Connection

s.bind((host, port))

print("Server Listening")
s.listen(5)

conn, addr = s.accept()
print("Connection From: ", addr)
print("Sending Message: ")
conn.sendall(msg.encode())

while True:
    inp = input(">>")
    conn.sendall(inp.encode())
  1. import socket - This line imports the socket module, which is a built-in module in Python that provides low-level network communication functions.

  2. host = "192.168.0.103" - This line defines a string variable named host that stores the IP address of the remote host.

  3. port = 54321 - This line defines an integer variable named port that stores the port number to use for the connection.

  4. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - This line creates a new socket object named s using the socket module. The first argument, socket.AF_INET, specifies the address family to use (IPv4), and the second argument, socket.SOCK_STREAM, specifies the socket type to use (TCP).

  5. s.connect((host, port)) - This line connects the socket s to the remote host and port specified by host and port.

  6. while True: - This line starts an infinite loop.

  7. data_from_server = s.recv(1024) - This line receives data from the remote host through the socket s and stores it in the variable data_from_server. The argument 1024 specifies the maximum amount of data to be received at once.

  8. print("received: ", data_from_server.decode()) - This line prints the received data to the console. The decode() method is used to convert the bytes received into a string that can be printed.

The overall purpose of this script is to connect to a remote host at a specified IP address and port number, and then continuously receive data from the remote host and print it to the console.

Client Script

import socket

#Remote IP and port
host = "192.168.0.103"
port = 54321

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))

#Data from server

while True:
    data_from_server = s.recv(1024)
    print("received: ", data_from_server.decode())
  1. The script imports the socket module for networking functionality.
  2. The script defines two variables host and port that represent the remote IP address and port number to connect to.
  3. A new socket object is created with socket.socket(socket.AF_INET, socket.SOCK_STREAM) where AF_INET indicates IPv4 addressing and SOCK_STREAM indicates a TCP socket.
  4. The connect() method is called on the socket object with the host and port arguments to establish a connection to the server.
  5. The script enters an infinite loop using while True: to continuously receive data from the server.
  6. The recv() method of the socket object is called with a buffer size of 1024 bytes to receive data from the server.
  7. The received data is decoded from bytes to string using the decode() method.
  8. The received data is printed to the console using the print() function, along with the message "received: ".

Sockets with Python - 3 - Creating Simple Client

import socket

#Remote IP and port
host = "192.168.0.103"
port = 54321

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))

#Data from server

while True:
    data_from_server = s.recv(1024)
    print("received: ", data_from_server.decode())
	

This script uses the socket module in Python to establish a connection with a server and receive data from it. The socket module provides a low-level interface to network communication, allowing developers to send and receive data over various protocols, such as TCP, UDP, and others.

The first step is to define the remote IP and port to which the client will connect. In this case, the IP address is 192.168.0.103, and the port is 54321.

The script then creates a new socket using the socket.socket method and sets its address family to AF_INET (IPv4) and the socket type to SOCK_STREAM (TCP).

Next, the script establishes a connection to the remote server using the connect method of the socket object. This method takes as input a tuple containing the IP address and port number of the server.

After the connection is established, the client enters a loop where it continuously receives data from the server using the recv method of the socket object. The recv method takes as input the maximum number of bytes to be received at once.

Once the data is received, the script decodes it from bytes to a string using the decode method, and then prints it to the console using the print function.

The loop continues until the connection is closed, or an error occurs, at which point the script exits.

Sockets with Python - 2 - Sending Custom Headers

import socket 

msg = "Meeting at 14h, Office 279"

#Local IP Data

host = "192.168.0.103"
port = 54321

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Preparing for Connection")
s.bind((host, port))

print("Server Listening")
s.listen(5)

while True:
    conn, addr = s.accept()
    print("Connection From: ", addr)
    print("Sending Message: ")
    conn.sendall(msg.encode())
    conn.send(b"\r\n")
    conn.send(b"-----------------------")
    conn.send(b"\r\n")

This script creates a simple TCP server using the Python socket library. The server is set to listen on a specific IP address and port. When a client connects to the server, the server sends a message to the client.

The first three lines of the script define some variables: msg is the message that the server will send to clients, host is the IP address that the server will listen on, and port is the port number that the server will listen on.

The next line creates a new socket object using the socket.socket() method. The two arguments that are passed to this method specify that we are creating an IPv4 socket using the TCP protocol.

After creating the socket object, the script binds the socket to the host and port that we defined earlier using the s.bind() method.

Next, the script starts the server listening for incoming connections using the s.listen() method. The argument passed to this method specifies the maximum number of queued connections.

The next section of the script starts an infinite loop that will run until the server is stopped. Within the loop, the script waits for an incoming connection using the s.accept() method. When a connection is received, the method returns two values: a new socket object representing the connection, and the address of the client that made the connection.

Once a connection is established, the server sends the message defined in msg to the client using the conn.sendall() method. This method sends the message as a byte string, so the msg variable is first encoded using the encode() method.

Finally, the server sends a couple of newline characters and a line of dashes to the client to separate the message from any subsequent messages that might be sent. The conn.send() method is used to send these additional messages.

Sockets with Python - 1 - Creating Simple Server

import socket 

msg = "Meeting at 14h, Office 279"

#Local IP Data

host = "192.168.0.103"
port = 54321
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

print("Preparing for Connection")
s.bind((host, port))

print("Server Listening")
s.listen()

conn, addr = s.accept()
print("Connection From: ", addr)
print("Sending Message: ")
conn.sendall(msg.encode())

This script sets up a TCP server that listens on a specific IP address and port for incoming connections. Once a client establishes a connection, it sends a message to the client.

Here is a step-by-step explanation of the code:

  1. import socket: This line imports the socket module which provides a way to communicate over the internet using TCP/IP.

  2. msg = "Meeting at 14h, Office 279": This line sets the message that will be sent to the client when the connection is established.

  3. host = "192.168.0.103": This line sets the IP address of the server.

  4. port = 54321: This line sets the port number that the server will listen on.

  5. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM): This line creates a new socket object using the AF_INET address family (IPv4) and the SOCK_STREAM socket type (TCP).

  6. print("Preparing for Connection"): This line prints a message to the console to indicate that the server is preparing to start.

  7. s.bind((host, port)): This line binds the socket to the specified IP address and port number.

  8. print("Server Listening"): This line prints a message to the console to indicate that the server is now listening for incoming connections.

  9. s.listen(): This line sets the server to listen for incoming connections. The listen() method takes one argument which specifies the maximum number of queued connections (backlog) that the server will allow.

  10. conn, addr = s.accept(): This line waits for a client to connect to the server and accepts the connection. The accept() method returns a tuple containing a new socket object (conn) which can be used to send and receive data on the connection, and the address of the client (addr) which consists of the client's IP address and port number.

  11. print("Connection From: ", addr): This line prints the address of the client that has connected to the server.

  12. print("Sending Message: "): This line prints a message to the console to indicate that the server is about to send the message to the client.

  13. conn.sendall(msg.encode()): This line sends the message to the client using the sendall() method of the socket object (conn). The encode() method is used to convert the message string into bytes, which is required when sending data over the network.

Overall, this script sets up a simple TCP server that listens for incoming connections and sends a message to the client once the connection is established.

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...