How to verify if a packet in scapy has a Raw layer? - scapy

Hello all this is my code:
#!usr/bin/env python
import scapy.all as scapy
from scapy_http import http
def sniff(interface):
scapy.sniff(iface=interface, store=False, prn=process_sniffed_packet)
def process_sniffed_packet(packet):
if packet.haslayer(http.HTTPRequest):`enter code here`
if packet.haslayer(Raw)
print(packet[scapy.Raw].load)
sniff("eth0")
But, every time I run this code, I get the following error:
if packet.haslayer(Raw)
^
SyntaxError: invalid syntax

You are missing a colon on this line:
if packet.haslayer(Raw):
And seeing how you used import scapy.all as scapy and not from scapy.all import *, I think it should also be
if packet.haslayer(scapy.Raw):

Related

module 'subprocess' has no attribute '_subprocess'

I used python3.7 in windows7.
When I tried to run this line: suinfo.dwFlags |= subprocess._subprocess.STARTF_USESHOWWINDOW
error occurs: module 'subprocess' has no attribute '_subprocess'
import os
import sqlite3
import subprocess
import time
import re
from django.core.mail import send_mail
from django.http import HttpResponse
suinfo = subprocess.STARTUPINFO()
suinfo.dwFlags |= subprocess._subprocess.STARTF_USESHOWWINDOW
How to deal with that?
There is no such thing as subprocess._subprocess, the constant is straight under subprocess:
suinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
See the docs: https://docs.python.org/3/library/subprocess.html#subprocess.STARTF_USESHOWWINDOW

picamera on raspberry pi zero module not installed

SUMMARY:
Unable to run a time-lapse Python3 script due to a module not being installed. I am running Raspian Lite on Raspberry Pi Zero W.
THINGS I'VE TRIED:
I've tried installing picamera module for python. Tried googling the error and came across https://raspberrypi.stackexchange.com/questions/88339/importerror-no-module-named-picamera
Here is a list of installed modules. I can't see picamera on there??
help('modules')
Please wait a moment while I gather a list of all available modules...
BaseHTTPServer aifc httplib sets
Bastion antigravity ihooks sgmllib
CDROM anydbm imageop sha
CGIHTTPServer argparse imaplib shelve
Canvas array imghdr shlex
ConfigParser ast imp shutil
Cookie asynchat importlib signal
DLFCN asyncore imputil site
Dialog atexit inspect sitecustomize
DocXMLRPCServer audiodev io smtpd
FileDialog audioop itertools smtplib
FixTk base64 json sndhdr
HTMLParser bdb keyword socket
IN binascii lib2to3 spwd
MimeWriter binhex linecache sqlite3
Queue bisect linuxaudiodev sre
RPi bsddb locale sre_compile
ScrolledText bz2 logging sre_constants
SimpleDialog cPickle lsb_release sre_parse
SimpleHTTPServer cProfile macpath ssl
SimpleXMLRPCServer cStringIO macurl2path stat
SocketServer calendar mailbox statvfs
StringIO cgi mailcap string
TYPES cgitb markupbase stringold
Tix chunk marshal stringprep
Tkconstants cmath math strop
Tkdnd cmd md5 struct
Tkinter code mhlib subprocess
UserDict codecs mimetools sunau
UserList codeop mimetypes sunaudio
UserString collections mimify symbol
_LWPCookieJar colorsys mmap symtable
_MozillaCookieJar commands modulefinder sys
builtin compileall multifile sysconfig
future compiler multiprocessing syslog
_abcoll contextlib mutex tabnanny
_ast cookielib netrc tarfile
_bisect copy new telnetlib
_bsddb copy_reg nis tempfile
_codecs crypt nntplib termios
_codecs_cn csv ntpath test
_codecs_hk ctypes nturl2path textwrap
_codecs_iso2022 curses numbers this
_codecs_jp datetime opcode thread
_codecs_kr dbhash operator threading
_codecs_tw dbm optparse time
_collections decimal os timeit
_csv difflib os2emxpath tkColorChooser
_ctypes dircache ossaudiodev tkCommonDialog
_ctypes_test dis parser tkFileDialog
_curses distutils pdb tkFont
_curses_panel dl pickle tkMessageBox
_elementtree doctest pickletools tkSimpleDialog
_functools dumbdbm pipes toaiff
_hashlib dummy_thread pkgutil token
_heapq dummy_threading platform tokenize
_hotshot email plistlib trace
_io encodings popen2 traceback
_json ensurepip poplib ttk
_locale errno posix tty
_lsprof exceptions posixfile turtle
_md5 fcntl posixpath types
_multibytecodec filecmp pprint unicodedata
_multiprocessing fileinput profile unittest
_osx_support fnmatch pstats urllib
_pyio formatter pty urllib2
_random fpformat pwd urlparse
_sha fractions py_compile user
_sha256 ftplib pyclbr uu
_sha512 functools pydoc uuid
_socket future_builtins pydoc_data warnings
_sqlite3 gc pyexpat wave
_sre genericpath quopri weakref
_ssl getopt random webbrowser
_strptime getpass re whichdb
_struct gettext readline wsgiref
_symtable glob repr xdrlib
_sysconfigdata grp resource xml
_sysconfigdata_nd gzip rexec xmllib
_testcapi hashlib rfc822 xmlrpclib
_threading_local heapq rlcompleter xxsubtype
_warnings hmac robotparser zipfile
_weakref hotshot runpy zipimport
_weakrefset htmlentitydefs sched zlib
abc htmllib select
CODE BELOW:
from time import sleep
import picamera
with picamera.PiCamera() as camera:
camera.resolution = (1024, 768)
WAIT_TIME = 300
with picamera.PiCamera() as camera:
camera.resolution = (1024, 768)
for filename in
camera.capture_continuous('/home/pi/camera/img{timestamp:%H-%M-%S-%f}.jpg'):
sleep(WAIT_TIME)
The expected result is images to appear in the camera folder timestamped every 5 minutes.
While it is not stated in the documentation of picamera and it could be that its trying to run in python 2.
But I found the solution to be the following:
You need to have the following packages installed: python-picamera & python3-picamera
So running:
sudo apt-get install python-picamera fixed it

