Share
Explore

Python Network Programming

How to Deliver this Work:

Include these exercises into your Project Presentation Document
Paste screen shots showing the performance of each activity.
Create a TEXT FILE named as Student_Name_StudentID.txt
Into this file: Put the edit URL to your Latex Document.
Upload Instructions will be Provided.

Learning Outcomes:

Develop a deep understanding of networking concepts and Python programming.
Make a Project Directory C:\pythonCiscoLab
Your hand in for this activity is to do these 10 Activities:

### Beginner Level: Python Basics
1. **Hello World** - Objective: Write a simple Python program that prints "Hello, World!" to the console. - Concepts: Basic syntax, print function.
2. **Variables and Data Types** - Objective: Create variables of different data types and print their values. - Concepts: Variables, data types (int, float, string, bool).
3. **Control Structures** - Objective: Write a Python script that makes decisions based on user input. - Concepts: if-else statements, user input.
4. **Loops** - Objective: Create a program that uses loops to perform repeated tasks. - Concepts: for loops, while loops.

Let's create a Python program that combines all these elements. We'll start with a basic "Hello World", then introduce variables of different data types, incorporate user input with control structures, and finally add a loop to repeat a certain task based on the user's choice. Here's the program:

```python # 1. Hello World print("Hello, World!")
# 2. Variables and Data Types my_integer = 10 my_float = 3.14 my_string = "Python is fun" my_bool = True

**— Extend this to OUTPUT to the Terminal the values of the Variables

# Print the variables print("Integer:", my_integer) print("Float:", my_float) print("String:", my_string) print("Boolean:", my_bool)
# 3. Control Structures user_input = input("Enter 'yes' to see a magic number or 'no' to exit: ").lower()
if user_input == 'yes': print("Here's a magic number:", my_integer + my_float) elif user_input == 'no': print("Goodbye!") else: print("Invalid input.")
# 4. Loops while user_input != 'no': user_input = input("Want to see the magic number again? Enter 'yes' or 'no': ").lower() if user_input == 'yes': print("Magic number is still:", my_integer + my_float) elif user_input == 'no': print("Alright, exiting now. Goodbye!") else: print("Invalid input, please type 'yes' or 'no'.") ```
This program starts by printing "Hello, World!", then declares and prints variables of different types. It asks the user for input to either display a "magic number" (a simple operation involving an integer and a float) or exit the program. If the user chooses to see the magic number, the program enters a loop where it repeatedly asks the user if they want to see the number again until they type 'no'.

# Python program themed on "Cat in the Hat" with strings representing CATS and Array with slots for hats

# 1. Define the Cat in the Hat cat_in_the_hat = "The Cat in the Hat"
# 2. Create an array with slots for hats hat_slots = [None] * 10 # Assuming there are 10 slots for hats
# 3. Display the header print("--- Welcome to the Cat in the Hat Program! ---\n")
# 4. Display the name of the cat print(f"Meet {cat_in_the_hat}!")
# 5. Check if the cat has any hats if any(hat_slots): print("The cat has some hats!") else: print("The cat has no hats.")
# 6. Let's add some hats to the array hat_slots[0] = "Red and White Striped Hat" hat_slots[1] = "Blue and White Striped Hat"
# 7. Display the hats the cat has print("\nThe cat's hats:") for index, hat in enumerate(hat_slots): if hat: print(f"Slot {index + 1}: {hat}")
# 8. Say goodbye to the cat print("\nGoodbye, Cat in the Hat!") ```
In this Python program, I've represented the Cat in the Hat using a string and created an array with slots for hats. The program checks if the cat has any hats, adds some hats to the array, displays the hats the cat has, and then bids farewell to the cat.
image.png
5. Functions and OBJECTS - Objective: Write a Python function that performs a simple calculation and returns the result. - Concepts: Function definition, return statement.
In Python, OBJECTS are boxes which contain (bind together) data variables and functions:

