I use codes below to capture wifi packets, and save the pcap file to a text file.
However in the text file it only shows packets with channel 1, even no channel 2 or more.
I'm using python2.7 and pyshark-0.3.8 .
capture = pyshark.LiveCapture(interface = network_card +'mon',output_file=pathfile +'.pcap')
capture.set_debug()
capture.sniff(timeout = scanner_time)
list = str(capture).split('(')[1]
list1 = list.split(' ')[0]
print(list1)
with open(pathfile +'.txt', 'w') as f:
for pkt in range(int(list1)):
f.write(str(capture[pkt]))
Is there any way to capture from a specific channel not just channel 1?
The image is a part of a packet in the text file which shows current channel.
image
I found this command that can change network card in monitor mode and switch to a certain channel.
sudo airmon-ng start 'network_card' 'channel'
Then run the code in my question, pyshark will search the channel you input.
When you want to stop monitoring, just type below:
sudo airmon-ng stop 'network_card'+'mon'
Related
I am using a barcode scanner as part of a project, everything works correctly until I exit the program then I can't communicate anymore with the barcode scanner. This holds true for whatever program I'm running, be it one of my own or just using screen to monitor the transmissions. As soon as I exit, the only way to make the scanner work again is to unplug and replug.
The scanner (this one) is always mounted correctly (usually at /dev/ttyACM0) and communicates by SSI over USB CDC.
I’ve tried monitoring with pyserial’s miniterm and with screen /dev/ttyACM0 9600 but the same problem arises (f.e. screen just says [screen is terminating])
Mind you, everything works well on another computer so I believe it might be an issue with the Jetson rather than the scanner.
In the project I’m trying to run, I use pyserial to interact with the device. Here is an extract of the code to give you an idea of how I use it:
import serial
serial_port = "/dev/ttyACM0"
baud_rate = 9600
with serial.Serial(serial_port, baud_rate, timeout=0.1) as device_serial:
device_serial.flush()
while True:
try:
# read a line from the serial port
barcode_byte_string = device_serial.readline()
if len(barcode_byte_string) > 0:
# convert the byte string to a string and strip the newline character
barcode = barcode_byte_string.decode("utf-8").rstrip()
# publish the barcode to the topic
self.publish_barcode(barcode, serial_port)
except serial.SerialException as e:
# exit with error code 1. This will cause the application to be restarted.
sys.exit(1)
except Exception as e:
break
First, thank for fixing my post. I'm still not sure how to include a sketch. I've been reading posts here for many months, but never posted one before.
My headless RasPi is running two sketches of mine, one reads data from a pm2.5 sensor (PMS7003) and the other is the program listed above that sends information to another Pi, the client, that turns on a pm2.5 capable air filter. (I live in California) The program that reads the PMS7003 sorts the data, called max_index, into one of six categories, 0 thru 5 and saves the current category to a text file. I'm using the 'w' mode during the write operation, so there is only one character in the text file at any time. The server program listed above reads the text file and sends it to a client that turns on the air filter for categories above 2. The client sends the word "done" back to the server to end the transaction.
Until you mentioned it, I didn't realize my mistake, clientsocket.recv(2). I'll fix that and try again.
So, the listener socket should go outside the while loop, leaving the send and receive inside???
Troubleshooting: I start the two programs using nice nohup python3 xxx.py & nice nohup python3 yyy.py. The program that reads the PMS7003 continues running and updating the text file with current category, but the server program falls out of existence after a few days. top -c -u pi reveals only the PMS7003 program running, while the server program is missing. Also, there's nothing in nohup.out or in socketexceptions.txt and I tried looking through system logs in /var/log but was overwhelmed by information and found nothing that made any sense to me.
Since writing to the socketexceptions.txt file is not in a try/except block, the crash might be happening there.
import socket
import time
index = " "
clientsocket = ""
def getmaxindex():
try:
with open('/home/pi/pm25/fan.txt','r')as f:
stat = f.read() #gets max_index from pm25b.py
return(stat)
except:
with open("/home/pi/pm25/socketexceptions.txt",'a')as f:
f.write("Failed to read max index")
def setup(index):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
s.bind(("192.168.1.70", 5050))
except:
with open("/home/pi/pm25/socketexceptions.txt",'a')as f:
f.write("Failed to bind")
try:
s.listen(1)
clientsocket, address = s.accept()
clientsocket.send(index)
rx = clientsocket.recv(2)
if rx == "done":
clientsocket.close()
except:
with open("/home/pi/pm25/socketexceptions.txt",'a')as f:
f.write("Failed to communicate with flient")
while True:
index = getmaxindex().encode('utf-8')
setup(index)
time.sleep(5)
enter code here
It is unknown what program is supposed to do and where exactly you run into problems, since there is only a code dump and no useful error description (what does "stop" mean - hang or exit, where exactly does it stop). But the following condition can never be met:
rx = clientsocket.recv(2)
if rx == "done":
The will receive at most 2 bytes (recv(2)) which is definitely not enough to store the value "done".
Apart from that it makes not real sense to recreate the same listener socket again and again, just to accept a single client and exchange some data. Instead the listener should only be created once and multiple accept should be called on the same listener socket, where each will result in a new client connection.
I am trying to read the payload of all packets in a .pcap file using Pyshark. I am able to open and read the file, access the packets and their other information but I am not able to find the correct attribute/method to use to access the payload of a packet. Any suggestions ? Is there any other way to read packet payloads in .pcap files using python for windows 10 ?
(I tried using Scapy instead of Pyshark, but apparently there is some issue with running Scapy on Windows, it does not work on my system as well)
I found these lines in different code snippets of pyshark projects on the Internet and on StackOverflow. I tried them but none of them work :
import pyshark
cap = pyshark.FileCapture('file.pcap')
pkt = cap[1]
#for other information
print(pkt.tcp.flags_ack) #this works
print(pkt.tcp.flags_syn) #this works
print(pkt.tcp.flags_fin) #this works
#for payload
print(pkt.tcp.data) #does not work, AttributeError
print(pkt.tcp.payload) #does not work, AttributeError
print(pkt.data.data) #does not work, AttributeError
This code will print the value associated with the field name tcp.payload.
capture = pyshark.FileCapture(pcap_file, display_filter='tcp')
for packet in capture:
field_names = packet.tcp._all_fields
field_values = packet.tcp._all_fields.values()
for field_name in field_names:
for field_value in field_values:
if field_name == 'tcp.payload':
print(f'{field_name} -- {field_value}')
# outputs
tcp.payload -- \xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7AP\xc2\xb7\xc2\xb7\xc2\xb7
tcp.payload -- 0x00001e2c
tcp.payload -- 113977858
...
In order to use that API you have to pass appropriate parameter into constructor of 'FileCapture' class:
import pyshark
cap = pyshark.FileCapture('file.pcap', include_raw=True, use_json=True)
pkt = cap[1]
print(pkt.data.data) # Will work
'include_raw' is the key here, but 'use_json' is needed when when 'include_raw' is used.
dir cap[].
This one will give you all accessible attributes related to your capture., look there if there is the payload option.
I have data acquisition devices I would like to pull information from. I've started a small project in Python 3.5 using pyserial to communicate to a device. I can send commands and receive data.
import serial
ser = serial.Serial()
ser.port = 'COM1'
ser.baudrate = 9600
ser.parity = PARITY_NONE
ser.timeout=.5
ser.open()
ser.write(b'#02\r')
print(ser.readline())
ser.close()
This sends a command to retrieve data in the buffer, and when I use the readline command, I pull in data.
b'>-999999-999999-999999-999999 -999999\r'
I've created an excel sheet to host data tables and test criteria which I am judging performance of our machines on. This was initially for manual user input, but I decided I'd try and see if I can automate this directly in excel. I've poured over several webpages, found several companies that would ask for payment for code- etc. I've finally settled on work done by The Scarms which uses the WIN32API to deal with serial I/O vs. the original mscomm32.ocx driver.
I've been able to bring his files into my project, and used the sample code to start. I can send a message, and visually verify it from the device I'm communicating through, but I don't get any reply from my end data acquisition device.
strData = "#02\r"
lngSize = Len(strData)
lngStatus = CommWrite(intPortID, strData)
The variable strData is a string. When sending a message using pyserial, it's prefaced by "b" which (to my knowledge) signals it to be encoded to bits before sent through the serial port.
I've been trying to look through the modCOMM code that gets added to VBA from the code provided by the link above, but I can't seem to get an input at all. Am I sending the information incorrectly using the WIN32API?
How do I send this command over the bus properly in order to get a response from the end device?
The end device in question is an Advantech ADAM 4017+.
I am working with a high refresh rate IMU (x-IO technologies NGIMU) which outputs all data in osc format. The manufacturer provides the following python script to serve the data on linux platforms ( I am running Ubuntu 16.04)
'''
NGIMU Demo python v2.7 script written by Tom Mitchell (teamxe.co.uk) 2016
Requires pyOSC https://trac.v2.nl/wiki/pyOSC
'''
import socket, OSC, threading, time
# Change this to the NGIMU IP address
send_address = '192.168.1.1', 9000
# Set the NGIMU to send to this machine's IP address
c = OSC.OSCClient()
c.connect(send_address)
msg = OSC.OSCMessage()
msg.setAddress('/wifi/send/ip')
msg.append(str(socket.gethostbyname(socket.gethostname())))
c.send(msg)
c.close()
# Set up receiver
receive_address = '192.168.1.2', 8000
s = OSC.OSCServer(receive_address)
s.addDefaultHandlers()
def sensorsHandler(add, tags, args, source):
print add + str(args)
def quaternionHandler(add, tags, args, source):
print add + str(args)
def batteryHandler(add, tags, args, source):
print add + str(args)
# Add OSC handlers
s.addMsgHandler("/sensors", sensorsHandler)
s.addMsgHandler("/quaternion", quaternionHandler)
s.addMsgHandler("/battery", batteryHandler)
# Start OSCServer
print "\nUse ctrl-C to quit."
st = threading.Thread(target = s.serve_forever)
st.start()
# Loop while threads are running
try :
while 1 :
time.sleep(10)
except KeyboardInterrupt :
print "\nClosing OSCServer."
s.close()
print "Waiting for Server-thread to finish"
st.join()
print "Done"
The IMU hosts its own network which I connect to with the computer that is to receieve the data.
I have installed pyOSC from the location referenced in the script.
When I run the script, no data is delivered, only the message "Use ctrl-C to quit".
All connections seem to take place properly. When the script is running, I can see the udp connection at the correct ip and port using the Ubuntu firewall configuration gui. I have tried disabling the firewall but that had no effect.
Separately, I have used another computer to send udp packets to that ip and port and confirmed their receipt.
To say that I am a coding novice is far too generous. Nonetheless, I need to get this script running. Any help you can offer is greatly appreciated.
The problem is that
socket.gethostbyname(socket.gethostname())
is not setting the correct IP. You should change to
msg.setAddress('/wifi/send/ip')
msg.append('192.168.1.2')