how do i store the result of ICMP Reply Packet into variable for further use? - python-2.7

I am new to python. As a beginner i am facing a problem that how to store the result of ICMP reply in to variable so that it can be further used in the script in python ? i am using scapy tool along with python for packet creation.
My script is-
#!/usr/bin/python
from scapy.all import *
mac=”3c:97:0e:57:00:f1”
def build_req():
For v in range(2, 4094):
Pkt = sendp(Ether(src=”ff:ff:ff:ff:ff:ff”)/Dot1Q(vlan=v)/ARP(hwsrc=mac, psrc=”192.168.1.108”,pdst=”192.168.1.107”)/ICMP()/Padding(load=”x”*10),iface=”enp0s25”)
If response is None:
Print “vlan id is not found”
Else:
Print “vlan id found’
Sys.exit(1)
Return pkt
{ I want to store the icmp response coming from vlan id in a variable and use that response to send the packet }

You are only sending packets, but not trying to get the response. Scapy documentation tells you how to do so:
https://scapy.readthedocs.io/en/latest/usage.html#send-and-receive-packets-sr

Related

How to send a captured packet saved as text with Python

I captured packets on individual text files with tcpdump, I want to send back the captured packets, first I extracted the IP and Port, but I have not been able to send the packet.
This is my code:
def client():
packet = open("packet3.txt", "r")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(10)
sock.connect(("192.168.128.1", 80))
while True:
try:
sock.send("packet")
sleep(1)
reply = sock.recv(131072)
if not reply:
break
print "recvd: ", reply
except KeyboardInterrupt:
print "bye"
break
sock.close()
return
client()
I get this error:
reply = sock.recv(131072)
error: [Errno 10054] An existing connection was forcibly closed by the remote host

unable to post data to mosquitto broker continuously

I am trying to send data continuously from raspberry pi to a windows pc using MQTT,
I am trying to send 5 data to mosquitto, but the mosquitto seems to get only one value
coding in raspberry pi
import paho.mqtt.client as mqtt
client=mqtt.Client()
client.connect("192.168.0.104",1883,60)
for i in range(0,5):
data={"protocol":"mqtt"}
client.publish("/test",str(data))
coding at the broker to receive data is
import paho.mqtt.client as mqtt
print("attempting to connect...")
def on_connect(client, userdata, flags, rc):
if(rc==0):
print("connection successful broker linked")
elif(rc==1):
print("connection refused - incorrect protocol version")
elif(rc==2):
print("connection refused - invalid client identifier")
elif(rc==3):
print("connection refused- server unavailable")
elif(rc==4):
print("connection refused- bad username or password")
elif(rc==5):
print("connection refused- not authorised")
else:
print("currently unused")
client.subscribe("s/test")
def on_message(client, userdata, msg):
data=eval(msg.payload)
print(data)
client = mqtt.Client()
client.connect("localhost",1883,60)
client.on_connect = on_connect
client.on_message = on_message
client.loop_forever()
Have you thought about following the answer I posted here?
https://github.com/eclipse/mosquitto/issues/972
You need to make sure the network loop runs for the publishing client as well a the subscriber. The network loop actually handles sending the messages.
The following is the simplest modification to your code.
import paho.mqtt.client as mqtt
client=mqtt.Client()
client.connect("192.168.0.104",1883,60)
for i in range(0,5):
data={"protocol":"mqtt"}
client.publish("/test",str(data))
client.loop()

How to send events from siddhi event simulator to android siddhi app

