AttributeError: module 'socket' has no attribute 'AF_PACKET' - python

I am working on building a packet sniffing program using Python, however I have hit a speed bump. For some reason I think socket has not imported properly, because I am getting the following message when my program is run: AttributeError: module 'socket' has no attribute 'AF_PACKET'
I am using OS X and Pycharm is my IDE and I am running the latest version of Python if that helps.
Anyways here is my complete program so far:
import struct
import textwrap
import socket
def main():
connection = socket.socket(socket.AF_PACKET, socket.SOCKET_RAW, socket.ntohs(3))
while True:
rawData, address = connection.recvfrom(65535)
reciever_mac, sender_mac, ethernetProtocol, data = ethernet_frame(rawData)
print('\nEthernet Frame: ')
print('Destination: {}, Source: {}, Protocol: {}'.format(reciever_mac, sender_mac, ethernetProtocol))
# Unpack ethernet frame
def ethernet_frame(data):
reciever_mac, sender_mac, protocol = struct.unpack('! 6s 6s H', data[:14])
return getMacAddress(reciever_mac), getMacAddress(sender_mac), socket.htons(socket), data[14:]
# Convert the Mac address from the jumbled up form from above into human readable format
def getMacAddress(bytesAddress):
bytesString = map('{:02x}'.format, bytesAddress)
macAddress = ':'.join(bytesString).upper()
return macAddress
main()
Thanks for any help in advance!

Actually, AF_PACKET doesn't work on OS X, it works on Linux.
AF_PACKET equivalent under Mac OS X (Darwin)

I ran into this issue on macOS 10.13.1, using Python 3.6.3 and this cool scapy fork that is compatible with python3.
I was using version 0.22 of that tool and as suggested in this issue downgrading to version 0.21 fixed this issue!
In case scapy is not a viable alternative, you could also try the pcap library as suggested in this post (although using python 2 seems to be necessary here).

Related

AttributeError: module 'serial' has no attribute 'reset_input_buffer'

Hey guys I have a problem with the command 'rest_input_buffer'.
serial.Serial for example works. I've got the latest version of Thonny 3.3.3, Python 3.7.3 and pyserial version 3.5
The important input:
import serial
ser = serial.Serial('/dev/ttyACM0',baudrate = 9600, timeout = 1)
serial.reset_input_buffer()
This is my output:
AttributeError: module 'serial' has no attribute 'reset_input_buffer'
Any ideas? I already uninstall pyserial and installed it again, same with python. I get a similiar error with the former command 'flushInput()'
You already start your serial session with:
ser = serial.Serial('/dev/ttyACM0',baudrate = 9600, timeout = 1)
Try to flush your buffer like this:
ser.reset_input_buffer()

How to get DDE server to work in python 3?

In 2015 I have posted a question on SO how to Create DDE server in python and send data continously. The answer and code posted by JayleoPlayGround to that question back then worked flawlessly in python 2.7 and I have used it until recently.
As Python 2 is no longer actively supported from January 2020, I want to move my code to python 3. I have installed pywin32 (version 227) using pip on python 3.7.6 and tried to use the same code as before:
# coded by JayleoPlayGround
# use Portable Python 2.7.5.1 + pywin32-214
import time
import win32ui, dde
from pywin.mfc import object
class DDETopic(object.Object):
def __init__(self, topicName):
self.topic = dde.CreateTopic(topicName)
object.Object.__init__(self, self.topic)
self.items = {}
def setData(self, itemName, value):
try:
self.items[itemName].SetData( str(value) )
except KeyError:
if itemName not in self.items:
self.items[itemName] = dde.CreateStringItem(itemName)
self.topic.AddItem( self.items[itemName] )
self.items[itemName].SetData( str(value) )
ddeServer = dde.CreateServer()
ddeServer.Create('Orbitron')
ddeTopic = DDETopic('Tracking')
ddeServer.AddTopic(ddeTopic)
while True:
yourData = time.ctime() + ' UP0 DN145000001 UMusb DMfm AZ040 EL005 SNNO SATELLITE'
ddeTopic.setData('Tracking', yourData)
win32ui.PumpWaitingMessages(0, -1)
time.sleep(0.1)
When running the above code in python 3.7.6 and using pywin32 (version 227), the external DDE client application that I interface with is able to connect to the DDE server, but the data string is not received correctly. As described before, if I am using Python 2.7 with pywin32 (version 214) this works fine however.
As there are no error messages shown I am lost what the problem is under python 3. I tried all available pywin32 versions for this python version (222 to 227) without success. Any ideas on how to get this to work would be much appreciated.

