Layer not found errors from scapy - python

I'm trying to sniff packets using scapy and keep getting the following error and not sure how to fix it.
Here is the code and the error:
from scapy.layers.inet import IP, TCP, UDP
from scapy.all import *
import socket
import datetime
def sniff_packets(pkt):
time = datetime.datetime.now()
# classifying packets into TCP
if pkt.haslayer(TCP):
# classyfying packets into TCP Incoming packets
if socket.gethostbyname(socket.gethostname()) == pkt[IP].dst:
print(str("[") + str(time) + str("]") + " " + "TCP-IN:{}".format(
len(pkt[TCP])) + " Bytes" + " " + "SRC-MAC:" + str(pkt.src) + " " + `enter code here`"DST-MAC:" + str(
pkt.dst) + " " + "SRC-PORT:" + str(pkt.sport) + " " + "DST-PORT:" + str(
pkt.dport) + " " + "SRC-IP:" + str(pkt[IP].src) + " " + "DST-IP:" + str(
pkt[IP].dst))
if socket.gethostbyname(socket.gethostname()) == pkt[IP].src:
print(str("[") + str(time) + str("]") + " " + "TCP-OUT:{}".format(
len(pkt[TCP])) + " Bytes" + " " + "SRC-MAC:" + str(pkt.src) + " " + `enter code here`"DST-MAC:" + str(
pkt.dst) + " " + "SRC-PORT:" + str(pkt.sport) + " " + "DST-PORT:" + str(
pkt.dport) + " " + "SRC-IP:" + str(pkt[IP].src) + " " + "DST-IP:" + str(
pkt[IP].dst))
# classifying packets into UDP
if pkt.haslayer(UDP):
if socket.gethostbyname(socket.gethostname()) == pkt[IP].src:
# classyfying packets into UDP Outgoing packets
print(str("[") + str(time) + str("]") + " " + "UDP-OUT:{}".format(
len(pkt[UDP])) + " Bytes " + " " + "SRC-MAC:" + str(pkt.src) + " " + `enter code here`"DST-
MAC:" + str(
pkt.dst) + " " + "SRC-PORT:" + str(pkt.sport) + " " + "DST-PORT:" + str(
pkt.dport) + " " + "SRC-IP:" + str(pkt[IP].src) + " " + "DST-IP:" + str(
pkt[IP].dst))
if socket.gethostbyname(socket.gethostname()) == pkt[IP].dst:
# classyfying packets into UDP Incoming packets
print(str("[") + str(time) + str("]") + " " + "UDP-IN:{}".format(
len(pkt[UDP])) + " Bytes " + " " + "SRC-MAC:" + str(pkt.src) + " " + `enter code here`"DST-MAC:" + str(
pkt.dst) + " " + "SRC-PORT:" + str(pkt.sport) + " " + "DST-PORT:" + str(
pkt.dport) + " " + "SRC-IP:" + str(pkt[IP].src) + " " + "DST-IP:" + str(
pkt[IP].dst))
#wrpcap("test.pcap", )
if __name__ == '__main__':
sniff(prn=sniff_packets)
Traceback (most recent call last):
File "C:\Users\tathi\CYBR-260-FINAL\final1.py", line 48, in <module>
sniff(prn=sniff_packets)
File "C:\Users\tathi\venv\lib\site-packages\scapy\sendrecv.py", line 1263, in sniff
sniffer._run(*args, **kwargs)
File "C:\Users\tathi\venv\lib\site-packages\scapy\sendrecv.py", line 1210, in _run
session.on_packet_received(p)
File "C:\Users\tathi\venv\lib\site-packages\scapy\sessions.py", line 108, in
on_packet_received
result = self.prn(pkt)
File "C:\Users\tathi\CYBR-260-FINAL\final1.py", line 28, in sniff_packets
if socket.gethostbyname(socket.gethostname()) == pkt[IP].src:
File "C:\Users\tathi\venv\lib\site-packages\scapy\packet.py", line 1344, in __getitem__
raise IndexError("Layer [%s] not found" % name)
IndexError: Layer [IP] not found

It looks like the pkt does not have the key IP in it. You can check the existence of the key by checking if IP in pkt and then proceed with your other code.
def sniff_packets(pkt):
if not IP in pkt:
return
... # Code that checks for IP value in pkt
Or, you can check any domain-specific function like pkt.haslayer that does the equivalent.
def sniff_packets(pkt):
if not pkt.haslayer(IP):
return
... # Code that checks for IP value in pkt

