Python network programming
Python network programming
python
import requests
from bs4 import BeautifulSoup
import json
# Get rating
rating_class = book.p['class'][1]
rating_dict = {
'One': 1,
'Two': 2,
'Three': 3,
'Four': 4,
'Five': 5
}
rating = rating_dict.get(rating_class, 0)
# Get price
price = book.find('p', class_='price_color').text.strip()
json
[
{
"name": "A Light in the Attic",
"rating": 3,
"price": "£51.77"
},
{
"name": "Tipping the Velvet",
"rating": 1,
"price": "£53.74"
},
// ... more books ...
]
To run this script, you'll need to have the following packages installed:
bash
Would you like me to modify the script to scrape all pages of the website?
I'll help you create a simple network topology with multiple devices and provide a Python script using
Netmiko to automate their configuration. For this example, we'll create a topology with one Layer 3
router and two Layer 2 switches connected together.
Network Topology:
python
# Configuration templates
router_config = [
'hostname R1',
'interface GigabitEthernet0/0',
'ip address 192.168.1.1 255.255.255.0',
'no shutdown',
'exit',
'ip routing',
'router ospf 1',
'network 192.168.1.0 0.0.0.255 area 0'
]
switch1_config = [
'hostname SW1',
'interface GigabitEthernet0/0',
'no switchport',
'ip address 192.168.1.2 255.255.255.0',
'no shutdown',
'exit',
'vlan 10',
'name SALES',
'exit',
'vlan 20',
'name ENGINEERING',
'exit',
'interface GigabitEthernet0/1',
'switchport mode trunk',
'switchport trunk allowed vlan 10,20',
'no shutdown'
]
switch2_config = [
'hostname SW2',
'interface GigabitEthernet0/0',
'no switchport',
'ip address 192.168.1.3 255.255.255.0',
'no shutdown',
'exit',
'vlan 10',
'name SALES',
'exit',
'vlan 20',
'name ENGINEERING',
'exit',
'interface GigabitEthernet0/1',
'switchport mode trunk',
'switchport trunk allowed vlan 10,20',
'no shutdown'
]
print(f"Configuring {device['device_name']}...")
output = connection.send_config_set(config_commands)
print(f"Configuration output for {device['device_name']}:\n{output}")
# Save configuration
connection.send_command('write memory')
print(f"Configuration saved on {device['device_name']}")
# Verify IP configuration
ip_output = connection.send_command('show ip interface brief')
print(f"IP Interface Status for {device['device_name']}:\n{ip_output}")
connection.disconnect()
print(f"Disconnected from {device['device_name']}")
except Exception as e:
print(f"Error configuring {device['device_name']}: {str(e)}")
# Main execution
def main():
configurations = {
'R1': router_config,
'SW1': switch1_config,
'SW2': switch2_config
}
if __name__ == "__main__":
print("Starting network configuration...")
main()
print("\nNetwork configuration completed!")
● Prerequisites:
● Install Cisco IOU L2/L3 images in GNS3 or EVE-NG (refer to the provided YouTube link for
installation)
● Install Netmiko: pip install netmiko
● Ensure devices are reachable via SSH
● Topology Setup in GNS3/EVE-NG:
● Add one IOU L3 router (R1)
● Add two IOU L2 switches (SW1 and SW2)
● Connect R1 Gi0/0 to SW1 Gi0/0
● Connect SW1 Gi0/1 to SW2 Gi0/1
● Configure initial IP addresses manually or via DHCP for management
● Script Functionality:
● Configures hostname on all devices
● Sets up management IP addresses
● Enables OSPF routing on R1
● Creates VLANs 10 and 20 on switches
● Configures trunk link between SW1 and SW2
● Saves configurations
● Verifies IP interfaces
● Modifications:
● Adjust IP addresses, credentials, and interface numbers based on your lab setup
● Add more devices or modify configurations as needed
● Add error handling for specific scenarios
● Running the Script:
● Save as configure_network.py
● Run: python configure_network.py
Expected Output:
You can expand this topology by adding more devices or enhance the configuration with additional
features like access ports, additional VLANs, or different routing protocols based on your
requirements.
I'll create a Python script that combines PySNMP to collect SNMP data using a specific OID and
integrates it with a BigDataCloud API request. For this example, I'll use the OID for system
description (1.3.6.1.2.1.1.1.0) and the BigDataCloud "IP Geolocation API" to get location information
based on the device's IP.
python
# SNMP Configuration
SNMP_HOST = '192.168.1.1' # Replace with your device IP
SNMP_PORT = 161
SNMP_COMMUNITY = 'public'
OID = '1.3.6.1.2.1.1.1.0' # sysDescr
if errorIndication:
print(f"SNMP Error: {errorIndication}")
return None
elif errorStatus:
print(f"SNMP Status Error: {errorStatus.prettyPrint()}")
return None
else:
for varBind in varBinds:
return str(varBind[1]) # Return the value
except Exception as e:
print(f"SNMP Collection Error: {str(e)}")
return None
# Main execution
def main():
# Collect SNMP data
print(f"Collecting SNMP data from {SNMP_HOST}...")
snmp_result = get_snmp_data(SNMP_HOST, SNMP_PORT, SNMP_COMMUNITY, OID)
if snmp_result:
print(f"System Description: {snmp_result}")
else:
print("Failed to collect SNMP data")
return
if geo_data:
# Extract relevant information
location_info = {
'device_ip': SNMP_HOST,
'system_description': snmp_result,
'country': geo_data.get('country', {}).get('name', 'N/A'),
'city': geo_data.get('location', {}).get('city', 'N/A'),
'latitude': geo_data.get('location', {}).get('latitude', 'N/A'),
'longitude': geo_data.get('location', {}).get('longitude', 'N/A')
}
# Print results
print("\nCombined Device Information:")
print(json.dumps(location_info, indent=4))
# Save to file
with open('device_info.json', 'w') as f:
json.dump(location_info, f, indent=4)
print("\nData saved to device_info.json")
else:
print("Failed to collect geolocation data")
if __name__ == "__main__":
print("Starting data collection...")
main()
print("\nData collection completed!")
● Prerequisites:
● Install required packages:
bash
● Setup:
● Replace SNMP_HOST with your device's IP address
● Adjust SNMP_COMMUNITY if different from 'public'
● Get a free API key from https://www.bigdatacloud.com/free-api and replace
YOUR_API_KEY_HERE
● Ensure your target device has SNMP enabled and is reachable
● What the script does:
● Uses PySNMP to query OID 1.3.6.1.2.1.1.0 (system description)
● Makes an API call to BigDataCloud's IP Geolocation API
● Combines the data into a JSON structure
● Saves the results to a file
● Example Output:
● Customization Options:
● Change the OID to collect different SNMP data (e.g., '1.3.6.1.2.1.1.5.0' for sysName)
● Add more OIDs by modifying the get_snmp_data function to handle multiple values
● Modify the geolocation data extraction to include additional fields
● Add error handling for specific scenarios
Notes:
● The BigDataCloud API has a free tier with limitations (check their website for current limits)
● Ensure SNMP is properly configured on your target device
● For production use, consider adding timeout handling and retry logic
● The actual system description will vary based on your device's software and hardware
Would you like me to modify this script to collect different SNMP data or use a different
BigDataCloud API endpoint?
Here are two Python scripts implementing a UDP client-server system for calculating the average of
comma-separated numbers:
python
import socket
def main():
# Create UDP socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# Get user input
while True:
numbers = input("Enter comma-separated numbers (or 'quit' to exit):
")
if numbers.lower() == 'quit':
break
except Exception as e:
print(f"Error: {str(e)}")
finally:
client_socket.close()
print("Client socket closed")
if __name__ == "__main__":
print("UDP Client starting...")
main()
python
import socket
def calculate_average(numbers_str):
try:
# Convert string of comma-separated numbers to list of floats
numbers = [float(num.strip()) for num in numbers_str.split(',')]
# Calculate average
if numbers:
avg = sum(numbers) / len(numbers)
return str(avg)
else:
return "Error: No numbers provided"
except ValueError:
return "Error: Invalid number format"
except Exception as e:
return f"Error: {str(e)}"
def main():
# Create UDP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Calculate average
result = calculate_average(numbers_str)
print(f"Calculated average: {result}")
except Exception as e:
print(f"Server error: {str(e)}")
finally:
server_socket.close()
print("Server socket closed")
if __name__ == "__main__":
main()
● Setup:
● Save both scripts in the same directory
● No additional packages needed (uses built-in socket module)
● Running the scripts:
● First, start the server:
● bash
● python udp_server.py
● Then, in a separate terminal, start the client:
● bash
● python udp_client.py
● Usage Example:
# Server terminal:
UDP Server listening on 127.0.0.1:5000
Received from ('127.0.0.1', 54321): 13,14,15,15.5,18
Calculated average: 15.1
# Client terminal:
UDP Client starting...
Enter comma-separated numbers (or 'quit' to exit): 13,14,15,15.5,18
Server response from ('127.0.0.1', 5000): Average = 15.1
Enter comma-separated numbers (or 'quit' to exit): quit
Client socket closed
Key Features:
Client:
Server:
Notes:
Would you like me to add any of these enhancements or modify the scripts in any way?