Craft a Python program that illustrates the use of functions and classes, with a networking theme. In this example, let's create a simple simulation of a network device and a function to connect to it. We'll have a NetworkDevice class representing a network device, and a function connect_to_device that simulates establishing a connection to the device.

class NetworkDevice:
def __init__(self, ip_address, device_type):
self.ip_address = ip_address
self.device_type = device_type

def get_details(self):
return f"Device Type: {self.device_type}, IP Address: {self.ip_address}"

def connect_to_device(device):
print(f"Attempting to connect to {device.device_type} at {device.ip_address}...")
# Simulate connection logic
is_connected = True # In a real scenario, this would involve more complex logic
if is_connected:
print(f"Successfully connected to {device.ip_address}!")
else:
print(f"Failed to connect to {device.ip_address}.")

# Creating instances of NetworkDevice
router = NetworkDevice("192.168.1.1", "Router")
switch = NetworkDevice("192.168.1.2", "Switch")

# Displaying device details
print(router.get_details())
print(switch.get_details())

# Connecting to devices
connect_to_device(router)
connect_to_device(switch)

In this program:
The NetworkDevice class represents a network device, with properties like ip_address and device_type.
The get_details method in the NetworkDevice class returns a string with the device details.
The connect_to_device function simulates the action of connecting to a network device. It prints messages indicating the attempt and result of the connection.
This example is a basic demonstration of how classes and functions can be used to represent and interact with objects in a program, here tailored around a networking theme. Remember, in real-world applications, connecting to network devices involves more sophisticated mechanisms including handling authentication, encryption, error checking, and network protocols.

Let's create an object-oriented Python program that simulates the behavior and interactions with a Cisco router. We'll define a class `CiscoRouter` that includes methods for various router operations like displaying the configuration, changing the hostname, and handling network interfaces. Keep in mind this is a simulation, and real router interactions involve more detailed and complex operations.

```python class CiscoRouter: def __init__(self, hostname, interfaces): self.hostname = hostname self.interfaces = interfaces # interfaces as a dictionary, e.g., {"GigabitEthernet0/0": "192.168.1.1"}
def display_config(self): print(f"Hostname: {self.hostname}") for interface, ip in self.interfaces.items(): print(f"Interface {interface} - IP Address: {ip}")
def change_hostname(self, new_hostname): self.hostname = new_hostname print(f"Hostname changed to {self.hostname}")
def configure_interface(self, interface_name, ip_address): self.interfaces[interface_name] = ip_address print(f"Configured {interface_name} with IP address {ip_address}")
def show_interfaces(self): print("Interface Status:") for interface in self.interfaces: print(f"{interface} - up")
# Example Usage router = CiscoRouter("Router1", {"GigabitEthernet0/0": "192.168.1.1"})
# Displaying current configuration router.display_config()
# Changing hostname router.change_hostname("Router2")
# Adding a new interface router.configure_interface("GigabitEthernet0/1", "192.168.1.2")
# Displaying interface status router.show_interfaces() ```
In this program: - The `CiscoRouter` class represents a Cisco router. - The `display_config` method prints the current configuration of the router. - The `change_hostname` method allows changing the router's hostname. - The `configure_interface` method adds or updates an interface's IP address. - The `show_interfaces` method simulates displaying the status of the interfaces (here, they are simply shown as 'up').
This is a basic and conceptual simulation intended for learning purposes. In real-world scenarios, managing a Cisco router involves interacting with the router's firmware through CLI commands or network management software, dealing with more complex configurations, security considerations, and protocol handling.

Create an object-oriented Python program to simulate a networking environment for teaching IP addressing, routing, and subnetting concepts, akin to Cisco Packet Tracer.

Our initial program will be a simplified version, focusing on basic concepts. We'll create classes for `NetworkDevice`, `Router`, and a `NetworkSimulation` class to manage the simulation environment. The simulation will allow users to create devices, set up IP addresses, and display routing information.

