parsing text from "ethtool" command

extraspecialbitter pauldavidmena at gmail.com
Tue Nov 1 18:13:25 EDT 2011


I'm still trying to write that seemingly simple Python script to print
out network interfaces (as found in the "ifconfig -a" command) and
their speed ("ethtool <interface>").  The idea is to loop for each
interface and
print out its speed.  I'm looping correctly, but have some issues
parsing the output for all interfaces except for the "pan0"
interface.  I'm running on eth1, and the "ifconfig -a" command also
shows an eth0, and of course lo.  My script is trying to match on the
string "Speed", but I never seem to successfully enter the "if"
clause.

First, here is the output of "ethtool eth1":

=================

Settings for eth1:
	Supported ports: [ TP ]
	Supported link modes:   10baseT/Half 10baseT/Full
	                        100baseT/Half 100baseT/Full
	Supports auto-negotiation: Yes
	Advertised link modes:  10baseT/Half 10baseT/Full
	                        100baseT/Half 100baseT/Full
	Advertised pause frame use: No
	Advertised auto-negotiation: Yes
	Speed: 100Mb/s
	Duplex: Full
	Port: Twisted Pair
	PHYAD: 1
	Transceiver: internal
	Auto-negotiation: on
	MDI-X: off
	Supports Wake-on: pumbag
	Wake-on: g
	Current message level: 0x00000001 (1)
	Link detected: yes

=================

The script *should* match on the string "Speed" and then assign "100Mb/
s" to a variable, but is never getting past the second if statement
below:

=================

#!/usr/bin/python

# Quick and dirty script to print out available interfaces and their
speed

# Initializations

output = " Interface: %s Speed: %s"
noinfo = "(Speed Unknown)"
speed  = noinfo

import os, socket, types, subprocess

fp = os.popen("ifconfig -a")
dat=fp.read()
dat=dat.split('\n')
for line in dat:
    if line[10:20] == "Link encap":
       interface=line[:9]
       cmd = "ethtool " + interface
       gp = os.popen(cmd)
       fat=gp.read()
       fat=fat.split('\n')
       for line in fat:
           if line[0:6] == "Speed":
               try:
                   speed=line[8:]
               except:
                   speed=noinfo
print output % (interface, speed)

=================

Again, I appreciate everyone's patience, as I'm obviously I'm a python
newbie.  Thanks in advance!



More information about the Python-list mailing list