python - 使用Python脚本查找IP和网关

标签 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

最佳答案

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

使用正则表达式:

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

关于python - 使用Python脚本查找IP和网关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17022122/

相关文章:

python - 使图像背景透明的问题: pygame

c - `off_t` 之前的预期表达式

python - Postgres JSONB - 查询所有根键

python - 与其他代码一起使用时,Tkinter 保存到文件不起作用

linux - 我可以从一个网络数据实例监控四台服务器吗?

php - 使用 PHP exec 命令和 scp 复制

linux - 如何使用 tail 和 head 在配置文件中的一行之前显示 5 行

c - 包含 unistd.h 的 write() 的包装例程导致错误

python - settings.py 中模板文件夹的 Django 路径

python - 如何在 plotly 中添加条形图上方的百分比差异