L’exemple de code suivant obtiendra l’adresse IPv4 pour l’interface réseau locale eth0 :
get_interface_ip.py
import subprocess
import re
def get_interface_ip(interface):
"""Obtient l'adresse IP pour une interface réseau donnée"""
command = f"ip addr show {interface}"
output = subprocess.check_output(command, shell=True).decode()
ip_pattern = r'inet\s+(\d+\.\d+\.\d+\.\d+)'
match = re.search(ip_pattern, output)
if match:
ip_address = match.group(1)
return ip_address
else:
return None
interface_name = "eth0"
ip_address = get_interface_ip(interface_name)
if ip_address:
print(f"IP address of {interface_name}: {ip_address}")
else:
print(f"No IP address found for {interface_name}")Exemple de sortie :
ip_address_output.txt
IP address of eth0: 192.168.178.221
Consultez les articles similaires par catégorie :
Python
Si cet article vous a aidé, pensez à m'offrir un café ou à faire un don via PayPal pour soutenir la recherche et la publication de nouveaux articles sur TechOverflow