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.
Related
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:
If been working on a twitter bot for a while now, just for fun, but I've been stuck with this single problem. Sometimes it works, sometimes it does not. Here is the code:
def teste():
tweets = api.home_timeline(2, read_id(FILE_NAME), tweet_mode = 'extended')
print('Setup is ok!')
for tweet in reversed(tweets):
if 'carente' in tweet.full_text.lower():
print(str(tweet.id) + ' - ' + tweet.full_text)
api.retweet(tweet.id)
store_the_id(FILE_NAME, tweet.id)
teste.x = 1
elif 'carente' not in tweet.full_text.lower():
teste.x = 0
else:
print('Error no sistema alguem me desconfiguro')
def tweet_timer():
if time.gmtime().tm_min == '10':
api.update_status(f'Farid esteve carente {y} vezes')
else:
return
while True:
teste()
with open('number.txt', 'r') as f:
read = f.readline
z = int(read())
y = z + teste.x
print(y)
with open('number.txt', 'w') as f:
write = f.write(str(y))
write
tweet_timer()
time.sleep(40)
I'm trying access the teste.x variable out of the function, but when I do at the y = z + teste.x it gives the following error:
Traceback (most recent call last):
File "c:\Users\fredg\Desktop\Programação\Python\Twitter Bot\Website\Word.py", line 69, in <module>
y = z + teste.x
AttributeError: 'function' object has no attribute 'x'
teste.x is deleted after the function is executed by the garbage collector, you can use a global variable or pass the created outside the function, returning its value from the function for further transfer and use.
Example:
def teste(x: int) -> int:
tweets = api.home_timeline(2, read_id(FILE_NAME), tweet_mode="extended")
print("Setup is ok!")
for tweet in reversed(tweets):
if "carente" in tweet.full_text.lower():
print(str(tweet.id) + " - " + tweet.full_text)
api.retweet(tweet.id)
store_the_id(FILE_NAME, tweet.id)
x = 1
elif "carente" not in tweet.full_text.lower():
x = 0
else:
print("Error no sistema alguem me desconfiguro")
return x
def tweet_timer():
if time.gmtime().tm_min == "10":
api.update_status(f"Farid esteve carente {y} vezes")
else:
return
x = 0
while True:
x = teste()
with open("number.txt", "r") as f:
read = f.readline
z = int(read())
y = z + x
print(y)
with open("number.txt", "w") as f:
write = f.write(str(y))
write
tweet_timer()
time.sleep(40)
P.S. I have not tested the functionality of the code due to the lack of the required library, but with the exception of simple possible errors, you will get the result you need
teste is a function not a class. If you want to have attributes on teste, make it a class like this:
class teste:
def __init__():
tweets = api.home_timeline(2, read_id(FILE_NAME), tweet_mode = 'extended')
# ...
Call it like this:
teste_instance = teste()
Access teste_instance.x inside of teste by referencing self.x.
Basically, i'm trying to write a script to bruteforce a protected zip file in python that tries every character combination (i.e. aa,ba,ca,da etc). But after a few tries it retrieves a strange error, and i'm not being able to find nowhere a solution for it.
Program:
import zipfile as z
class zipVictim:
def __init__(self,file):
self.found = False
self.password = ''
self.file = file
self.extracted_file_list = []
def bruteforceAttack(self,start_char: int,end_char: int,length: int,deep_loop=False,print_mode=False):
"""
Doc
"""
def _loop_chain(self,file,start_char,end_char,length):
lList = []
sPass = ''
iAttempt = 1
for iInc in range(length):
lList.append(start_char)
while lList[len(lList)-1] < end_char:
for iInc2 in range(start_char,end_char):
for iInc3 in range(len(lList)):
sPass = sPass + chr(lList[iInc3])
if iInc3 == 0:
lList[iInc3] = lList[iInc3] + 1
elif lList[iInc3 -1] > end_char:
lList[iInc3] = lList[iInc3] + 1
lList[iInc3 -1] = start_char
try:
if print_mode:
print("Attempt %s, password: %s" % (iAttempt,sPass),end='\r')
iAttempt = iAttempt + 1
oFile.extractall(pwd=sPass.encode())
self.extracted_file_list = oFile.namelist()
self.password = sPass
self.found = True
return self.found
except RuntimeError:
pass
sPass = ''
return self.found
oFile = self.file
if not deep_loop:
_loop_chain(self,oFile,start_char,end_char,length)
else:
for iInc in range(length):
_loop_chain(self,oFile,start_char,end_char,iInc+1)
if __name__ == '__main__':
file = z.ZipFile('data.zip')
s = zipVictim(file)
s.bruteforceAttack(64,125,2,print_mode=True)
Error Retrieved:
Traceback (most recent call last):
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\zipfile.py", line 925, in _read1
data = self._decompressor.decompress(data, n)
zlib.error: Error -3 while decompressing data: invalid block type
Does anybody know what trigger this error and how to solve it?
When I run the line:
def book_processing(pair, pool_length):
p = Pool(len(pool_length)*3)
temp_parameters = partial(book_call_mprocess, pair)
p.map_async(temp_parameters, pool_length).get(999999)
p.close()
p.join()
return exchange_books
I get the following error:
Traceback (most recent call last):
File "test_code.py", line 214, in <module>
current_books = book_call.book_processing(cp, book_list)
File "/home/user/Desktop/book_call.py", line 155, in book_processing
p.map_async(temp_parameters, pool_length).get(999999)
File "/usr/lib/python2.7/multiprocessing/pool.py", line 567, in get
raise self._value
zipfile.BadZipfile: Truncated file header
I feel as though there is some resource that is being used that didn't close during the last loop, but I am not sure how to close it (still learning about multiprocessing library). This error only occurs when my code repeats this section relatively quickly (within the same minute). This does not happen often, but is clear when it does.
Edit (adding the book_call code):
def book_call_mprocess(currency_pair, ex_list):
polo_error = 0
live_error = 0
kraken_error = 0
gdax_error = 0
ex_list = set([ex_list])
ex_Polo = 'Polo'
ex_Live = 'Live'
ex_GDAX = 'GDAX'
ex_Kraken = 'Kraken'
cp_polo = 'BTC_ETH'
cp_kraken = 'XETHXXBT'
cp_live = 'ETH/BTC'
cp_GDAX = 'ETH-BTC'
# Instances
polo_instance = poloapi.poloniex(polo_key, polo_secret)
fookraken = krakenapi.API(kraken_key, kraken_secret)
publicClient = GDAX.PublicClient()
flag = False
while not flag:
flag = False
err = False
# Polo Book
try:
if ex_Polo in ex_list:
polo_books = polo_instance.returnOrderBook(cp_polo)
exchange_books['Polo'] = polo_books
except:
err = True
polo_error = 1
# Livecoin
try:
if ex_Live in ex_list:
method = "/exchange/order_book"
live_books = OrderedDict([('currencyPair', cp_live)])
encoded_data = urllib.urlencode(live_books)
sign = hmac.new(live_secret, msg=encoded_data, digestmod=hashlib.sha256).hexdigest().upper()
headers = {"Api-key": live_key, "Sign": sign}
conn = httplib.HTTPSConnection(server)
conn.request("GET", method + '?' + encoded_data, '', headers)
response = conn.getresponse()
live_books = json.load(response)
conn.close()
exchange_books['Live'] = live_books
except:
err = True
live_error = 1
# Kraken
try:
if ex_Kraken in ex_list:
kraken_books = fookraken.query_public('Depth', {'pair': cp_kraken})
exchange_books['Kraken'] = kraken_books
except:
err = True
kraken_error = 1
# GDAX books
try:
if ex_GDAX in ex_list:
gdax_books = publicClient.getProductOrderBook(level=2, product=cp_GDAX)
exchange_books['GDAX'] = gdax_books
except:
err = True
gdax_error = 1
flag = True
if err:
flag = False
err = False
error_list = ['Polo', polo_error, 'Live', live_error, 'Kraken', kraken_error, 'GDAX', gdax_error]
print_to_excel('excel/error_handler.xlsx', 'Book Call Errors', error_list)
print "Holding..."
time.sleep(30)
return exchange_books
def print_to_excel(workbook, worksheet, data_list):
ts = str(datetime.datetime.now()).split('.')[0]
data_list = [ts] + data_list
wb = load_workbook(workbook)
if worksheet == 'active':
ws = wb.active
else:
ws = wb[worksheet]
ws.append(data_list)
wb.save(workbook)
The problem lies in the function print_to_excel
And more specifically in here:
wb = load_workbook(workbook)
If two processes are running this function at the same time, you'll run into the following race condition:
Process 1 wants to open error_handler.xlsx, since it doesn't exist it creates an empty file
Process 2 wants to open error_handler.xlsx, it does exist, so it tries to read it, but it is still empty. Since the xlsx format is just a zip file consisting of a bunch of XML files, the process expects a valid ZIP header which it doesn't find and it omits zipfile.BadZipfile: Truncated file header
What looks strange though is your error message as in the call stack I would have expected to see print_to_excel and load_workbook.
Anyway, Since you confirmed that the problem really is in the XLSX handling you can either
generate a new filename via tempfile for every process
use locking to ensure that only one process runs print_to_excel at a time
So I am learning python and redoing some old projects. This project involves taking in a dictionary and a message to be translated from the command line, and translating the message. (For example: "btw, hello how r u" would be translated to "by the way, hello how are you".
We are using a scanner supplied by the professor to read in tokens and strings. If necessary I can post it here too. Heres my error:
Nathans-Air-4:py1 Nathan$ python translate.py test.xlt test.msg
Traceback (most recent call last):
File "translate.py", line 26, in <module>
main()
File "translate.py", line 13, in main
dictionary,count = makeDictionary(commandDict)
File "/Users/Nathan/cs150/extra/py1/support.py", line 12, in makeDictionary
string = s.readstring()
File "/Users/Nathan/cs150/extra/py1/scanner.py", line 105, in readstring
return self._getString()
File "/Users/Nathan/cs150/extra/py1/scanner.py", line 251, in _getString
if (delimiter == chr(0x2018)):
ValueError: chr() arg not in range(256)
Heres my main translate.py file:
from support import *
from scanner import *
import sys
def main():
arguments = len(sys.argv)
if arguments != 3:
print'Need two arguments!\n'
exit(1)
commandDict = sys.argv[1]
commandMessage = sys.argv[2]
dictionary,count = makeDictionary(commandDict)
message,messageCount = makeMessage(commandMessage)
print(dictionary)
print(message)
i = 0
while count < messageCount:
translation = translate(message[i],dictionary,messageCount)
print(translation)
count = count + 1
i = i +1
main()
And here is my support.py file I am using...
from scanner import *
def makeDictionary(filename):
fp = open(filename,"r")
s = Scanner(filename)
lyst = []
token = s.readtoken()
count = 0
while (token != ""):
lyst.append(token)
string = s.readstring()
count = count+1
lyst.append(string)
token = s.readtoken()
return lyst,count
def translate(word,dictionary,count):
i = 0
while i != count:
if word == dictionary[i]:
return dictionary[i+1]
i = i+1
else:
return word
i = i+1
return 0
def makeMessage(filename):
fp = open(filename,"r")
s = Scanner(filename)
lyst2 = []
string = s.readtoken()
count = 0
while (string != ""):
lyst2.append(string)
string = s.readtoken()
count = count + 1
return lyst2,count
Does anyone know whats going on here? I've looked through several times and i dont know why readString is throwing this error... Its probably something stupid i missed
chr(0x2018) will work if you use Python 3.
You have code that's written for Python 3 but you run it with Python 2. In Python 2 chr will give you a one character string in the ASCII range. This is an 8-bit string, so the maximum parameter value for chris 255. In Python 3 you'll get a unicode character and unicode code points can go up to much higher values.
The issue is that the character you're converting using chr isn't within the range accepted (range(256)). The value 0x2018 in decimal is 8216.
Check out unichr, and also see chr.