Raspberrypi Python code not working proprely - shell

I want use this code to get cpu temperature from my raspberry_pi and if the temperature is too high sending an warn email , the code show below:
# coding=utf-8
import os
import smtplib
from email.mime.text import MIMEText
# At First we have to get the current CPU-Temperature with this defined function
def getCPUtemperature():
res = os.popen('vcgencmd measure_temp').readline()
return (res.replace("temp=", "").replace("'C\n", ""))
# Now we convert our value into a float number
temp = float(getCPUtemperature())
# Check if the temperature is abouve 30°C (test with 30)
if (temp > 30):
# Enter your smtp Server-Connection
server = smtplib.SMTP('smtpmail.provider.com', 587)
# if your using gmail: smtp.gmail.com
server.ehlo()
server.starttls()
server.ehlo
# Login
server.login("your email or username", "your Password")
# Now comes the Text we want to send:
value = "Critical warning! The actual temperature is: " + getCPUtemperature()
msg = MIMEText(value)
# The Subject of your E-Mail
msg['Subject'] = "Critical warning! Temperature:" + getCPUtemperature()
# Consigner of your E-Mail
msg['From'] = "Raspberry Pi"
# recipient of your E-Mail
msg['To'] = "recipient#gmail.com"
# Finally send the mail
server.sendmail("consigner#gmail.com", "recipient#gmail.com", msg.as_string())
server.quit()
print "Everything was working fine! Best regards www.quaintproject.wordpress.com"
this code should working and had previous successful examples , but when I run it the output like this:
pi#raspberrypi:~ $ sudo nano tempwarn.py
pi#raspberrypi:~ $ sudo python tempwarn.py
Traceback (most recent call last):
File "tempwarn.py", line 20, in <module>
server = smtplib.SMTP('smtpmail.provider.com', 587)
File "/usr/lib/python2.7/smtplib.py", line 256, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python2.7/smtplib.py", line 317, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python2.7/smtplib.py", line 292, in _get_socket
return socket.create_connection((host, port), timeout)
File "/usr/lib/python2.7/socket.py", line 557, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno -2] Name or service not known
why it has this kind of error? and im pretty sure the 587 is correct setting for gmail.

swap smtpmail.provider.com to smtp.gmail.com

Related

Getting OSError: (Address already in use) while runnning a function that uses trio-sockets in a while loop

Code
import trio
from trio import socket
async def listen(host, port):
while True:
fullmsg = ""
sock = socket.socket()
await sock.bind((host, port))
sock.listen()
print(f'Awaiting Receive On {host}:{port}')
conn, addr = await sock.accept()
print(f'Connection Received From {addr[0]}:{addr[1]}')
while True:
try:
msg = await conn.recv(8)
if len(msg.decode().strip()) > 0:
print(f'Received {len(msg.strip())} bytes')
fullmsg += msg.decode().strip()
else:
break
except Exception as e:
print(f'DEBUG: {e}')
sock.shutdown(0)
sock.close()
print(fullmsg)
# function that runs the listen function:
async def create():
async with trio.open_nursery() as nursery:
nursery.start_soon(listen, '127.0.0.1', 6969)
# To run the program
trio.run(create)
I want to run the function over and over again everytime it receives a message of length 0 or when the connection gets closed by the client but when the function completes the first iteration of the first while loop, it gives an OSError saying the port is already in use. I close and shutdown my sockets by the ending of the loop but I still don't know where the program is erroring out.
Output Of The Program
Awaiting Receive On 127.0.0.1:6969
Connection Received From 127.0.0.1:37122
Received 8 bytes
Received 5 bytes
Hello, World!
Traceback (most recent call last):
File "./ape.py", line 68, in <module>
trio.run(create)
File "/usr/local/lib/python3.8/dist-packages/trio/_core/_run.py", line 1804, in run
raise runner.main_task_outcome.error
File "./ape.py", line 59, in create
nursery.start_soon(listen, '127.0.0.1', 6969)
File "/usr/local/lib/python3.8/dist-packages/trio/_core/_run.py", line 730, in __aexit__
raise combined_error_from_nursery
File "./ape.py", line 15, in listen
await sock.bind((host, port))
File "/usr/local/lib/python3.8/dist-packages/trio/_socket.py", line 473, in bind
return self._sock.bind(address)
OSError: [Errno 98] Address already in use
Like others said in their comments, the problem is that on Unix-y platforms, you have to set the SO_REUSEADDR socket option if you want to be able to close a listening socket and then immediately open a new one bound to the same port.
Note that on Windows, though, you should never set the SO_REUSEADDR option, because on Windows, the behavior you want is enabled by default, and SO_REUSEADDR is redefined to be a "turn off security" option.
trio.socket is very low-level and exposes all these details, so if you want to deal with them yourself it lets you do that. But most users will be better off using the higher level helpers like trio.serve_tcp, which will handle a lot of these details automatically.

