2017-04-05 50 views
-1

我編寫了這個程序來嗅探網絡中的arp數據包並打印出那裏的源地址。代碼如下: (這僅僅是修改樣本源約亞馬遜破折號按鈕狙擊包一點點)在Python中運行Scapy Sniff函數的錯誤2,3

from scapy.all import * 

import urllib 

global flag 

def arp_display(pkt): 


if pkt[ARP].op == 1: #who-has (request) 

#if pkt[ARP].psrc == '0.0.0.0': # ARP Probe 

    if pkt[ARP].hwsrc == '0c:47:c3:e6:c5:b7': # Energizier 

    print ("Pushed Energizier") 

    if (flag == NULL) or (flag == 0): 

     url = url + "LED=0" 

     req = urllib2.Request(url) 

     response = urllib2.urlopen(req) 

     flag = 1 

     print ("send signal") 

    else : 

     url = url + "LED=1" 

     req = urllib2.Request(url) 

     response = urllib2.urlopen(req) 

     flag = 0 


    elif pkt[ARP].hwsrc == 'a4:af:66:df:9e:45': # Elements 

    print ("Pushed Elements") 

    else: 

    print ("ARP Probe from unknown device: " + pkt[ARP].hwsrc) 



print (sniff(prn=arp_display, filter="arp", store=0, count=10,lfilter=lambda pkt: ARP in pkt)) 

錯誤消息

Traceback (most recent call last): 
File "/share/Web/python/dash_check.py", line 54, in <module> 
print (sniff(prn=arp_display, filter="arp", store=0, 
count=10,lfilter=lambda pkt: ARP in pkt)) 
File "/opt/lib/python2.7/site-packages/scapy/sendrecv.py", line 620, in sniffr = prn(p) 
File "/share/Web/python/dash_check.py", line 21, in arp_display 
if (flag == NULL) or (flag == 0): 
UnboundLocalError: local variable 'flag' referenced before assignment 

我真的不知道爲什麼打印出來像這樣的錯誤消息

+1

在使用'flag'之前,它在第21行的'if'語句中有一個值。您需要爲'flag'變量賦值或甚至是'None' '聲明。 –

+0

如果可以,請編輯您的問題標題,因爲您的問題與「scrapy」無關。 –

回答

2

您正試圖訪問和修改您的函數中的全局變量。但是當你要分配功能的範圍內,本flag變量,如:

flag = 1 

flag = 0 

flag被假定爲一個局部變量,它屏蔽了該同名全局變量的外部範圍。看看這裏:Why am I getting an UnboundLocalError when the variable has a value?

這就是你的代碼發生的一個小例子:

flag = 0 
def func(): 
    if flag==0: 
     print("flag is 0") 
     flag = 1 

調用func()會引發同樣的錯誤:

UnboundLocalError: local variable 'flag' referenced before assignment 

對此的解決方案是使用global關鍵字來修改局部範圍內的全局變量。像這樣:

flag = 0 
def func(): 
    global flag 
    if flag==0: 
     print("flag is 0") 
     flag = 1 

請檢查鏈接及回答以獲得更好的理解。