Related

Below piece of code is not deleting records but the records are deleted from the query when run manually

def complete_stage_purge_process(self, target_cnxn, stage_table, process_cd):
self.logger.debug(datetime.now())
self.logger.debug('complete_stage_purge_process')
delete_dt = datetime.today() - timedelta(days=30)
delete_dt = str(delete_dt)
run_pk_sql = "select run_pk from " + schemaName.PROCESS.value + "." + tableName.RUN_LOG.value + " where " + ProcessRunlog.ETL_MODIFIED_DTM.value + " <= '" + delete_dt + "' and " + \
ProcessRunlog.PROCESS_PK.value + " = (select " + ProcessRunlog.PROCESS_PK.value + " from " + schemaName.PROCESS.value + "." + \
tableName.PROCESS.value + " where " + \
Process.PROCESS_CODE.value + " = '" + process_cd + "') "
delete_sql = "delete from " + schemaName.STAGE.value + "." + stage_table + " where run_pk in (" + run_pk_sql + ")"
print(delete_sql)
print(target_cnxn)
try:
trgt_cursor = target_cnxn.cursor()
trgt_cursor.execute(delete_sql)
self.logger.debug("deletes processed successfully ")
except:
self.logger.exception('Error in processing deletes')
raise
But when added commit after trgt_cursor.execute(delete_sql) then below error is thrown. Could someone please help on how to handle this
AttributeError: 'psycopg2.extensions.cursor' object has no attribute 'commit'

Name is not identified when returning into a function python [duplicate]

This question already has answers here:
What is the scope of the variable "a"?
(3 answers)
Closed 3 years ago.
This is my code:
def checking():
response2 = requests.get('https://www.nitrxgen.net/md5db/' + str(word[1])).text
if response2:
print(Fore.GREEN + "[" + Fore.WHITE + strftime("%H:%M:%S")+ Fore.GREEN + "]" + Fore.WHITE + " |" + Fore.GREEN + " ■ " + Fore.WHITE +
"Hash Found: " + Fore.GREEN + response2 + Style.RESET_ALL + "\n", end='')
else:
print(Fore.RED + "[" + Fore.WHITE + strftime("%H:%M:%S")+ Fore.RED + "]" + Fore.WHITE + " |" + Fore.RED + " ■ " + Fore.WHITE +
"Hash Not Found" + Style.RESET_ALL + "\n", end='')
def Mutiple():
Tk().withdraw()
filename = askopenfilename(title='Choose a File', filetypes=[("Text Files", "*.txt")])
clear = lambda: os.system('cls')
clear()
with open(filename, "r", encoding="utf8") as file:
for line in file:
word = line.strip()
word = word.split(":")
return checking()
And the error code is
Traceback (most recent call last):
File "C:\Users\tosun\OneDrive\Desktop\Hashkiller\Hashkiller.py", line 111, in <module>
Mutiple()
File "C:\Users\tosun\OneDrive\Desktop\Hashkiller\Hashkiller.py", line 40, in Mutiple
return checking()
File "C:\Users\tosun\OneDrive\Desktop\Hashkiller\Hashkiller.py", line 18, in checking
response2 = requests.get('https://www.nitrxgen.net/md5db/' + str(word[1])).text
NameError: name 'word' is not defined
word is a local variable in Mutiple(). If you want to use it in checking(), you should pass it as a parameter.
def checking(word):
response2 = requests.get('https://www.nitrxgen.net/md5db/' + str(word[1])).text
if response2:
print(Fore.GREEN + "[" + Fore.WHITE + strftime("%H:%M:%S")+ Fore.GREEN + "]" + Fore.WHITE + " |" + Fore.GREEN + " ■ " + Fore.WHITE +
"Hash Found: " + Fore.GREEN + response2 + Style.RESET_ALL + "\n", end='')
else:
print(Fore.RED + "[" + Fore.WHITE + strftime("%H:%M:%S")+ Fore.RED + "]" + Fore.WHITE + " |" + Fore.RED + " ■ " + Fore.WHITE +
"Hash Not Found" + Style.RESET_ALL + "\n", end='')
def Mutiple():
Tk().withdraw()
filename = askopenfilename(title='Choose a File', filetypes=[("Text Files", "*.txt")])
clear = lambda: os.system('cls')
clear()
with open(filename, "r", encoding="utf8") as file:
for line in file:
word = line.strip()
word = word.split(":")
return checking(word)

