且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

利用pypthon得到IP和MAC地址

更新时间:2022-09-16 16:58:59

 最近在学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:DC:6A
1: eth1 00:0D:88:4A:C6:0D



   这里利用的是grep的方法,实现的功能和shell中的awk和sed类似,哈哈,代码很简单吧。。。
本文转自你是路人甲还是霍元甲博客51CTO博客,原文链接http://blog.51cto.com/world77/573091如需转载请自行联系原作者

world77