'WinError 10061' when using a sockets function in a tk command

Hi and thanks for reading this. I know what the problem is but I can't figure out how to fix it.
So the problem goes like this (I think), python is trying to run connect() before the user inputs the host name(hostname) therefore python is trying to connect to a blank host('') which in turn causes a [WinError 10061] to happen. I have tried buffering connect() with another function(connect_buffer()), the error kept on happening, even when I added a if statement that set hostname to 'localhost' if hostname was blank(''), but that didn't work either and turned up the same error.
So my Question is how do I fix this?
Here is the error:
Traceback (most recent call last):
File "H:\server\New folder\Tk_cleint.py", line 89, in <module>
setup_confirm_button = tk.Button(window,text = 'Connect', command = setup())
File "H:\server\New folder\Tk_cleint.py", line 18, in setup
create_sock(host, int(port))
File "H:\server\New folder\Tk_cleint.py", line 36, in create_sock
connect(cleintsocket, nhost, nport)
File "H:\server\New folder\Tk_cleint.py", line 27, in connect
self.connect((hostname, connectingport))
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
And here is my code
#---Import statments---#
import socket, os, multiprocessing
import tkinter as tk
#---global variables---#
setup = ''
cleintsocket = ''
#---Defs---#
def setup():
global host, port, user
host = setup_host_box.get()
port = setup_port_box.get()
user = setup_user_box.get()
def connect_buffer(self, hostname, connectingport):
connect(self, hostname, connectingport)
def connect(self, hostname, connectingport):
if hostname == '':
hostname = 'localhost'
self.connect((hostname, int(connectingport)))
print('connected')
multiprocessing.Process(target = resv()).start()
def create_sock(nhost, nport):
global cleintsocket
cleintsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connect(cleintsocket, nhost, nport)
def send(username, cleintsock):
'''to send a message'''
usrmsg = (username + ' - ' + chat_msg_box.get()).encode()
cleintsock.send(usrmsg)
def resv(sock):
'''resive subscript, run through mutiprosses module'''
while True:
rmsg = sock.recv(1024).decode()
chat_msg_display_text.insert('end.0.', rmsg)
def chat():
'''loads chat page'''
setup_host_text.pack_forget()
setup_host_box.pack_forget()
setup_port_text.pack_forget()
setup_port_box.pack_forget()
setup_user_text.pack_forget()
setup_user_box.pack_forget()
setup_confirm_button.pack_forget()
chat_msg_display_text.pack()
chat_msg_box.pack()
chat_msg_send_button.pack()
def start():
'''starts the setup page'''
setup_host_text.pack()
setup_host_box.pack()
setup_port_text.pack()
setup_port_box.pack()
setup_user_text.pack()
setup_user_box.pack()
setup_confirm_button.pack()
def send_button_callback():
'''add a buffer to allow time for 'cleintsocket' to be defined in "create_sock()"'''
send(user, cleintsocket)
#---TK Setup---#
#--window setup--#
window = tk.Tk()
window.title('Chat')
window.geometry('600x600')
window.configure(background='#ffffff')
#--connection setup page--#
setup_host_text = tk.Label(window, text = 'Host')
setup_host_box = tk.Entry(window, bg = '#ffffff')
setup_port_text = tk.Label(window, text = 'Port')
setup_port_box = tk.Entry(window, bg = '#ffffff')
setup_user_text = tk.Label(window, text = 'Username')
setup_user_box = tk.Entry(window, bg = '#ffffff')
setup_confirm_button = tk.Button(window,text = 'Connect', command = setup())
#--chat page--#
chat_msg_box = tk.Entry(window, bg='#ffffff')
chat_msg_send_button = tk.Button(window, text = 'send', command = send_button_callback)
chat_msg_display_text = tk.Text(window, width=600, height=500, wrap = 'word')
#--------------#
start()
and here are some links to questions that didn't help:
WinError 10049: The requested address is not valid in its context
Connecting to myself through my public IP through TCP
Webscraping with Python: WinError 10061: Target machine actively refused
Thank you to anyone who helps.
On your setup_confirm_button you're using command = setup() this should be command = setup or command = lambda: setup()
By calling setup() you're actually calling the function instead of setting it as a reference to the function for the command, and it's running your function then instead of on the button click.
The reason using lambda: setup() also works is because lambda creates an anonymous function.
Also, in your multiprocessing process you're likewise calling resv() instead of passing resv this is calling the function with a while loop and blocking the main event loop.