How to get new line

How can I print a new line on the output file? When I try to add the new line with "/n" it just prints /n
This is what I have so far.
``
inputFile = open("demofile1.txt", "r")
outFile = open("Ji
string = line.split(',')
go =(string)[3::]
bo = [float(i) for i in go]
total = sum(bo)
pine = ("%8.2f"%total)
name = string[2] + "," + " " + string[1]
kale = (string[0] + " " + name + " " + "/n")
se)
Current Result
8
53 Baul
A999999
You need to use \n, not /n. So this line:
kale = (string[0] + " " + name + " " + "/n")
Should be:
kale = (string[0] + " " + name + " " + "\n")
Also, please do consider using a str formatter, so all these lines:
go =(string)[3::]
bo = [float(i) for i in go]
total = sum(bo)
pine = ("%8.2f"%total)
name = string[2] + "," + " " + string[1]
kale = (string[0] + " " + name + " " + "/n")
str1 = ''.join(kale)
str2 = ''.join(pine)
outFile.write(str1 + " " + str2 + " ")
Will become:
outFile.write("{} {} {:8.2f}\n".format(string[0], string[2] + ", " + string[1], sum(bo))

Attempting to find Cooccupancy using a custom python script

This script was created by an ex-lab member that was quite a bit more adapt at Python scripting than I am.
I am attempting to find Cooccupancy between annotated peaks in "exon" regions of the entire human h19 genome. However, after trying to get this to run for about an hour I am looking for help.
Here is the script:
#!/usr/bin/python
import math
import sys
import re
import csv
import MySQLdb
import itertools
import argparse
# format for execution: ./findCooccupancy.py <loci file> <comma separated list of marks to check> <window size> <outputfile>
# example: ./findCooccupancy.py AllGenes.txt PolII-ChIP,KAP1-ChIP,Hexim 150 output.txt
# format of loci file:
# chr2 12345678 12345900 GENEA 1 +
# chr4 987654321 98765000 GENEB 1 -
# etc...
locifile = sys.argv[1]
marks = sys.argv[2]
window = int(sys.argv[3])
outputfile = sys.argv[4]
loci = list(csv.reader(open(locifile, 'rb'),delimiter='\t'))
#loci = list(itertools.chain.from_iterable(loci))
db = MySQLdb.connect(host="localhost",user="snrnp",passwd="snrnp",db="snrnp")
cur = db.cursor()
cntdict = {}
for mark in marks.split(","):
cntdict[mark] = []
counter = 1
for locus in loci:
print "Working on line# " + str(counter)
counter += 1
if str(locus[5]) == "+":
exon = locus[1]
else:
exon = locus[2]
for mark in marks.split(","):
# this is incredibly dirty. sorry. I don't have time to do this better
if mark == 'PolII-ChIP':
cur.execute("select count(*) from CHIP_PEAK where mark = '" + str(mark) + "' and chr = '" + str(locus[0]) + "' and (abs(summit - " + str(exon) + ") < " + str(window) + ")")
#print "select count(*) from CHIP_PEAK where mark = '" + str(mark) + "' and chr = '" + str(locus[0]) + "' and (abs(summit - " + str(exon) + ") < " + str(window) + ")"
else:
cur.execute("select count(*) from CHIP_PEAK where mark = '" + str(mark) + "' and chr = '" + str(locus[0]) + "' and ((chr_start < " + str(exon) + " and chr_end > " + str(exon) + ") or (abs(chr_start - " + str(exon) + ") < " + str(window) + ") or (abs(chr_end - " + str(exon) + ") < " + str(window) + "))")
#print "select count(*) from CHIP_PEAK where mark = '" + str(mark) + "' and chr = '" + str(locus[0]) + "' and ((chr_start < " + str(exon) + " and chr_end > " + str(exon) + ") or (abs(chr_start - " + str(exon) + ") < " + str(window) + ") or (abs(chr_end - " + str(exon) + ") < " + str(window) + "))"
cnt = cur.fetchone()[0]
if cnt > 0:
cntdict[mark].append(",".join(locus))
convertedlist = []
for key in cntdict.keys():
convertedlist.append(cntdict[key])
intersectlist = set(convertedlist[0]).intersection(*convertedlist[1:])
for key in cntdict.keys():
print str(key) + " hits: " + str(len(cntdict[key]))
print "\nTotal Intersection Count: " + str(len(intersectlist))
with open(outputfile, 'w') as outputwriter:
for line in intersectlist:
outputwriter.write(line + "\n")
This is the command line that I have been using:
./findCooccupancy.py ~/code/snRNP/analysis/from\ sequencing/KEC_Project/Pol-IIAnnotatedPeaksGenome.txt PolII-ChIP 150 KECExonOccupancy.txt
This is the latest error message I have received:
Working on line# 1
Traceback (most recent call last):
File "./findCooccupancy.py", line 41, in <module>
cur.execute("select count(*) from CHIP_PEAK where mark = '" + str(mark) + "' and chr = '" + str(locus[0]) + "' and (abs(summit - " + str(exon) + ") < " + str(window) + ")")
File "/Library/Python/2.7/site-packages/MySQLdb/cursors.py", line 205, in execute
self.errorhandler(self, exc, value)
File "/Library/Python/2.7/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
_mysql_exceptions.OperationalError: (1054, "Unknown column 'Start' in 'where clause'")

Python error: string index out of range

I try to update a game of n in a row. But when I try to update the array matrix i get the "string out of range error.
I made a while statement with ind < len(board_height).
What am I doing wrong here?
Traceback (most recent call last):
File "matrix.py", line 61, in <module>
drop_disk(print_board(1))
File "matrix.py", line 23, in print_board
(matrix[0][4]) + " " + str(matrix[0][5]) + " " + str(matrix[0][6]) +" |")
IndexError: string index out of range
This is what my terminal spits out at me.
import tkinter
def print_board(y):
"""Prints the board"""
matrix = [
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0]]
matrix = str(y)
print("\n")
print("| " + str(matrix[0][0]) + " " + str(matrix[0][1]) + " " + str(matrix[0][2]) + " " + str(matrix[0][3]) + " " + str
(matrix[0][4]) + " " + str(matrix[0][5]) + " " + str(matrix[0][6]) +" |")
print("| " + str(matrix[1][0]) + " " + str(matrix[1][1]) + " " + str(matrix[1][2]) + " " + str(matrix[1][3]) + " " + str
(matrix[1][4]) + " " + str(matrix[1][5]) + " " + str(matrix[1][6]) +" |")
print("| " + str(matrix[2][0]) + " " + str(matrix[2][1]) + " " + str(matrix[2][2]) + " " + str(matrix[2][3]) + " " + str
(matrix[2][4]) + " " + str(matrix[2][5]) + " " + str(matrix[2][6]) +" |")
print("| " + str(matrix[3][0]) + " " + str(matrix[3][1]) + " " + str(matrix[3][2]) + " " + str(matrix[3][3]) + " " + str (matrix[3][4]) + " " + str(matrix[3][5]) + " " + str(matrix[3][6]) +" |")
print("| " + str(matrix[4][0]) + " " + str(matrix[4][1]) + " " + str(matrix[4][2]) + " " + str(matrix[4][3]) + " " + str (matrix[4][4]) + " " + str(matrix[4][5]) + " " + str(matrix[4][6]) +" |")
print("| " + str(matrix[5][0]) + " " + str(matrix[5][1]) + " " + str(matrix[5][2]) + " " + str(matrix[5][3]) + " " + str (matrix[5][4]) + " " + str(matrix[5][5]) + " " + str(matrix[5][6]) +" |")
print("| " + str(matrix[6][0]) + " " + str(matrix[6][1]) + " " + str(matrix[6][2]) + " " + str(matrix[6][3]) + " " + str (matrix[6][4]) + " " + str(matrix[6][5]) + " " + str(matrix[6][6]) +" |")
print("="*17)
return matrix
def drop_disk(matrix):
"Drops the disk in one of the seven columns"
board_height = 7
empty = 0
row = 0
col = 0
ind = 0
player1 = input("Wat is de naam van speler 1?\n")
player2 = input("Wat is de naam van speler 2?\n")
column = int(input(player1 + ", In welke colom wil je je stuk laten vallen (1-7)?\n"))
while ind < len(board_height):
for y in range(board_height):
if matrix[row][col] == empty:
y = matrix[row -1][col -1] = 1
ind += 1
return y
return -1
drop_disk(print_board(1))
print_board(1)
error is because you are reassigning matrix to str(y)
so matrix changes to str(y) which is actually '1'.
drop_disk(print_board(1)) # calls print_board(1) and sets y = '1'
def print_board(y): # assign y='1'
matrix = [
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0]]
matrix = str(y) # matrix = 1

Categories

Resources