给Asus WL500G Deluxe无线路由器日志文件添加IP地址地理位置信息的Python小程序

Python在不温不火的发展了10年后,突然火起来了,原因是蟒父Guido van Rossum加入了google,而google又迫切希望拥有一门可以和Sun、IBM的Java,MS的C#比肩的下一代语言,看起来 python很有潜力成为这样一门语言。于是,作为独立IT爱好者,同时,也是一个非常想去google拿高工资的我,在“智廉”网上看到 google招人要求后,决定好好学学python。

我学习过Perl,同Perl的格言There's More Than One Way to Do It不同,Python的格言是There should be one-- and preferably only one --obvious way to do it. 很难说哪种哲学正确,但Python的易读易用性比Perl的确好一些。

华硕的WL500GD无线路由器可以外接一个移动硬盘兼做FTP服务器,我去年10月入手一台后,在WL500GD上7x24小时一直运行FTP服务,FTP和其他服务一起,通过 http://192.168.1.1/的浏览器界面可以设置管理路由器。当然也包括检查FTP的访问情况,如下图所示:
o_Router_Web.gif
无疑这样通过浏览器访问需要多次点击,较麻烦,而且光看IP很难估计出访客来自哪里,通常还要通过 http://www.ip138.com/可以查询IP地址来自哪里,剪贴复制的操作也不可少,趁着学习Python,我决定写一个漂亮点的程序,一次解决这些问题。

仔细分析一下,这个小小的Python程序还真运用了不少技术,通过urllib2模块提交IP数据并抓取结果页面,抓取需要HTTP基本验证才能访问的页面(访问路由器日志),通过sgmllib模块来分析抓取下来的html页面,取得需要的信息,通过anydbm模块缓存IP地址地理位置信息,通过正则表达式和string的一些访问处理文本……

好了,如果你恰巧也有一部华硕的WL500G的话,不妨试试这个程序,其他无线路由的原理相同,但需要略为修改:
ContractedBlock.gif ExpandedBlockStart.gif Check_WL500GD_FTP_Log.py
None.gifimport urllib, urllib2, sgmllib, anydbm, re
None.gif
None.gif

class LogsParser(sgmllib.SGMLParser):
None.gif    
def __init__(self):
None.gif        sgmllib.SGMLParser.
__init__(self)
None.gif        self.in_textarea 
= False
None.gif        self.log 
= ""
None.gif    
def start_textarea(self, attributes):
None.gif        
for name, value in attributes:
None.gif            
if name == 'class' and value == 'content_log_td' :
None.gif                self.in_textarea 
= True                
None.gif                
return
None.gif    
def end_textarea(self) :
None.gif        self.in_textarea 
= False
None.gif        
return
None.gif    
def handle_data(self, data) :
None.gif        
if self.in_textarea == True :
None.gif            self.log 
+= data
None.gif        
return
None.gif
None.gif

class LocationParser(sgmllib.SGMLParser):
None.gif    
def __init__(self):
None.gif        sgmllib.SGMLParser.
__init__(self)
None.gif        self.in_location 
= False
None.gif        self.location_info 
= ""
None.gif    
def start_ul(self, attributes) :
None.gif        
for name, value in attributes:
None.gif            
if name == 'class' and value == 'ul1' :
None.gif                self.in_location 
= True
None.gif    
def end_ul(self) :
None.gif        self.in_location 
= False
None.gif        
return
None.gif    
def handle_data(self, data) :
None.gif        
if self.in_location == True :
None.gif            self.location_info 
+= data
None.gif        
return
None.gif    
None.gif

def Get_Logs() :
None.gif    
# create a password manager
None.gif
    password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
None.gif    
# Add the username and password.
None.gif
    # If we knew the realm, we could use it instead of ``None``.
None.gif
    top_level_url = "http://192.168.1.1/"