```python class NetworkDevice: def __init__(self, name): self.name = name self.ip_address = None
def set_ip_address(self, ip): self.ip_address = ip
def get_details(self): return f"{self.name} - IP: {self.ip_address}"
class Router(NetworkDevice): def __init__(self, name): super().__init__(name) self.routing_table = []
def add_route(self, network, mask, gateway): self.routing_table.append({'network': network, 'mask': mask, 'gateway': gateway})
def display_routing_table(self): print(f"Routing Table for {self.name}:") for route in self.routing_table: print(f"Network: {route['network']}, Mask: {route['mask']}, Gateway: {route['gateway']}")
class NetworkSimulation: def __init__(self): self.devices = []
def add_device(self, device): self.devices.append(device)
def display_network(self): for device in self.devices: print(device.get_details())
# Simulation example simulation = NetworkSimulation()
# Creating routers router1 = Router("Router1") router1.set_ip_address("192.168.1.1") router1.add_route("192.168.2.0", "255.255.255.0", "192.168.1.2")
router2 = Router("Router2") router2.set_ip_address("192.168.1.2") router2.add_route("192.168.1.0", "255.255.255.0", "192.168.1.1")
# Adding devices to simulation simulation.add_device(router1) simulation.add_device(router2)
# Displaying network setup simulation.display_network()
# Displaying routing tables router1.display_routing_table() router2.display_routing_table() ```
In this program: - `NetworkDevice` is a base class for network devices with basic attributes like `name` and `ip_address`. - `Router` is a subclass of `NetworkDevice`, adding routing functionality with a routing table. - `NetworkSimulation` manages the network environment, allowing addition of devices and displaying their details.
This code provides a foundational structure. For a real educational tool, you would need to expand this significantly with more detailed simulations of networking behavior, error handling, user interactions, and graphical representations, much like Cisco Packet Tracer.

Intermediate Level: Networking Basics in Python

6. **Basic Socket Programming**

- Objective: Create a simple client-server program using Python's `socket` module. - Concepts: TCP/IP basics, client-server model, sockets.

Create an object-oriented Python program for basic socket programming. This program will consist of a simple client-server architecture where the server listens for incoming connections and the client can connect to the server. Both client and server will be implemented as classes.

Note that you will run each class in its own Python Runtime Environment:
### Server Class
```python import socket import threading
class Server: def __init__(self, host='127.0.0.1', port=65432): self.host = host self.port = port self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.bind((self.host, self.port))
def listen_for_connections(self): self.socket.listen() print(f"Server listening on {self.host}:{self.port}") while True: conn, addr = self.socket.accept() threading.Thread(target=self.handle_client, args=(conn, addr)).start()
def handle_client(self, connection, address): print(f"Connected by {address}") while True: data = connection.recv(1024) if not data: break connection.sendall(data) connection.close()
def start(self): threading.Thread(target=self.listen_for_connections).start() ```
### Client Class
```python class Client: def __init__(self, host='127.0.0.1', port=65432): self.host = host self.port = port self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def connect_to_server(self): self.socket.connect((self.host, self.port)) print(f"Connected to server on {self.host}:{self.port}")
def send_data(self, message): self.socket.sendall(message.encode()) data = self.socket.recv(1024) print(f"Received from server: {data.decode()}")
def close_connection(self): self.socket.close() ```
### Running the Server and Client
To use these classes, you would run the server in one Python instance/script and the client in another.
#### Server script:
```python server = Server() server.start() ```
#### Client script:
```python client = Client() client.connect_to_server() client.send_data("Hello, Server!") client.close_connection() ```
This program demonstrates a basic client-server model using Python's `socket` module. The server listens for connections and echoes back any data it receives. The client connects to the server, sends a message, and prints the response.
Note: - Multithreading is used in the server to handle multiple client connections. - This is a basic example for educational purposes. Real-world applications would need more robust error handling and potentially more complex communication protocols.

