使用Python脚本查找IP和网关

时间:2013-06-10 10:49:22

标签: python linux

我是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

1 个答案:

答案 0 :(得分: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