Facing problems in python - python

Code:
import socket
import struct
from datetime import datetime
s = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, 8)
dict = {}
file_txt = open("dos.txt", 'a')
file_txt.writelines("**********")
t1 = str(datetime.now())
file_txt.writelines(t1)
file_txt.writelines("**********")
file_txt.writelines("n")
print
"Detection Start ......."
D_val = 10
D_val1 = D_val + 10
while True:
pkt = s.recvfrom(2048)
ipheader = pkt[0][14:34]
ip_hdr = struct.unpack("!8sB3s4s4s", ipheader)
IP = socket.inet_ntoa(ip_hdr[3])
print
"Source IP", IP
if dict_has.key(IP):
dict[IP] = dict[IP] + 1
print
dict[IP]
if (dict[IP] > D_val) and (dict[IP] < D_val1):
line = "DDOS Detected "
file_txt.writelines(line)
file_txt.writelines(IP)
file_txt.writelines("n")
else:
dict[IP] = 1
When compiling i have facing a error
Error:
raceback (most recent call last):
File "/root/Desktop/Detect/./Detectddos.py", line 24, in
if dict_has.key(IP):
NameError: name 'dict_has' is not defined

it seems you have made a spelling mistake in the if statement
if dict_has.key(IP):
should be
if dict.has_key(IP):
refer https://www.geeksforgeeks.org/python-dictionary-has_key/ for more.
dict.has_key() has removed from Python 3.x
instead use
if IP in dict:

Related

Traceback <module> from extractdocx import * <module> from docx import opendocx, getdocumenttext from exceptions import PendingDeprecationWarning