I have a siddhi cep application running on Android. Now I want to send events from event simulator from stream processing editor to android app via a socket connection. Till now I have been successful in making android server socket which listens to python client simulator made by me. But to ease the process, is it possible that I can use event simulator to send events to android siddhi app?
I was wondering if I can change some configurations such that event simulator sends events to android socket, so I looked at setting in deployment.yaml file
but the sending configurations are defined for HTTP
senderConfigurations:
-
id: "http-sender"
# Configuration used for the databridge communication
databridge.config:
# No of worker threads to consume events
# THIS IS A MANDATORY FIELD
workerThreads: 10
# Maximum amount of messages that can be queued internally in MB
# THIS IS A MANDATORY FIELD
maxEventBufferCapacity: 10000000
# Queue size; the maximum number of events that can be stored in the queue
# THIS IS A MANDATORY FIELD
eventBufferSize: 2000
# Keystore file path
# THIS IS A MANDATORY FIELD
keyStoreLocation : ${sys:carbon.home}/resources/security/wso2carbon.jks
# Keystore password
# THIS IS A MANDATORY FIELD
keyStorePassword : wso2carbon
# Session Timeout value in mins
# THIS IS A MANDATORY FIELD
clientTimeoutMin: 30
# Data receiver configurations
# THIS IS A MANDATO
Thanks in advance. If you need some more details please let me know
Edit 1
I actually found a way around to do it but it's having some issues. So basically I redirected output sink of event generator to port such that sink has all the data streams. The code for Stream Processor Studio editor is
#App:name("PatternMatching")
#App:description('Identify event patterns based on the order of event arrival')
define stream RoomTemperatureStream(roomNo string, temp double);
#sink(type="tcp", url='tcp://localhost:5001/abc', sync='false', tcp.no.delay='true', keep.alive='true', worker.threads="10", #map(type='text'))
define stream RoomTemperatureAlertStream(roomNo string, initialTemp double, finalTemp double);
--Capture a pattern where the temperature of a room increases by 5 degrees within 2 minutes
#info(name='query1')
from RoomTemperatureStream
select e1.roomNo, e1.temp as initialTemp, e2.temp as finalTemp
insert into RoomTemperatureAlertStream;
it sends the streams as text to python server, which needs to be started first, code of which is
#!/usr/bin/env python
# Author : Amarjit Singh
import pickle
import socket
import pandas
from pandas import json
if __name__ == "__main__":
# ------------------ create a socket object-----------------------#
try:
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as err:
serversocket.close()
print("socket creation failed with error %s" % (err))
except KeyboardInterrupt:
serversocket.close()
print("KeyboardInterrupt - but server socket was closed ")
host = "127.0.0.1"
Server_port = 5001
# ------------------ binding to the port -----------------------#
try:
serversocket.bind((host, Server_port))
serversocket.listen(50) # queue up to 5 requests
print("\n Server has started and waiting for connection request ..... ")
# bind to the port
while True: # extra while is created so that server runs even if there is no data
running = True
clientsocket, addr = serversocket.accept() # accept a connection from client
print("Got a connection from Server%s" % str(addr)) # show connection success message
while running:
receivedData = clientsocket.recv(2048)
# json = receivedData
if receivedData:
print(receivedData)
print(receivedData[0])
print(receivedData[1])
print(receivedData[2])
# roomNo = str(receivedData[0])
# temp = int(client_tuple[1]) # from unicode to int
#
# print(" roomNo = %d: UUID = %s temp = %d" % (roomNo, temp))
except socket.error as err:
serversocket.close()
print("socket creation failed with error %s" % (err))
except KeyboardInterrupt:
serversocket.close()
print("KeyboardInterrupt - but server socket was closed ")
Initially, I was sending json data from simulator, but pickle.loads and json.loads did not work. but the problem with text is that data is displayed as
b'\x02\x00\x00\x00t\x00\x00\x003bed14d31-6697-4a74-8a3f-30dc012914ad-localhost:5001\x00\x00\x00\x03abc\x00\x00\x002roomNo:"X0ZYp",\ninitialTemp:15.97,\nfinalTemp:17.22'
b'\x02\x00\x00\x00t\x00\x00\x003bed14d31-6697-4a74-8a3f-30dc012914ad-localhost:5001\x00\x00\x00\x03abc\x00\x00\x002roomNo:"2X951",\ninitialTemp:13.42,\nfinalTemp:10.76'
b'\x02\x00\x00\x00t\x00\x00\x003bed14d31-6697-4a74-8a3f-30dc012914ad-localhost:5001\x00\x00\x00\x03abc\x00\x00\x002roomNo:"PUaJA",\ninitialTemp:15.46,\nfinalTemp:16.26'
b'\x02\x00\x00\x00t\x00\x00\x003bed14d31-6697-4a74-8a3f-30dc012914ad-localhost:5001\x00\x00\x00\x03abc\x00\x00\x002roomNo:"pnz0i",\ninitialTemp:10.42,\nfinalTemp:15.82'
how to remove this extra data?
Siddhi has a WebSocket connector[1] and it's still WIP. Using this dependency you will be able to add a WebSocket sink to your app and send events from that.
Unfortunately, you cannot directly send events from Stream Processor[2] Studio/Editor but if you have an app running in Stream Processor Editor and if it has a WebSocket sink then you can send events to App's sink stream from the Simulator which will intern send that message via WebSocket to the Siddhi app in android.
You can only simulate apps running inside the editor via the Event Simulator or simulate apps deployed in Stream Processor worker nodes via Event Simulator API.
[1]https://github.com/wso2-extensions/siddhi-io-websocket
[2]https://wso2.com/analytics

How to get MAC address of connected Access point?

I am using Scapy to sniff access point(AP) beacon packets and also getting all AP beacon packets and it's MAC address nearby AP but I need exact MAC address of connected AP then How to sniff only connected AP beacon frame or How to filter connected AP beacon frame using scapy or any alternate idea.
*I am doing it in python 2.7
Assuming the beacon frame is called pkt. pkt.addr1 is the destination MAC, pkt.addr2 is the source MAC and pkt.addr3 is the MAC address of the AP. You could write something like:
from scapy.all import *
def ap_mac(pkt):
if pkt.haslayer(Dot11)
if pkt.type == 0 and pkt.subtype == 8:
print('SSID: '+%s+' MAC:'+%s)(pk.info,pkt.addr3)
else: pass
else: pass
sniff(prn=ap_mac)
to print out all the AP MACs from beacon frames. Then you could use something like:
from scapy.all import *
def sniff_ap(pkt):
if pkt.haslayer(Dot11):
if pkt.add3 == 'xx.xx.xx.xx.xx.xx': ## AP MAC
print(pkt.summary())
else: pass
else: pass
sniff(prn=sniff_ap)
Here is a good link re: beacon frames. https://www.4armed.com/blog/forging-wifi-beacon-frames-using-scapy/
I choose alternate method i.e using command in python program
Code snippet
def Check_connected_ap():
cmd =["nmcli -f BSSID,ACTIVE dev wifi list | awk '$2 ~ /yes/ {print $1}'"]
address = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
(out, err) = address.communicate()
print out

fetch website with python include j.s css

i'm trying to fetch a whole website include the JavaScript and css file while using python.
The script get a "GET" request and send back the website (local proxy).
here is my code :
class myHandler(BaseHTTPRequestHandler):
# Handler for the GET requests
def do_GET(self):
opener = urllib.FancyURLopener({})
f = opener.open("http://www.ynet.co.il")
self.wfile.write(f.read())
return
try:
# Create a web server and define the handler to manage the
# incoming request
server = HTTPServer(('', PORT_NUMBER), myHandler)
print 'Started httpserver on port ', PORT_NUMBER
# Wait forever for incoming htto requests
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down the web server'
server.socket.close()
The result for this code is only the html is present to the client.
Thanks a lot for the help, i'm Trying to solve that for few days with no result any .