python通过ip获取mac地址_利用python得到IP和MAC地址 - Python/Ruby/Perl/PHP - LinuxTone | 运维专家网论坛 - 最棒的Linux运维与开源架构...

最近在学python,现在假设需要知道这台机器的ip和MAC地址,这个需求用shell和perl很简单就能得到,我这里使用python来实现这个功能,功能比较简单,老鸟可以闪过,下面贴出过程代码

login as: root

root@172.28.19.98's password:

Last login: Tue May 24 12:03:44 2011 from 172.28.102.210

[root@localhost ~]# ipython

Python 2.6.5 (r265:79063, Jan 20 2011, 13:20:15)

Type "copyright", "credits" or "license" for more information.

IPython 0.10.1 -- An enhanced Interactive Python.

?         -> Introduction and overview of IPython's features.

%quickref -> Quick reference.

help      -> Python's own help system.

object?   -> Details about 'object'. ?object also works, ?? prints more.

In [1]: ps = !ifconfig

/usr/local/lib/python2.6/site-packages/IPython/genutils.py:437: DeprecationWarning: os.popen3 is deprecated.  Use the subprocess module.

pin,pout,perr = os.popen3(cmd)

In [2]: ps= !ifconfig

In [3]: ps.g

ps.get_list   ps.get_nlstr  ps.get_paths  ps.get_spstr  ps.grep

In [3]: ps.grep("inet addr")

Out[3]: SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):

0:           inet addr:172.28.19.98  Bcast:172.28.255.255  Mask:255.255.0.0

1:           inet addr:172.16.2.165  Bcast:172.16.255.255  Mask:255.255.0.0

2:           inet addr:127.0.0.1  Mask:255.0.0.0

In [4]: ps.grep("inet addr").fields(2)

Out[4]: SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):

0: Bcast:172.28.255.255

1: Bcast:172.16.255.255

2: Mask:255.0.0.0

In [5]: ps.grep("inet addr").fields(1)

Out[5]: SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):

0: addr:172.28.19.98

1: addr:172.16.2.165

2: addr:127.0.0.1

In [6]: ps.grep("HWaddr").fields(0,4)

Out[6]: SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):

0: eth0 00:14:85:01

C:6A

1: eth1 00:0D:88:4A:C6:0D

这里利用的是grep的方法,实现的功能和shell中的awk和sed类似,哈哈,代码很简单吧。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值