7. **HTTP Requests**

- Objective: Write a Python script that makes
HTTP requests and processes responses.
- Concepts: HTTP protocol, `requests` module.

Create two Python classes, `HTTPServer` and `HTTPClient`,

which demonstrate basic HTTP request and response handling.

The server PYTHON PROGRAM will respond with a simple HTML page

The client will make GET requests to the server.

To enhance the learning experience, both classes will provide detailed output to help students understand and visualize the network activity.

We will use Python's built-in `http.server` module for the server and the `requests` module for the client.

First, let's install the `requests` module if you haven't already:
```bash ​pip install requests ```
### HTTPServer Class
```python from http.server import BaseHTTPRequestHandler, HTTPServer import threading
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header('Content-Type', 'text/html') self.end_headers() self.wfile.write(b"<html><body><h1>Hello, World!</h1></body></html>") print(f"Handled GET request from {self.client_address}")
class HTTPServer: def __init__(self, host='localhost', port=8000): self.server_address = (host, port)
def start(self): httpd = HTTPServer(self.server_address, SimpleHTTPRequestHandler) print(f"Starting HTTP server on {self.server_address[0]}:{self.server_address[1]}") threading.Thread(target=httpd.serve_forever).start() ```
### HTTPClient Class
```python import requests
class HTTPClient: def __init__(self, url): self.url = url
def send_get_request(self): print(f"Sending GET request to {self.url}") response = requests.get(self.url) print("Received Response:") print("Status Code:", response.status_code) print("Response Headers:", response.headers) print("Response Body:", response.text) ```
### Usage
#### Server Side
Run this script to start the server:
```python server = HTTPServer() server.start() ```
#### Client Side
Run this script to send a request:
```python client = HTTPClient('http://localhost:8000') client.send_get_request() ```
In this setup, the `HTTPServer` class starts a simple HTTP server that listens for incoming GET requests and responds with a basic HTML page. The `HTTPClient` class makes a GET request to the specified URL and prints the status code, headers, and body of the response.
This exercise is educational and helps students understand the basics of HTTP requests and responses. In real-world scenarios, the server would be more complex, handling various HTTP methods, serving different resources, and potentially involving middleware and routing logic.

image.png
8. **Working with JSON** - Objective: Fetch JSON data from an API and parse it in Python. - Concepts: JSON, API interaction.
### Advanced Level: Deep Dive into Networking with Python
9. **Building a Simple Web Server** - Objective: Implement a basic web server that can handle HTTP requests. - Concepts: HTTP server, handling GET and POST requests.
10. **TCP/IP Socket Programming** - Objective: Create a more complex client-server application using TCP/IP protocols. - Concepts: TCP/IP stack, data streaming.
11. **UDP Socket Programming** - Objective: Build a simple application that communicates using the UDP protocol. - Concepts: UDP, datagrams.
### Expert Level: Network Interface and Packet Analysis
12. **Network Interface Interaction** - Objective: Write a Python script to list all network interfaces on the machine. - Concepts: `socket` and `os` modules, network configuration.
13. **Raw Socket Programming** - Objective: Create a program that uses raw sockets to send and receive data. - Concepts: Raw sockets, packet crafting.
14. **Packet Sniffing** - Objective: Develop a script that captures and analyzes network packets. - Concepts: Packet sniffing, `pcapy` or `scapy` libraries.
15. **TCP Frame Analysis** - Objective: Write a program to capture TCP frames and dissect their components. - Concepts: TCP frame structure, packet analysis.
Throughout this journey, it's crucial to have a solid understanding of Python programming and networking concepts. Each level builds upon the last, so make sure to grasp each topic thoroughly before proceeding to the next. This progression will not only improve your Python skills but also deepen your understanding of how networks and protocols operate at a low level.
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.