pyzmq recv_json can't decode message sent by send_json

Here is my code with the extraneous stuff stripped out:
coordinator.py
context = zmq.Context()
socket = context.socket(zmq.ROUTER)
port = socket.bind_to_random_port(ZMQ_ADDRESS)
poller = zmq.Poller()
poller.register(socket, zmq.POLLIN)
while True:
event = poller.poll(1)
if not event:
continue
process_id, val = socket.recv_json()
worker.py
context = zmq.Context()
socket = context.socket(zmq.DEALER)
socket.connect('%s:%s' % (ZMQ_ADDRESS, kwargs['zmq_port']))
socket.send_json(
(os.getpid(), True)
)
what happens when I run it:
process_id, val = socket.recv_json()
File "/Users/anentropic/.virtualenvs/myproj/lib/python2.7/site-packages/zmq/sugar/socket.py", line 380, in recv_json
return jsonapi.loads(msg)
File "/Users/anentropic/.virtualenvs/myproj/lib/python2.7/site-packages/zmq/utils/jsonapi.py", line 71, in loads
return jsonmod.loads(s, **kwargs)
File "/Users/anentropic/.virtualenvs/myproj/lib/python2.7/site-packages/simplejson/__init__.py", line 451, in loads
return _default_decoder.decode(s)
File "/Users/anentropic/.virtualenvs/myproj/lib/python2.7/site-packages/simplejson/decoder.py", line 406, in decode
obj, end = self.raw_decode(s)
File "/Users/anentropic/.virtualenvs/myproj/lib/python2.7/site-packages/simplejson/decoder.py", line 426, in raw_decode
raise JSONDecodeError("No JSON object could be decoded", s, idx)
JSONDecodeError: No JSON object could be decoded: line 1 column 0 (char 0)
and if I dig in with ipdb:
> /Users/anentropic/.virtualenvs/myproj/lib/python2.7/site-packages/zmq/sugar/socket.py(380)recv_json()
379 msg = self.recv(flags)
--> 380 return jsonapi.loads(msg)
381
ipdb> p msg
'\x00\x9f\xd9\x06\xa2'
hmm, that doesn't look like JSON... is this a bug in pyzmq? am I using it wrong?
Hmm, ok, found the answer.
There is an annoying asymmetry in the ØMQ interface, so you have to be aware of the type of socket you are using.
In this case my use of ROUTER/DEALER architecture means that the JSON message sent from the DEALER socket, when I do send_json, gets wrapped in multipart message envelope. The first part is a client id (I guess this is the '\x00\x9f\xd9\x06\xa2' that I got above) and the second part is the JSON string we are interested in.
So in the last line of my coordinator.py I need to do this instead:
id_, msg = socket.recv_multipart()
process_id, val = json.loads(msg)
IMHO this is bad design on the part of ØMQ/pyzmq, the library should abstract this away and have just send and recv methods, that just work.
I got the clue from this question How can I use send_json with pyzmq PUB SUB so it looks like PUB/SUB architecture has the same issue, and no doubt others too.
This is described in the docs but it's not very clear
http://zguide.zeromq.org/page:all#The-Asynchronous-Client-Server-Pattern
Update
In fact, I found in my case I could simplify the code further, by making use of the 'client id' part of the message envelope directly. So the worker just does:
context = zmq.Context()
socket = context.socket(zmq.DEALER)
socket.identity = str(os.getpid()) # or I could omit this and use ØMQ client id
socket.connect('%s:%s' % (ZMQ_ADDRESS, kwargs['zmq_port']))
socket.send_json(True)
It's also worth noting that when you want to send a message the other direction, from the ROUTER, you have to send it as multipart, specifying which client it is destined for, eg:
coordinator.py
context = zmq.Context()
socket = context.socket(zmq.ROUTER)
port = socket.bind_to_random_port(ZMQ_ADDRESS)
poller = zmq.Poller()
poller.register(socket, zmq.POLLIN)
pids = set()
while True:
event = poller.poll(1)
if not event:
continue
process_id, val = socket.recv_json()
pids.add(process_id)
# need some code in here to decide when to stop listening
# and break the loop
for pid in pids:
socket.send_multipart([pid, 'a string message'])
# ^ do your own json encoding if required
I guess there is probably some ØMQ way of doing a broadcast message rather than sending to each client in a loop as I do above. I wish the docs just had a clear description of each available socket type and how to use them.