JPype error: import jpype ModuleNotFoundError: No module named 'jpype'

I installed JPype in a correct way and anything is fine and my instalation was succeed but when i run my refactor.py from command prompt i have error that i pointed in title.
i hope you can help me for solving this problem.
also i have to point that i am beginner in python3.
here is my code:
import urllib.request
import os
import tempfile
import sys
import fileinput
import logging
import jpype
logging.basicConfig(filename="ERROR.txt", level= logging.ERROR)
try:
logging.debug('we are in the main try loop')
jpype.startJVM("C:/Users/user/AppData/Local/Programs/Python/Python36/ClassWithTest.java", "-ea")
test_class = jpype.JClass("ClassWithTest")
a = testAll()
file_java_class = open("OUTPUT.txt", "w")
file_java_class.write(a)
except Exception as e1:
logging.error(str(e1))
jpype.shutdownJVM()
startJVM() function takes the path to the JVM which is like this - C:\\Program Files\\Java\\jdk-10.0.2\\bin\\server\\jvm.dll. You could use the getDefaultJVMPath() function to get the JVM path on your PC. So you can just start the JVM this way:
startJVM(getDefaultJVMPath(), "-ea")
Hope that helps!

Using NASDAQ API, can't use decode on urlopen

I'm trying to use the NASDAQ API from https://github.com/Nasdaq/DataOnDemand but cannot seem to get it to work in Python 3.
I fixed the urllib stuff and first got an error at line 92 which I fixed by encoding it to utf-8
Before:
request_parameters = urllib.parse.urlencode(values)
Fix:
request_parameters = urllib.parse.urlencode(values).encode('utf-8')
But now i get an error on:
response = urllib.request.urlopen(req)
>>>TypeError: cannot use a string pattern on a bytes-like object
When i try to fix it by decoding i get:
response = urllib.request.urlopen(req).decode()
OR
response = urllib.request.urlopen(req).decode('utf-8')
>>>AttributeError: 'HTTPResponse' object has no attribute 'decode'
This is what my imports look like:
import urllib.request
import urllib.parse
import xml.etree.cElementTree as ElementTree
import re
from pprint import pprint
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import datetime as dt
Any help is appreciated

Google speech long_running_recognizer does not work when fired through celery task

The code below works when fired as a script using python. But the same, when i encapsulate in a celery task and try to execute, it does not work. The celery task prints the line before the long_running_recognize, but does not print the one after the operation - seems like it gets stuck at the long_running_recognize call when executing as a celery task.
#!/usr/bin/env python3
import speech_recognition as sr
import json
import sqlalchemy
import io
import os
# Imports the Google Cloud client library
from google.cloud import speech
from google.cloud.speech import enums
from google.cloud.speech import types
from sqlalchemy import create_engine
# Instantiates a client
client = speech.SpeechClient()
audio=speech.types.RecognitionAudio(uri='gs://<bucket_name>/<audio_file>')
config = types.RecognitionConfig(
encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16,
language_code='en-US')
print('FIRING GOOGLE SPEECH RECOGNITION')
# Detects speech in the audio file
operation = client.long_running_recognize(config, audio)
print('Waiting for operation to complete...')
response = operation.result(timeout=600)
outfile = open('test.txt', 'w')
for result in response.results:
for alternative in result.alternatives:
print('=' * 20)
outfile.write('Transcript: {}'.format(alternative.transcript))
outfile.write('=' * 20)
outfile.write("Confidence: {}".format(alternative.confidence))
print('Transcript: {}'.format(alternative.transcript))
print(alternative.confidence)
outfile.close()
I had the same issue today, but it worked recently. I rolled back to these requirements in pip and it solved the problem.
google-api-python-client==1.6.4
google-auth==1.1.1
google-cloud-core==0.27.1
google-cloud-speech==0.29.0
google-gax==0.15.15
googleapis-common-protos==1.5.2

Resources