如何用Python从Linux系统的shell命令中提取并显示IP地址?
Fixing Python IP Retrieval for Linux's
eno1 Interface Hey there! I see you're trying to fetch the IP address of the eno1 network interface on Linux using Python and display it, but your current code isn't working as expected. Let's walk through the issues with your existing code and fix this step by step.
What's Wrong with Your Current Code?
- The regex pattern
^([A-Z][0-9]+)+$doesn't match IPv4 addresses at all—it's designed for uppercase letters followed by numbers, which has nothing to do with IP formats. - You're relying on
cmd[1]to get the line with the IP address, butifconfigoutput can vary slightly between Linux distributions. Hardcoding line numbers makes your code unstable. re.match('[0-9]+', cmd[1])only matches the first sequence of numbers in the line, not the full IP address (like10.11.10.1).
Solution 1: Parse ifconfig Output Correctly
This approach uses a proper regex to match IPv4 addresses and adds error handling for missing interfaces:
import tkinter import subprocess import re def get_interface_ip(interface_name): try: # Run ifconfig and decode the output to a string cmd_output = subprocess.check_output(f"ifconfig {interface_name}", shell=True).decode() # Regex to find the "inet" line and capture the IP address ip_match = re.search(r'inet (\d+\.\d+\.\d+\.\d+)', cmd_output) if ip_match: return ip_match.group(1) return "No IPv4 address assigned to this interface" except subprocess.CalledProcessError: return f"Interface '{interface_name}' does not exist on this system" # Get the IP for eno1 eno1_ip = get_interface_ip("eno1") print(f"eno1 IP Address: {eno1_ip}") # Display the IP in a Tkinter window root = tkinter.Tk() root.title("Network Interface IP") ip_label = tkinter.Label(root, text=f"eno1 IP: {eno1_ip}", font=("Arial", 12)) ip_label.pack(padx=30, pady=30) root.mainloop()
Solution 2: Use ip addr (Modern Linux Systems)
Many newer Linux distributions deprecate ifconfig in favor of ip addr. This method is more reliable on modern systems:
import tkinter import subprocess import re def get_interface_ip(interface_name): try: cmd_output = subprocess.check_output(f"ip addr show {interface_name}", shell=True).decode() # Match the inet line and extract the IP (ignoring the subnet mask) ip_match = re.search(r'inet (\d+\.\d+\.\d+\.\d+)\/', cmd_output) if ip_match: return ip_match.group(1) return "No IPv4 address assigned to this interface" except subprocess.CalledProcessError: return f"Interface '{interface_name}' does not exist on this system" # Fetch and display the IP eno1_ip = get_interface_ip("eno1") print(f"eno1 IP Address: {eno1_ip}") # Tkinter window display root = tkinter.Tk() root.title("Network Interface IP") ip_label = tkinter.Label(root, text=f"eno1 IP: {eno1_ip}", font=("Arial", 12)) ip_label.pack(padx=30, pady=30) root.mainloop()
Key Improvements:
- Stable IP Matching: Uses regex tailored to IPv4 addresses, so it doesn't depend on fixed line positions in command output.
- Error Handling: Catches cases where the specified interface doesn't exist, preventing crashes.
- Flexible Display: Includes both terminal output and a Tkinter window to show the IP, as you mentioned wanting to display it on screen.
内容的提问来源于stack exchange,提问作者user1662698
相关产品推荐
相关产品推荐