File "D:\datasend.py", line 36, in <module> s.send(message) TypeError: 'str' does not support the buffer interface in python 3.4.1

Send some data to remote server
message = "GET / HTTP/1.1\r\n\r\n"
try :
#Set the whole string
s.send(message)
except socket.error:
#Send failed
print ('Send failed')
sys.exit()
print ('Message send successfully')
Now receive data
reply = s.recv(4096)
print ('reply')

Handling Authentication Retrieving a Image from authenicated website Via urllib2

I am trying to make a small API that logs into a internal monitoring tool via web and retrieves images on pages that I specify using the login credentials I specify. It's not passing any authentication to the last section after it has already built the URL. After the URL is built, it is put into variable y. I then attempt to open y and save it, that is where the authentication problem is happening. Please scroll down for examples.
import urllib
import urllib2
import lxml, lxml.html
ID = raw_input("Enter ID:")
PorS = raw_input("Enter 1 for Primary 2 for Secondary:")
base_link = 'http://statseeker/cgi/nim-report?rid=42237&command=Graph&mode=ping&list=jc-'
dash = '-'
end_link = '&tfc_fav=range+%3D+start_of_today+-+1d+to+now%3B&year=&month=&day=&hour=&minute=&duration=&wday_from=&wday_to=&time_from=&time_to=&tz=America%2FChicago&tfc=range+%3D+start_of_today+-+1d+to+now%3B&rtype=Delay&graph_type=Filled&db_type=Average&x_step=1&interval=60&y_height=100&y_gridlines=5&y_max=&y_max_power=1&x_gridlines=on&legend=on'
urlauth = base_link + jConnectID + dash + jConnectPorS + end_link
print urlauth
realm = 'statseeker'
username = 'admin'
password = '*****'
auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(realm, urlauth, username, password)
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
data = opener.open(urlauth).read()
html = lxml.html.fromstring(data)
imgs = html.cssselect('img.graph')
for x in imgs:
y = 'http://statseeker%s' % (x.attrib['src'])
g = urllib2.urlopen(y).read()
urllib2.urlopen(test.jpg, 'wb').write(g)
print 'http://statseeker%s' % (x.attrib['src'])
with open('statseeker.html', 'a') as f:
f.write(y)
Result:
C:\Users\user\Documents\Scripting>python test.py
Enter ID:4050
Enter 1 for Primary 2 for Secondary:1
http://statseeker/cgi/nim-report?rid=42237&command=Graph&mode=ping&list=jc-4050-
1&tfc_fav=range+%3D+start_of_today+-+1d+to+now%3B&year=&month=&day=&hour=&minute
=&duration=&wday_from=&wday_to=&time_from=&time_to=&tz=America%2FChicago&tfc=ran
ge+%3D+start_of_today+-+1d+to+now%3B&rtype=Delay&graph_type=Filled&db_type=Avera
ge&x_step=1&interval=60&y_height=100&y_gridlines=5&y_max=&y_max_power=1&x_gridli
nes=on&legend=on
Traceback (most recent call last):
File "JacksonShowAndSave.py", line 35, in <module>
g = urllib2.urlopen(y).read()
File "C:\Python27\lib\urllib2.py", line 127, in urlopen
return _opener.open(url, data, timeout)
File "C:\Python27\lib\urllib2.py", line 410, in open
response = meth(req, response)
File "C:\Python27\lib\urllib2.py", line 523, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python27\lib\urllib2.py", line 448, in error
return self._call_chain(*args)
File "C:\Python27\lib\urllib2.py", line 382, in _call_chain
result = func(*args)
File "C:\Python27\lib\urllib2.py", line 531, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 401: Authorization Required
C:\Users\user\Documents\Scripting>
How do I fix these errors to pass the Authentication to any web page opened on that website? I thought that any urlopen request would use the same authentication as above.
The Section that is Failing:
y = 'http://statseeker%s' % (x.attrib['src'])
g = urllib2.urlopen(y).read()
urllib2.urlopen(test.jpg, 'wb').write(g)
print 'http://statseeker%s' % (x.attrib['src'])
with open('statseeker.html', 'a') as f:
I built another auth handler for the request:
auth_handler2 = urllib2.HTTPBasicAuthHandler()
auth_handler2.add_password(realm, y, username, password)
opener2 = urllib2.build_opener(auth_handler2)
urllib2.install_opener(opener2)
link = urllib2.Request(y)
response = urllib2.urlopen(link)
output = open('out2.jpg','wb')
output.write(response.read())
output.close()

Resources