Traceback (most recent call last):
File "C:\xampp\htdocs\Plag\scripts\main.py", line 8, in
from extractdocx import *
File "C:\xampp\htdocs\Plag\scripts\extractdocx.py", line 18, in
from docx import opendocx, getdocumenttext
File "C:\Users\zeesh\AppData\Local\Programs\Python\Python39\lib\site-packages\docx.py", line 30, in
from exceptions import PendingDeprecationWarning
ModuleNotFoundError: No module named 'exceptions'
# -*- coding: utf-8 -*-
# Master script for the plagiarism-checker
# Coded by: Shashank S Rao
#import other modules
from cosineSim import *
from htmlstrip import *
from extractdocx import *
#import required modules
import codecs
import traceback
import sys
import operator
import urllib.request, urllib.parse, urllib.error, urllib.request, urllib.error, urllib.parse
import json as simplejson
# Given a text string, remove all non-alphanumeric
# characters (using Unicode definition of alphanumeric).
def getQueries(text,n):
import re
sentenceEnders = re.compile('[.!?]')
sentenceList = sentenceEnders.split(text)
sentencesplits = []
for sentence in sentenceList:
x = re.compile(r'\W+', re.UNICODE).split(sentence)
x = [ele for ele in x if ele != '']
sentencesplits.append(x)
finalq = []
for sentence in sentencesplits:
l = len(sentence)
l=l/n
index = 0
for i in range(0,l):
finalq.append(sentence[index:index+n])
index = index + n-1
if index !=len(sentence):
finalq.append(sentence[len(sentence)-index:len(sentence)])
return finalq
# Search the web for the plagiarised text
# Calculate the cosineSimilarity of the given query vs matched content on google
# This is returned as 2 dictionaries
def searchWeb(text,output,c):
try:
text = text.encode('utf-8')
except:
text = text
query = urllib.parse.quote_plus(text)
if len(query)>60:
return output,c
#using googleapis for searching web
base_url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q='
url = base_url + '%22' + query + '%22'
request = urllib.request.Request(url,None,{'Referer':'Google Chrome'})
response = urllib.request.urlopen(request)
results = simplejson.load(response)
try:
if ( len(results) and 'responseData' in results and 'results' in results['responseData'] and results['responseData']['results'] != []):
for ele in results['responseData']['results']:
Match = results['responseData']['results'][0]
content = Match['content']
if Match['url'] in output:
#print text
#print strip_tags(content)
output[Match['url']] = output[Match['url']] + 1
c[Match['url']] = (c[Match['url']]*(output[Match['url']] - 1) + cosineSim(text,strip_tags(content)))/(output[Match['url']])
else:
output[Match['url']] = 1
c[Match['url']] = cosineSim(text,strip_tags(content))
except:
return output,c
return output,c
# Use the main function to scrutinize a file for
# plagiarism
def main():
# n-grams N VALUE SET HERE
n=9
if len(sys.argv) <3:
print ("Usage: python main.py <input-filename>.txt <output-filename>.txt")
sys.exit()
if sys.argv[1].endswith(".docx"):
t = docxExtract(sys.argv[1])
else:
t=open(sys.argv[1],'r')
if not t:
print ("Invalid Filename")
print ("Usage: python main.py <input-filename>.txt <output-filename>.txt")
sys.exit()
t=t.read()
queries = getQueries(t,n)
q = [' '.join(d) for d in queries]
found = []
#using 2 dictionaries: c and output
#output is used to store the url as key and number of occurences of that url in different searches as value
#c is used to store url as key and sum of all the cosine similarities of all matches as value
output = {}
c = {}
i=1
count = len(q)
if count>100:
count=100
for s in q[:100]:
output,c=searchWeb(s,output,c)
msg = "\r"+str(i)+"/"+str(count)+"completed..."
sys.stdout.write(msg);
sys.stdout.flush()
i=i+1
#print ("\n")
f = open(sys.argv[2],"w")
for ele in sorted(iter(c.items()),key=operator.itemgetter(1),reverse=True):
f.write(str(ele[0])+" "+str(ele[1]*100.00))
f.write("\n")
f.close()
print ("\nDone!")
if __name__ == "__main__":
try:
main()
except:
#writing the error to stdout for better error detection
error = traceback.format_exc()
print(("\nUh Oh!\n"+"Plagiarism-Checker encountered an error!:\n"+error)) ```
docx, last release was in 2014. The code imports module exceptions that was a top-level module in Python 2.7 but was removed in Python 3:
$ python2.7 -c "import exceptions"
$ python3.7 -c "import exceptions"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ModuleNotFoundError: No module named 'exceptions'
The bottom line: the package is only for Python 2. Use Python 2.7 or find a different package.

Python code not storing readings in a .csv file. "sequence expected" error recieved. Any idea how to fix this?

I was applying a code that reads the coordinates from a gps and fills it in a .csv file.i am new to all of this so i can't get my head around this problem. I have used the "csv" code in other programs and it has worked. But here it is giving me a hard time. The error is as follows:
Traceback (most recent call last):
File "GPScodetest2.py", line 48, in <module>
data_writer.writerow(data)
_csv.Error: sequence expected
How to fix this?
P.S the code:
from time import sleep, strftime, time
import serial
import pynmea2
import datetime
from csv import writer
#setup the serial port to which gps is connected
port = "/dev/ttyS0"
ser = serial.Serial(port, baudrate = 9600, timeout = 0.5)
dataout = pynmea2.NMEAStreamReader()
counter = 0
def get_sense_data():
while True:
newdata = ser.readline()
if newdata[0:6] == '$GPGGA':
parsed_line = pynmea2.parse(newdata)
latitude_reading = parsed_line.latitude
alpha = latitude_reading
#print(newlat)
longitude_reading = parsed_line.longitude
beta = longitude_reading
#print(newlong)
#print(latitude_reading)
#print(longitude_reading)
sense_data=[]
sense_data.append(counter)
sense_data.append(datetime.datetime.now())
sense_data.append(alpha)
sense_data.append(beta)
return sense_data
with open('GPSdata.csv', 'w+') as f:
data_writer = writer(f)
data_writer.writerow(['Term No.','Date and Time','Latitude',
' Longitude'])
while True:
data = get_sense_data
data_writer.writerow(data)
counter = counter + 1
You aren't calling the function:
data = get_sense_data
Try calling it:
data = get_sense_data()

Python object cannot be interpreted as an index

Running the code below
import threading
import io
import Client
Proxies = None
Users = None
with open("proxies.txt") as x:
Proxies = x.readlines()
with open("ids.txt") as f:
Users = f.readlines()
c = 0
for udata in Users:
uid = udata.split(':')[0]
ok = udata.split(':')[1]
while True:
proxy = Proxies[c].strip('\n')
proxySplit = proxy.split(':')
c = Client.Client(proxySplit[0], proxySplit[1], uid, ok, 171147281)
if(c):
c += 1
break
I've got this exception:
Traceback (most recent call last):
File "Run.py", line 20, in <module>
proxy = str(Proxies[c]).strip('\n')
TypeError: object cannot be interpreted as an index
I can not found what's wrong with my code. Any help will be appreciated.
It seems that in line 22 c = Client.Client(proxySplit[0], proxySplit[1], uid, ok, 171147281) you make c an object, not an int anymore. And when it goes to line 20 again, c is used as an index, which is not allowed.

Error always on line 102 of my code

So I am creating a module, and I am importing it to a python shell and running some stuff to make sure all features work and such.
For some reason every time I run the code, it gives the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/ryansaxe/Desktop/Code/python/modules/pymaps.py", line 102, in url_maker
#anything can be here
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
So where the #anything can be here is, is whatever is on line 102 of my code. Originally line 102 was:
if isinstance(startindex,datetime.datetime):
and I got the error above. I put a quick print statement on line 102 to check and it gave the same error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/ryansaxe/Desktop/Code/python/modules/pymaps.py", line 102, in url_maker
print 'Hello'
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
Is this some sort of bug? Why is it telling me there is an error with datetime on the line print 'Hello'?
Because it may be helpful, I will give you the function I am having trouble with since I have no clue how this is possible. I am keeping the print 'Hello' line so you can see where line 102 is:
def url_maker(latitudes,longitudes,times=None,color='red',label=' ',zoom=12,center=None,start=None,end=None,by=None,size='600x300'):
urls = []
import datetime
if isinstance(times[0],str) or isinstance(times[0],datetime.datetime):
from dateutil import parser
if isinstance(times[0],str):
times = [parser.parse(x) for x in times]
if isinstance(start,str):
startindex = parser.parse(start)
else:
startindex = start
if isinstance(end,str):
endindex = parse.parse(end)
else:
endindex = end
print 'Hello'
if isinstance(startindex,datetime.datetime):
startpos = between_times(times,startindex,by='start')
elif isinstance(startindex,int):
if isinstance(endindex,datetime.datetime):
startpos = between_times(times,endindex,by='end') - start
else:
startpos = start
else:
pass
if isinstance(endindex,datetime.datetime):
endpos = between_times(times,endindex,by='end')
elif isinstance(endindex,int):
if isinstance(startindex,datetime.datetime):
endpos = between_times(times,startindex,by='start') + end
else:
endpos = end
else:
pass
else:
times = range(1,len(latitudes) + 1)
if isinstance(start,int):
startpos = start
else:
startpos = None
if isinstance(end,int):
endpos = end
else:
endpos = None
if isinstance(by,str):
lat,lon,t = latitudes[startpos:endpos],latitudes[startpos:endpos],times[startpos:endpos]
print lat
t,lats,lons = time_sample(t,by,lat,lon)
elif isinstance(by,int):
lats,lons,t = latitudes[startpos:endpos:by],latitudes[startpos:endpos:by],times[startpos:endpos:by]
else:
lats,lons,t= latitudes[startpos:endpos],latitudes[startpos:endpos],times[startpos:endpos]
print t
print len(t)
if center == None:
latit = [str(i) for i in lats]
longi = [str(i) for i in lons]
center = '&center=' + common_finder(latit,longi)
else:
center = '&center=' + '+'.join(center.split())
zoom = '&zoom=' + str(zoom)
for i in range(len(lats)):
#label = str(i)
x,y = str(lats[i]),str(lons[i])
marker = '&markers=color:' + color + '%7Clabel:' + label + '%7C' + x + ',' + y
url = 'http://maps.googleapis.com/maps/api/staticmap?maptype=roadmap&size=' + size + zoom + center + marker + '&sensor=true'
urls.append(url)
#print i
return urls,t
You are running with a stale bytecode cache or are re-running the code in an existing interpreter without restarting it.
The traceback code has only bytecode to work with, which contains filename and linenumber information. When an exception occurs, the source file is loaded to retrieve the original line of code, but if the source file has changed, that leads to the wrong line being shown.
Restart the interpreter and/or remove all *.pyc files; the latter will be recreated when the interpreter imports the code again.
As for your specific exception; you probably imported the datetime class from the datetime module somewhere:
from datetime import datetime
The datetime class does not have a datetime attribute, only the module does.

Permissions, Python Script

I am learning to write Python Scripts for work and I have run into some problems. The script is supposed to read a file, and print the permissions to an email. My problem is I am getting an error when it tries to call the permission() method, and I don't know how to fix it.
Python Code
import smtplib
import os
import stat
result = ""
def permission(file):
s = os.stat(file)
mode = s.st_mode
if(stat.S_IRUSR & mode):
ownerRead = 1
result += ownerRead
else:
ownerRead = 0
result += ownerRead
if(stat.S_IWUSR & mode):
ownerWrite = 1
result += ownerWrite
else:
ownerWrite = 0
result += ownerWrite
if(stat.S_IXUSR & mode):
ownerExecute = 1
result += ownerExecute
else:
ownerExecute = 0
result += ownerExecute
if(stat.S_IRGRP & mode):
groupRead = 1
result += groupRead
else:
groupRead = 0
result += groupRead
if(stat.S_IWGRP & mode):
groupWrite = 1
result += groupWrite
else:
groupWrite = 0
result += groupWrite
if(stat.S_IXGRP & mode):
groupExecute = 1
result += groupExecute
else:
groupExecute = 0
result += groupExecute
if(stat.S_IROTH & mode):
otherRead = 1
result += otherRead
else:
otherRead = 0
result += otherRead
if(stat.S_IWOTH & mode):
otherWrite = 1
result += otherWrite
else:
otherWrite = 0
result += otherWrite
if(stat.S_IXOTH & mode):
otherExecute = 1
result += otherExecute
else:
otherExecute = 0
result += otherExecute
return result
to = 'email#yahoo.com'
gmail_user = 'email#gmail.com'
gmail_pwd = 'pwd'
smtpserver = smtplib.SMTP("smtp.gmail.com",587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(gmail_user, gmail_pwd)
header = 'To:' + to + '\n' + 'From: ' + gmail_user + '\n' + 'Subject:permissions \n'
print header
values = permission(file)
print values
msg = header + values
smtpserver.sendmail(gmail_user, to, msg)
print 'done!'
smtpserver.close()
Error Output
Traceback (most recent call last):
File "lastpart.py", line 83, in <module>
values = permission(file)
File "lastpart.py", line 15, in permission
s = os.stat(file)
TypeError: coercing to Unicode: need string or buffer, type found
You fix it by passing the actual filename to the function, not the file built-in type.
>>> file
<type 'file'>
Name your variable something other than file, and actually pass a filename to it. You never actually define the thing you're passing to your call of the function, and thus the only reason it's not crashing with an undefined variable error is because Python happens to already define something with that name, built-in.

Categories

Resources