-1

我是 python 新手,我已经编写了以下小脚本,我只需要尽可能简单地改进代码而不是复杂。

import subprocess
import StringIO
import re

ip_r_l=subprocess.Popen("ip r l",shell=True,stdout=subprocess.PIPE).communicate()[0]
s = StringIO.StringIO(ip_r_l)

for line in s:
        if "default" in line:
                gw = re.search(r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b',line).group(0)

        if "src" in line:
                ip = re.search(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} $',line).group(0)
                ip = ip.rstrip()


print "Gatway: %r" % gw
print "IPaddr: %r" % ip
4

1 回答 1

1
import subprocess, shlex
strs = subprocess.check_output(shlex.split('ip r l'))
gateway = strs.split('default via')[-1].split()[0]
ip  = strs.split('src')[-1].split()[0]
print gateway, ip
#10.64.64.64 106.205.92.100

使用regex

import subprocess, shlex, re
strs =  subprocess.check_output(shlex.split('ip r l'))
match_string = r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
ip = re.search('src '+ match_string, strs).group(1)
gateway = re.search('default via ' + match_string, strs).group(1)
print gateway, ip
#10.64.64.64 106.205.92.100
于 2013-06-10T11:03:59.943 回答