None.gif    password_mgr.add_password(None, top_level_url, 
"admin""password"# Change password to fit your router
None.gif
    handler = urllib2.HTTPBasicAuthHandler(password_mgr)
None.gif    
# create "opener" (OpenerDirector instance)
None.gif
    opener = urllib2.build_opener(handler)
None.gif    
# use the opener to fetch a URL
None.gif
    opener.open(top_level_url)
None.gif    
# Install the opener.
None.gif
    # Now all calls to urllib2.urlopen use our opener.
None.gif
    urllib2.install_opener(opener)
None.gif
None.gif    p 

= LogsParser( )
None.gif    f 
= urllib2.urlopen("http://192.168.1.1/Main_LogStatus_Content.asp")
None.gif    data 
= f.read()
None.gif    
if not data:
None.gif        
return
None.gif    p.feed(data)
None.gif    p.close()
None.gif    f.close()
None.gif    



return p.log.split('\n')
None.gif
None.gif

def Get_Location_from_IP138(ip) :
None.gif    l 
= LocationParser()
None.gif    submit_data 
= {'ip' : '127.0.0.1''action' : '2' }
None.gif    submit_data[
'ip']=ip
None.gif    f
=urllib2.urlopen("http://www.ip138.com/ips8.asp", urllib.urlencode(submit_data))
None.gif    data 
= f.read()
None.gif    
if not data:
None.gif        
return
None.gif    l.feed(data)
None.gif    l.close()
None.gif    f.close()
None.gif    ipinfo 



= l.location_info
None.gif    
return ipinfo[ipinfo.rindex("查询结果3:")+11:]
None.gif
None.gif

class Location() :
None.gif    
def __init__(self) :
None.gif        self.ip_db 
= anydbm.open('ip_location_cache.dbm''c')
None.gif        self.ip_match 
= re.compile(r'\d+\.\d+\.\d+\.\d+')
None.gif    
def __del__(self) :
None.gif        self.ip_db.close()
None.gif    

def info(self, ip) :
None.gif        
if self.ip_match.match(ip,1!= None :
None.gif            
if self.ip_db.has_key(ip) == 0 :  # no IP info in cache
None.gif
                self.ip_db[ip] = Get_Location_from_IP138(ip)
None.gif            
return self.ip_db[ip]
None.gif        
return ""
None.gif
None.giflogs 

= Get_Logs()
None.gifloc 
= Location()
None.gif
for line in logs :
None.gif    
if line.strip() != "" :
None.gif        
print line, loc.info(line[line.rindex(' ')+1:])
None.gifraw_input()
None.gif



这个程序在CPython下运行通过,对于Web浏览器界面的运行结果如下:
Jun 25 02:43:53  FTP server: user anonymous logged in from 219.129.83.12 广东省韶关市 电信ADSL
Jun 25 02:43:53  FTP server: user anonymous logged in from 219.129.83.12 广东省韶关市 电信ADSL
Jun 25 03:08:58  ntp client: time is synchronized to time.nist.gov  
Jun 25 05:09:04  ntp client: time is synchronized to time.nist.gov  
Jun 25 07:09:09  ntp client: time is synchronized to time.nist.gov  
Jun 25 08:48:11  FTP server: user anonymous logged in from 219.146.252.21 山东省青岛市 广电网
Jun 25 08:48:44  FTP server: user anonymous logged in from 219.146.252.21 山东省青岛市 广电网
Jun 25 08:58:28  FTP server: user anonymous quit by session timeout 
Jun 25 09:09:09  ntp client: time is synchronized to time.nist.gov  
Jun 25 09:41:20  FTP server: user anonymous logged in from 222.244.8.189 湖南省长沙市 (宁乡县)电信
Jun 25 09:41:22  FTP server: user anonymous logged in from 222.244.8.189 湖南省长沙市 (宁乡县)电信
Python有趣么?嗯,Cool emsmiled.gif 795349.html

丁丁 2007-06-25 20:43 发表评论













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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值