Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

Determine Active NIC address using python console commands

I am trying to find an active NIC, an active NIC is one where the command wil return UP for me.

In my command:

# cat /sys/class/net/eth0/operstate

I am returned a value of UP

In another command, I type:

# cat /sys/class/net/eth1/operstate

I get a value of DOWN Overall I have 4 eth's. I basically have to use the command to determine UP or DOWN

/sys/class/net/eth[0|1|2|3]/operstate    = up | down

I want to be able to write a program where I will be able to return the eth[0|1|2|3] value that is UP.

So far this is what I have:

mylist= [0,1,2,3]
for x in mylist:
       with open('/sys/class/net/'x'/operstate') as f:
              mac_eth0= f.read().rstrip()
       if mac_eth0 == "up"
                print "it is %s" %(mac_eth0)

When I do run this code, it tells me there is an error:

File "tes.py", line 5
  with open('/sys/class/net/'x'/operstate') as f:
                             ^
 Syntax Error: invalid syntax

I'm just not sure how to add in the which eth number from the for loop. Maybe there is a better way to approach this.

Thanks in advance for the help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

x is a variable containing the value: 1 or 2 or 3 or 4. The code-snippet you've treats x as a string. Also, the code-snippet tries to enclose single quotes within single quotes generating the error.

Modify as below and it should work.

Also, there's a syntax error in the above code - you're missing a colon after the 'if' clause.

mylist= [0,1,2,3]
for x in mylist:
       with open('/sys/class/net/{}/operstate'.format(x)) as f:
              mac_eth0= f.read().rstrip()
       if mac_eth0 == "up":
                print "it is %s" %(mac_eth0)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...