Packet Sniffer using Scapy

I have write code for sniffing packet using scapy in python. And i got some problems that make me confused, showed by this picture below.
enter image description here -> Important
so this is the code
import subprocess
import time
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
logging.getLogger("scapy.loading").setLevel(logging.ERROR)
logging.getLogger("scapy.interactive").setLevel(logging.ERROR)
try:
from scapy.all import *
except ImportError:
sys.exit()
interface = 'wlp10s0'
subprocess.call(["ifconfig",interface,"promisc"],stdout=None,stderr=None,shell=False)
print 'Interface has been set to Promiscous mode'
totalpackets=0
sniffingtime=10
protocols=0
infinite=1
def timenow():
currenttime=time.strftime("%m%d%y-%H%M%S")
return currenttime
def export():
p = sniff(iface='wlp10s0',timeout=sniffingtime,count=0)
wrpcap('./home/Desktop/' + timenow() + '.pcap',p);
while infinite==1 :
export()
I hope someone can helping me solve this code.
Thank you.
./home/... is an I valid path. Use /home/... instead.
It clearly says “OSerror: No such file or directory”. You may want to lookup those errors ;-)

vscode import error: from scapy.all import IP

vscode said can't find IP in scapy.all
but from terminal, i can import it:
could somebody tell my why?
I get exactly the same issue with my Scapy code in VS Code. I think it's to do with the way pylint is working.
When you from scapy.all import IP, Python loads scapy/all.py, which includes the line from scapy.layers.all import *. scapy/layers/all.py includes this code:
for _l in conf.load_layers:
log_loading.debug("Loading layer %s" % _l)
try:
load_layer(_l, globals_dict=globals(), symb_list=__all__)
except Exception as e:
log.warning("can't import layer %s: %s", _l, e)
conf.load_layers is over in scapy/config.py:
load_layers = ['bluetooth', 'bluetooth4LE', 'dhcp', 'dhcp6', 'dns',
'dot11', 'dot15d4', 'eap', 'gprs', 'hsrp', 'inet',
'inet6', 'ipsec', 'ir', 'isakmp', 'l2', 'l2tp',
'llmnr', 'lltd', 'mgcp', 'mobileip', 'netbios',
'netflow', 'ntp', 'ppp', 'pptp', 'radius', 'rip',
'rtp', 'sctp', 'sixlowpan', 'skinny', 'smb', 'snmp',
'tftp', 'vrrp', 'vxlan', 'x509', 'zigbee']
I suspect that pylint doesn't follow those imports correctly.
I've tried the workarounds suggested in the relevant GitHub issue, but they don't seem to fix anything for Scapy. Pylint eventually added specific workarounds for the issues in Numpy - and no-one has done that for Scapy.
You can work around these issues by directly importing the IP class from the relevant layer at the top of your Python file:
from scapy.layers.inet import IP, UDP, TCP, ICMP
Et voila! No more pylint complaints about those imports.

'Serial' object has no attribute 'is_open'

I've been using code on my RPi2 to communicate to an RS485 Shield to drive various relays. I recently got a RPi3, and the code that has previously worked on the RPi2 has an error on the RPi3.
To begin with, I know that the uart (/dev/ttyAMA0) is "stolen" on the RPi3 for the bluetooth controller. Using this post, I reassigned the uart to the GPIO header so the RS485 shield should work as before. I give you this history, even though I suspect the problem is not with the hardware per se.
Here's the problem. When I execute the code below on the RPi3, I get an error:
Traceback (most recent call last):
File "serialtest.py", line 15, in <module>
if usart.is_open:
AttributeError: 'Serial' object has no attribute 'is_open'
Obviously, within the pySerial library, the serial object DOES have the 'is_open' attribute. Any suggestions on why this error is thrown? I haven't found any references to this specific error in web searches.
#!/usr/bin/env python
import serial
import time
import binascii
data = "55AA08060100024D5E77"
usart = serial.Serial ("/dev/ttyAMA0",19200)
usart.timeout = 2
message_bytes = data.decode("hex")
try:
usart.write(message_bytes)
#print usart.is_open # True for opened
if usart.is_open:
time.sleep(0.5)
size = usart.inWaiting()
if size:
data = usart.read(size)
print binascii.hexlify(data)
else:
print('no data')
else:
print('usart not open')
except IOError as e :
print("Failed to write to the port. ({})".format(e))
If you have an old version of pyserial on the Raspberry Pi, pyserial might not have the is_open, but isOpen() method instead. The isOpen() method was depricated in version 3.0 according to the documentation. You can check the pyserial version with serial.VERSION.

Categories

Resources