I have just started with Python a few days earlier, and now I am trying to make a Gmail notifier for Arduino using Python. I am getting the following error. I have entered my username and ID properly, I have even tried putting application specified code given by Google, but I'm still getting this error.
import serial, sys, feedparser,time
#Settings - Change these to match your account details
USERNAME="XXXX"
PASSWORD="XXXXXXX"
PROTO="https://"
SERVER="mail.google.com"
PATH="/gmail/feed/atom/important"
try:
ser = serial.Serial("COM3", 9600)
except serial.SerialException:
print ("no device connected exiting")
sys.exit()
newmails = int(feedparser.parse(PROTO + USERNAME + ":" + PASSWORD + "#" + SERVER + PATH)["feed"]["fullcount"])
# Output data to serial port
if newmails > 0:
ser.write("m")
print("some mail")
else:
ser.write("n")
print("no mail")
#print data to terminal
# Close serial port
ser.close()
ERROR IS FOLLOWING :- C:\Python33>python mailarduino.py Traceback
(most recent call last): File "mailarduino.py", line 13, in
newmails = int(feedparser.parse(PROTO + USERNAME + ":" + PASSWORD +
"#" + SE RVER + PATH)["feed"]["fullcount"]) File
"C:\Python33\lib\site-packages\feedparser-5.1-py3.3.egg\feedparser.py",
l ine 346, in getitem return dict.getitem(self, key) KeyError:
'fullcount'
C:\Python33>
The tutorial you are copying is 5 years old. API's, which are the functions you can call and what they return, can change over time. I suggest printing out:
feedparser.parse(PROTO + USERNAME + ":" + PASSWORD + "#" + SERVER + PATH)
and see what that produces. Once you see what you have, then you can work out how to extract the info you want.
Related
I'm using Telnetlib to control a VIAVI 5800.Here is my code.
And I log results of telnet.read_very_eager. Sometimes the first read returns b'', maybe say it occurs a lot. I really don't understand why only the first read has this problem while the others just work fine. I also tried adding more time after I finishing changing the time slot, this still happens.
import telnetlib
import time
from robot.libraries.BuiltIn import BuiltIn
for vc4 in range(vc4, vc4_end):
for tug3 in range(stm_start, tug3_end):
for tug2 in range(1, 8):
for tu12 in range(1, 4):
tu12_com = ":SENSE:SDH:DS1:E1:LP:C12:CHANNEL" + " " + str(tu12) + "\n"
tug2_com = ":SENSE:SDH:DS1:E1:LP:C2:CHANNEL" + " " + str(tug2) + "\n"
tug3_com = ":SENSE:SDH:DS1:E1:LP:C3:CHANNEL" + " " + str(tug3) + "\n"
vc4_com = ":SENSE:SDH:CHANNEL:STMN" + " " + str(vc4)
tn.write(tu12_com.encode('ascii')) # change tu12
time.sleep(0.1)
tn.write(tug2_com.encode('ascii')) # change tug2
time.sleep(0.1)
tn.write(tug3_com.encode('ascii')) # change tug3
time.sleep(0.1)
tn.write(vc4_com.encode('ascii')) # change vc4
time.sleep(1.5)
tn.write(b":ABOR\n")
time.sleep(1)
tn.write(b":INIT\n")
time.sleep(5)
tn.write(b":SENSE:DATA? TEST:SUMMARY\n")
time.sleep(2)
result = tn.read_very_eager()
result_num = str(vc4) + "-" + str(tug3) + "-" + str(tug2) + "-" + str(tu12)
BuiltIn().log_to_console(result_num)
BuiltIn().log_to_console(result)
The results are like under:
results saved in excel workbook
results in RF Ride console
I'm so confused and wondering can anyone explain this. Thanks a lot.
BTW, my python version is:
C:\Users\Quinn>python -V
Python 3.7.9
I am trying to donwload a huge zip file (~9Go zipped and ~130GO unzipped) from an FTP with python using the ftplib library but unfortunately when using the retrbinary method, it does create the file in my local diretory but it is not writing into the file. After a while the code runs, I get an timeout error. It used to work fine before, but when I tried to go deeper in the use of sockets by using this code it does not work anymore. Indeed, as the files I am trying to download are huge I want to have more control with the connection to prevent timeout error while downloading the files. I am not very familar with sockets so I may have misused it. I have been searching online but did not find any problems like this. (I tried with smaller files too for test but still have the same issues)
Here are the function that I tried but both have problems (method 1 is not writing to file, method 2 donwloads file but I can't unzip it)
import time
import socket
import ftplib
import threading
# To complete
filename = ''
local_folder = ''
ftp_folder = ''
host = ''
user = ''
mp = ''
# timeout error in method 1
def downloadFile_method_1(filename, local_folder, ftp_folder, host, user, mp):
try:
ftp = ftplib.FTP(host, user, mp, timeout=1600)
ftp.set_debuglevel(2)
except ftplib.error_perm as error:
print(error)
with open(local_folder + '/' + filename, "wb") as f:
ftp.retrbinary("RETR" + ftp_folder + '/' + filename, f.write)
# method 2 works to download zip file, but header error when unziping it
def downloadFile_method_2(filename, local_folder, ftp_folder, host, user, mp):
try:
ftp = ftplib.FTP(host, user, mp, timeout=1600)
ftp.set_debuglevel(2)
sock = ftp.transfercmd('RETR ' + ftp_folder + '/' + filename)
except ftplib.error_perm as error:
print(error)
def background():
f = open(local_folder + '/' + filename, 'wb')
while True:
block = sock.recv(1024*1024)
if not block:
break
f.write(block)
sock.close()
t = threading.Thread(target=background)
t.start()
while t.is_alive():
t.join(60)
ftp.voidcmd('NOOP')
def unzip_file(filename, local_folder):
local_filename = local_folder + '/' + filename
with ZipFile(local_filename, 'r') as zipObj:
zipObj.extractall(local_folder)
And the error I get for method 1:
ftplib.error_temp: 421 Timeout - try typing a little faster next time
And the error I get when I try to unzip after using method 2:
zipfile.BadZipFile: Bad magic number for file header
Alos, regarding this code If anyone could explain what this does concerning socketopt too would be helpful:
ftp.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
ftp.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 75)
ftp.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 60)
Thanks for your help.
I've built a program to change my Mac address.The following part works just fine:
import subprocess
import optparse
import re
def get_arguments():
parser = optparse.OptionParser()
parser.add_option("-i", "--interface", dest="interface", help="interface que terá seu Mac alterado")
parser.add_option("-n","--mac", dest = "new_mac", help="New Mac address")
(options, arguments) = parser.parse_args()
if not options.interface:
parser.error("[-] Please specify an interface. Use --help for more info")
elif not options.new_mac:
parser.error("[-] Please specify a Mac. Use --help for mmore info")
return options
def change_mac(interface, new_mac):
print("[+] Changing Mac address for " + interface + " to " + new_mac)
subprocess.call("sudo ip link set dev " + interface + " down", shell=True)
subprocess.call("sudo ip link set dev " + interface + " address " + new_mac, shell=True)
subprocess.call("sudo ip link set dev " + interface + " up", shell=True)
print("***************************************************")
options = get_arguments()
change_mac(options.interface, options.new_mac)
The problem is here:
ifconfig_result = subprocess.check_output(["ifconfig", options.interface])
mac_address_search_result = re.search(r"\w\w:\w\w:\w\w:\w\w:\w\w:\w\w", ifconfig_result)
print(mac_address_search_result.group(0))
I'm receiving the following error when I try to run the program:
[+] Changing Mac address for enp5s0 to 00:1B:44:11:3A:B7
Traceback (most recent call last): File "mac_changer.py", line 31,
in
mac_address_search_result = re.search(r"\w\w:\w\w:\w\w:\w\w:\w\w:\w\w", ifconfig_result) File
"/usr/lib/python3.6/re.py", line 182, in search
return _compile(pattern, flags).search(string) TypeError: cannot use a string pattern on a bytes-like object
I know I don't need the re module, still I would like to use it.
As the error suggests, ifconfig_result is of type bytes, but re.search (and the other re functions) expect str.
You can fix this by simply converting ifconfig_result to str with decode:
ifconfig_result = subprocess.check_output(["ifconfig", options.interface]).decode()
I have created a program and from what I understand from the error shown below and from other posts on Stack, I need to encode the object before it can be hashed.
I have tried several ways to do this but still keep getting the same error message. provided below is my code and also a list of changes I have tried.
I understand what needs to be done but I guess I'm putting the code in the wrong place or the syntax is wrong as what I am trying isn't working.
any help is much appreciated.
Error Message
ha1 = hashlib.md5(user + ':' + realm + ':' + password.strip()).hexdigest()
TypeError: Unicode-objects must be encoded before hashing
Code
import sys
import requests
import hashlib
realm = "Pentester Academy"
lines = [line.rstrip('\n') for line in open('wordl2.txt')]
print (lines)
for user in ['nick', 'admin']:
get_response = requests.get("http://pentesteracademylab.appspot.com/lab/webapp/digest2/1")
test_creds = get_response
print (test_creds)
for password in lines:
# not the correct way but works for this challenge
snounce = test_creds.headers.get('www-authenticate').split('"')
uri = "/lab/webapp/digest2/1"
# create the HTTP Digest
ha1 = hashlib.md5(user + ':' + realm + ':' + password.strip()).hexdigest()
ha2 = hashlib.md5("GET:" + uri).hexdigest()
response = hashlib.md5(ha1 + ':' + snounce + ':' + ha2).hexdigest()
header_string = 'Digest username="%s", realm="%s", nonce="%s", uri="%s", response="%s"' % (user, realm, snounce, uri, response)
headers = { 'Authorization' : header_string }
test_creds = requests.get("http://pentesteracademylab.appspot.com/lab/webapp/digest2/1", headers = headers)
if test_creds.status_code == 200:
print ("CRACKED: %s:%s" % (user,password))
break
elif test_creds.status_code == 401:
print ("FAILED: %s:%s" % (user,password))
else:
print ("unexpected Status code: %d " % test_creds.status_code)
Attempted Changes
password.encode(utf-8)
----------------------
hashlib.md5().update(password.encode(lines.encoding))
---------------
lines = [line.rstrip('\n') for line in open('wordl2.txt', "rb")]
I have managed to solve my own problem using the line
pass2 = str.encode(password)
just inside the password for loop
I'm getting the following error when updating text boxes:
load glyph failed err=23 face=0x0, glyph=19
All of the lines responsible for updating the text boxes look like this the par:
self.lnePer1_temp.setText(str(values_s[0]))# + " °C")
The method which aggregates these methods is called like this:
def timer_handler(self):
self.pressedSearchDevices()
if self.grbKeys1.isEnabled():
self.pressedKey1_bat()
if self.grbKeys2.isEnabled():
self.pressedKey2_bat()
if self.grbPer1.isEnabled():
self.pressedPer1_read_all()
if self.grbPer2.isEnabled():
self.pressedPer2_read_all()
threading.Timer(60, lambda: self.timer_handler()).start()
Basically it checks periodically whether some devices are available and updates the textboxes accordingly. When commented out - everything works fine. The full method responsible for updating the textboxes is:
def pressedPer2_read_all(self):
call('./reset_ble.sh', shell=True)
cmd = "sudo node Per_read_all.js " + Per_2.lower()
output = 'None'
with Popen(cmd, shell=True, stdout=PIPE, preexec_fn=os.setsid) as process:
try:
output = process.communicate(timeout=5)[0]
except TimeoutExpired:
os.killpg(process.pid, signal.SIGINT) # send signal to the process group
output = process.communicate()[0]
print(output)
output_s = output.decode("utf-8")
values_s = output_s.split('\n')
for s in values_s: print(s + " °C")
if len(values_s) == 7:
self.lnePer2_temp.setText(str(values_s[0]))# + " °C")
self.lnePer2_dig.setText(str(values_s[1]))
self.lnePer2_light.setText(str(values_s[2]))# + " %")
self.lnePer2_hum.setText(str(values_s[3]))# + " %")
self.lnePer2_alert.setText(str(values_s[4]))
self.lnePer2_but.setText(str(values_s[5]))
else:
self.lnePer2_temp.setText(" °C")
self.lnePer2_dig.setText(" ")
self.lnePer2_light.setText(" %")
self.lnePer2_hum.setText(" %")
self.lnePer2_alert.setText(" ")
self.lnePer2_but.setText(" ")
When replacing the if-else statement with only the else statement - everything works fine, so I'm assuming that the error lies in the change of values or something like that. Similar error messages link to Qt, so I'm also assuming that the fault lies somewhere there.
The script is running on a Raspberry Pi Zero, the Python Version used is Python 3.4.2, the PyQt5 version is 5.3.2.