ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get issuer certificate (_ssl.c:1123) - ssl

import time
import logging
import paho.mqtt.client as mqtt
from OpenSSL import SSL
import os
import ssl
log = logging.getLogger('RemoTV.hardware.l298n')
logging.basicConfig(level=logging.DEBUG)
sleeptime = 0.2
rotatetimes = 0.4
StepPinForward = None
StepPinBackward = None
StepPinLeft = None
StepPinRight = None
def setup(robot_config):
global StepPinForward
global StepPinBackward
global StepPinLeft
global StepPinRight
global sleeptime
global rotatetimes
sleeptime = robot_config.getfloat('l298n', 'sleeptime')
rotatetimes = robot_config.getfloat('l298n', 'rotatetimes')
log.debug("GPIO mode : %s", str(GPIO.getmode()))
GPIO.setwarnings(False)
GPIO.cleanup()
if robot_config.getboolean('tts', 'ext_chat'): # ext_chat enabled, add motor commands
extended_command.add_command('.set_rotate_time', set_rotate_time)
extended_command.add_command('.set_sleep_time', set_sleep_time)
# TODO passing these as tuples may be unnecessary, it may accept lists as well.
StepPinForward = tuple(map(int, robot_config.get('l298n', 'StepPinForward').split(',')))
StepPinBackward = tuple(map(int, robot_config.get('l298n', 'StepPinBackward').split(',')))
StepPinLeft = tuple(map(int, robot_config.get('l298n', 'StepPinLeft').split(',')))
StepPinRight = tuple(map(int, robot_config.get('l298n', 'StepPinRight').split(',')))
def on_message(client, userdata, message):
payload = message.payload.decode('utf-8')
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.OUT)
GPIO.setup(11, GPIO.OUT)
GPIO.setup(15, GPIO.OUT)
GPIO.setup(16, GPIO.OUT)
GPIO.setup(36, GPIO.OUT)
GPIO.setup(35, GPIO.OUT)
if payload == 'f':
GPIO.output(12, GPIO.HIGH)
time.sleep(sleeptime)
GPIO.output(12, GPIO.LOW)
if payload == 'b':
GPIO.output(11, GPIO.HIGH)
time.sleep(sleeptime)
GPIO.output(11, GPIO.LOW)
if payload == 'l':
GPIO.output(15, GPIO.HIGH)
time.sleep(sleeptime * rotatetimes)
GPIO.output(15, GPIO.LOW)
if payload == 'r':
GPIO.output(16, GPIO.HIGH)
time.sleep(sleeptime * rotatetimes)
GPIO.output(16, GPIO.LOW)
if payload == 'z':
GPIO.output(36, GPIO.HIGH)
time.sleep(sleeptime * rotatetimes)
GPIO.output(36, GPIO.LOW)
if payload == 'x':
GPIO.output(35, GPIO.HIGH)
time.sleep(sleeptime * rotatetimes)
GPIO.output(35, GPIO.LOW)
ca_cert_path = "fullchain1.pem"
client = mqtt.Client()
# Set the TLS/SSL parameters for the client
client.tls_set(
ca_certs=ca_cert_path,
certfile='cert1.pem',
keyfile='privkey1.pem',
cert_reqs=ssl.CERT_REQUIRED,
tls_version=SSL.SSLv23_METHOD
)
client.username_pw_set(username="not posting my passwd", password="lol ahah")
# client.tls_insecure_set(False)
client.on_message = on_message
client.connect('clawclan.co.uk',8083)
client.subscribe("clawmachine/controls")
client.loop_forever()
Thats the python code that I'm using to connect to my mqtt broker, I have been through multiple issues as tlsv1.3 isn't supported by pyopenssl or something, I have spent days trying to get this code to work and fixing issues, and this one has been making me lose my mind hahahahahahahahah.
My mosquitto config:
allow_anonymous false
password_file /home/pi/claw/passwordfile.txt
listener 1883 localhost
listener 8883
certfile /home/pi/claw/cert1.pem
cafile /home/pi/claw/chain1.pem
keyfile /home/pi/claw/privkey1.pem
listener 8083
protocol websockets
certfile /home/pi/claw/cert1.pem
cafile /home/pi/claw/chain1.pem
keyfile /home/pi/claw/privkey1.pem
This is the error I'm getting when I run the .py file
pi#raspberrypi:~/claw $ python3 cac.py
Traceback (most recent call last):
File "/home/pi/claw/cac.py", line 102, in <module>
client.connect('clawclan.co.uk', 8083)
File "/home/pi/.local/lib/python3.9/site-packages/paho/mqtt/client.py", line 914, in connect
return self.reconnect()
File "/home/pi/.local/lib/python3.9/site-packages/paho/mqtt/client.py", line 1073, in reconnect
sock.do_handshake()
File "/usr/lib/python3.9/ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get issuer certificate (_ssl.c:1123)
If u want me to add anything, just ask, as I will be just checking for responses, for the rest of the day

Related

BROWNIE ISSUES:NONETYPE

5:31:35 in the video, Typed the codes in exactly the same way and ran it but I keep getting this error
INFO: Could not find files for the given pattern(s).
Brownie v1.18.1 - Python development framework for Ethereum
File "C:\Users\Morounfola\AppData\Local\Programs\Python\Python38\lib\site-packages\brownie_cli_main_.py", line 64, in main
importlib.import_module(f"brownie._cli.{cmd}").main()
File "C:\Users\Morounfola\AppData\Local\Programs\Python\Python38\lib\site-packages\brownie_cli\run.py", line 42, in main
active_project.load_config()
File "C:\Users\Morounfola\AppData\Local\Programs\Python\Python38\lib\site-packages\brownie\project\main.py", line 462, in load_config
_load_project_config(self._path)
File "C:\Users\Morounfola\AppData\Local\Programs\Python\Python38\lib\site-packages\brownie_config.py", line 222, in _load_project_config
and "cmd_settings" in values
TypeError: argument of type 'NoneType' is not iterable
This is the code;
from brownie import FundMe, MockV3Aggregator, network, config
from scripts.helpful_scripts import get_account
def deploy_fund_me():
account = get_account()
# pass the pricefeed address to our fund me contract
# if we are on a persistent address like rinkeby, use the associated address
# otherwise, deploy mocks
if network.show_active != "development":
price_feed_address = config["networks"][network.show_active()][
"eth_usd_price_feed"
]
else:
print(f"The active network is{network.show_active()}")
print("Deploying Mocks...")
mock_aggregator = MockV3Aggregator.deploy(
18, 200000000000000000000, {"from": account}
)
price_feed_address = mock_aggregator.address
print("Mocks Deployed!")
fund_me = FundMe.deploy(price_feed_address, {"from": account}, publish_source=True)
print(f"Contract deployed to {fund_me.address}")
def main():
deploy_fund_me()
I answered this here:
File "brownie/_config.py", line 222, in _load_project_config and "cmd_settings" in values TypeError: argument of type 'NoneType' is not iterable
I had the same exact issue and it was because my brownie-config.yml file was incorrect. You can't have any blank variables in your config file.
Under networks I had:
networks:
rinkeby:
eth_usd_price_feed: "0x8A753747A1Fa494EC906cE90E9f37563A8AF630e"
verify: True
kovan:
mainnet:
having 'kovan' and 'mainnet' set to blank caused the error.
The solution is to either delete those two lines or comment them out like this:
networks:
rinkeby:
eth_usd_price_feed: "0x8A753747A1Fa494EC906cE90E9f37563A8AF630e"
verify: True
# kovan:
# mainnet:

How to solve the consumer error in Rabbitmq using python

when I run Consumer.py for headersExchange in rabbitmq using python,it is getting error like below
I have mentioned consumer and publish program below
Traceback (most recent call last):
File "headersConsumer.py", line 32, in <module>
main()
File "headersConsumer.py", line 14, in main
channel.exchange_declare(exchange = 'headers_logs',exchange_type='headers',durable=True)
File "C:\Python38\lib\site-packages\pika\adapters\blocking_connection.py", line 2387, in
exchange_declare
self._flush_output(declare_ok_result.is_ready)
File "C:\Python38\lib\site-packages\pika\adapters\blocking_connection.py", line 1339, in
_flush_output
raise self._closing_reason # pylint: disable=E0702
pika.exceptions.ChannelClosedByBroker: (406, "PRECONDITION_FAILED
- inequivalent arg 'type' for exchange 'headers_logs' in vhost '/': received 'headers' but
current is 'fanout'")
I have written consumer code like this
#!/usr/bin/env python
import pika, sys, os
def main():
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange = 'headers_logs',exchange_type='headers',durable=True)
channel.queue_declare(queue = "HeaderQueue1", durable=True)
channel.queue_bind(exchange = 'headers_logs', queue="HeadersQueue1", routing_key='',
arguments={'x-match': 'any', 'key1': 'one', 'key2': 'two'})
def callback(ch, method, properties, body):
print(" [x] %r" % body.decode())
print(' [*] Waiting for logs. To exit press CTRL+C')
channel.basic_consume(
queue="HeadersQueue1", on_message_callback=callback, auto_ack=True)
channel.start_consuming()
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print('Interrupted')
try:
sys.exit(0)
except SystemExit:
os._exit(0)
I have written publish program likethis
import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='headers_logs',exchange_type='headers')
message = ' '.join(sys.argv[1:]) or "Hello World!"
channel.basic_publish((exchange='headers_logs',routing_key="",body=message,properties=pika.BasicProperties(
delivery_mode = 2, # make message persistent
headers = {'key1':'one', 'key2': 'three'}
))
print(" [x] Sent %r" % message)
connection.close()
I am not understanding this error,Can anyone please suggest this error
PRECONDITION_FAILED means that you declared an exchange with set of parameters then you are trying to create the same queue name using different parameters.
in your case:
headers_logs' in vhost '/': received 'headers' but
current is 'fanout'")
so you are trying to change the exchange type from fanout to headers
Se here for more detail (this is for the queues but exchanges work in the same way).
Before a queue can be used it has to be declared. Declaring a queue
will cause it to be created if it does not already exist. The
declaration will have no effect if the queue does already exist and
its attributes are the same as those in the declaration. When the
existing queue attributes are not the same as those in the declaration
a channel-level exception with code 406 (PRECONDITION_FAILED) will be
raised.

python3.5 paramiko failed with hostname

Please help me to correct my script. My script checks the ssh login of a host and displays success/failure based on result. It fails when I give wrong hostname.
Code is as of below :
[root#test1 script]# cat param.py
import multiprocessing
import paramiko
import random
import threading
import time
host_name = "test2"
print ("Checking hostname :"+str(host_name))
file = open('output_file','a')
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(host_name, username='root', password='test')
print ("success")
file.write("success:"+str(host_name+"\n"))
except paramiko.SSHException:
print ("Connection Failed")
file.write("failed:"+str(host_name+"\n"))
quit()
stdin,stdout,stderr = ssh.exec_command("hostname&&uptime")
for line in stdout.readlines():
print (line.strip())
ssh.close()
It works fine when the correct username/password given :
[root#test1 script]# python3 param.py
Checking hostname :test2
success
test2
12:31:49 up 83 days, 2:56, 2 users, load average: 0.00, 0.01, 0.05
It works fine when the wrong password is given. I have changed the password to a wrong one in the script and it says connection failed as expected.
root#test1 script]# python3 param.py
Checking hostname :test2
Connection Failed
Now my question, when I change the hostname to something doenot exist, paramiko fails and lot of errors pop up.
[root#test1 script]# python3 param.py
Checking hostname :invalidtest2
Traceback (most recent call last):
File "param.py", line 16, in <module>
ssh.connect(host_name, username='root', password='test')
File "/root/usr/local/lib/python3.5/site-packages/paramiko/client.py", line 301, in connect
to_try = list(self._families_and_addresses(hostname, port))
File "/root/usr/local/lib/python3.5/site-packages/paramiko/client.py", line 199, in _families_and_addresses
hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM)
File "/root/usr/local/lib/python3.5/socket.py", line 728, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known
How can I get message that the connection failed ? I'm using python3.5
It is not good idea to keep the passwords stored in the script itself. Modified the script so that it takes the hostnames from a file and writes the output to different files
#!/bin/python3
import threading, time, paramiko, socket, getpass
from queue import Queue
start_time1 = time.time()
locke1 = threading.Lock()
q = Queue()
#Check the login
def check_hostname(host_name, pw_r):
with locke1:
print ("Checking hostname :"+str(host_name)+" with " + threading.current_thread().name)
file_output = open('output_file','a')
file_success = open('success_file','a')
file_failed = open('failed_file','a')
file_error = open('error_file','a')
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(host_name, username='root', password=pw_r)
#print ("Success")
file_success.write(str(host_name+"\n"))
file_success.close()
file_output.write("success: "+str(host_name+"\n"))
file_output.close()
# printing output if required from remote machine
#stdin,stdout,stderr = ssh.exec_command("hostname&&uptime")
#for line in stdout.readlines():
# print (line.strip())
except paramiko.SSHException:
# print ("error")
file_failed.write(str(host_name+"\n"))
file_failed.close()
file_output.write("failed: "+str(host_name+"\n"))
file_output.close()
#quit()
except paramiko.ssh_exception.NoValidConnectionsError:
#print ("might be windows------------")
file_output.write("failed: " + str(host_name + "\n"))
file_output.close()
file_failed.write(str(host_name+"\n"))
file_failed.close()
#quit()
except socket.gaierror:
#print ("wrong hostname/dns************")
file_output.write("error: "+str(host_name+"\n"))
file_output.close()
file_error.write(str(host_name + "\n"))
file_error.close()
ssh.close()
def performer1():
while True:
hostname_value = q.get()
check_hostname(hostname_value,pw_sent)
q.task_done()
if __name__ == '__main__':
print ("This script checks all the hostnames in the input_file with your standard password and write the outputs in below files: \n1.file_output\n2.file_success \n3.file_failed \n4.file_error \n")
f = open('output_file', 'w')
f.write("-------Output of all hosts-------\n")
f.close()
f = open('success_file', 'w')
f.write("-------Success hosts-------\n")
f.close()
f = open('failed_file', 'w')
f.write("-------Failed hosts-------\n")
f.close()
f = open('error_file', 'w')
f.write("-------Hosts with error-------\n")
f.close()
with open("input_file") as f:
hostname1 = f.read().splitlines()
#Read the standard password from the user
pw_sent=getpass.getpass("Enter the Password:")
for i in hostname1:
q.put(i)
#print ("all the hostname : "+str(list(q.queue)))
for no_of_threads in range(3):
t = threading.Thread(target=performer1)
t.daemon=True
t.start()
q.join()
print ("Check output files for results")
print ("completed task in" + str(time.time()-start_time1) + "seconds")

Socket error while connecting to hive through: hiveserver2-client.py

Has anyone experienced this error before when trying to connect to hive.
Sample code used (https://github.com/telefonicaid/fiware-cygnus/blob/master/cygnus-ngsi/resources/hiveclients/python/hiveserver2-client.py):
import sys
import pyhs2
from pyhs2.error import Pyhs2Exception
# get the input parameters
if len(sys.argv) != 6:
print 'Usage: python hiveserver2-client.py <hive_host> <hive_port> <db_name> <hadoop_user> <hadoop_password>'
sys.exit()
hiveHost = sys.argv[1]
hivePort = sys.argv[2]
dbName = sys.argv[3]
hadoopUser = sys.argv[4]
hadoopPassword = sys.argv[5]
# do the connection
with pyhs2.connect(host=hiveHost,
port=hivePort,
authMechanism="PLAIN",
user=hadoopUser,
password=hadoopPassword,
database=dbName) as conn:
# get a client
with conn.cursor() as client:
# create a loop attending HiveQL queries
while (1):
query = raw_input('remotehive> ')
try:
if not query:
continue
if query == 'exit':
sys.exit()
# execute the query
client.execute(query)
# get the content
for row in client.fetch():
print row
except Pyhs2Exception, ex:
print ex.errorMessage
Error displayed:
[centos#test]$ sudo python hiveserver2-client.py computing.cosmos.lab.fiware.org 10000 default USERNAME TOKEN
Traceback (most recent call last):
File "hiveserver2-client.py", line 42, in <module>
database=dbName) as conn:
File "/usr/lib/python2.7/site-packages/pyhs2/__init__.py", line 7, in connect
return Connection(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/pyhs2/connections.py", line 46, in __init__
transport.open()
File "/usr/lib/python2.7/site-packages/pyhs2/cloudera/thrift_sasl.py", line 74, in open
status, payload = self._recv_sasl_message()
File "/usr/lib/python2.7/site-packages/pyhs2/cloudera/thrift_sasl.py", line 92, in _recv_sasl_message
header = self._trans.readAll(5)
File "/usr/lib/python2.7/site-packages/thrift/transport/TTransport.py", line 60, in readAll
chunk = self.read(sz - have)
File "/usr/lib/python2.7/site-packages/thrift/transport/TSocket.py", line 132, in read
message='TSocket read 0 bytes')
thrift.transport.TTransport.TTransportException: TSocket read 0 bytes
can you post your piece of code ? This looks like some auth mechanism or credentials sent are not Valid.
authMechanism= can be "PLAIN" or "KERBEROS" as per your setup .

Twisted error in server with mqtt client

I'm running a Twisted TCP server. Each protocol instance has an mqtt pub/sub client. I've reduced the actual production code to the simplest possible form below. I've stripped out a lot of irrelevant complexity to simplify the bug-finding process. The server works for multiple client connections and produces the data received from the mqtt client, but after any client connects/disconnects/reconnects a few times I get an exception that I haven't been able to understand or trap. I'm hoping that Jean-Paul or someone can point me at the error of my ways.
Once the exception occurs, no new clients can connect to the server. Each new connect attempt produces the exception.
Clients that are already connected continue to receive data ok.
The exception is
Unhandled Error
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/twisted/python/log.py", line 73, in callWithContext
return context.call({ILogContext: newCtx}, func, *args, **kw)
File "/usr/lib/python2.7/dist-packages/twisted/python/context.py", line 118, in callWithContext
return self.currentContext().callWithContext(ctx, func, *args, **kw)
File "/usr/lib/python2.7/dist-packages/twisted/python/context.py", line 81, in callWithContext
return func(*args,**kw)
File "/usr/lib/python2.7/dist-packages/twisted/internet/posixbase.py", line 614, in _doReadOrWrite
why = selectable.doRead()
--- <exception caught here> ---
File "/usr/lib/python2.7/dist-packages/twisted/internet/tcp.py", line 1069, in doRead
transport = self.transport(skt, protocol, addr, self, s, self.reactor)
File "/usr/lib/python2.7/dist-packages/twisted/internet/tcp.py", line 786, in __init__
self.startReading()
File "/usr/lib/python2.7/dist-packages/twisted/internet/abstract.py", line 429, in startReading
self.reactor.addReader(self)
File "/usr/lib/python2.7/dist-packages/twisted/internet/epollreactor.py", line 256, in addReader
_epoll.EPOLLIN, _epoll.EPOLLOUT)
File "/usr/lib/python2.7/dist-packages/twisted/internet/epollreactor.py", line 240, in _add
self._poller.modify(fd, flags)
exceptions.IOError: [Errno 2] No such file or directory
The basic server code is:
(this example will run and does generate the exception)
from twisted.internet import reactor
from twisted.internet.protocol import Factory
from twisted.protocols import basic
from paho.mqtt import client # The most recent version of the legacy Mosquitto client
from random import randint
class MsgReceiver(basic.LineReceiver):
def __init__(self, factory): # new (factory)
self.factory = factory # new (factory)
def connectionMade(self):
self.mqClient = self.startMQ()
if self.mqClient:
self.factory.clients.append(self)
else:
self.transport.loseConnection()
def connectionLost(self, reason):
pass
def lineReceived(self, line):
pass
def on_message(self, mosq, obj, msg):
try:
self.sendLine(msg.payload)
except Exception, err:
print(err.message)
def startMQ(self):
mqName = "-".join(["myAppName", str(randint(0, 99999))])
mqClient = client.Client(mqName)
if mqClient.connect("localhost", 1883, 60) != 0:
print('Could not connect to mq server')
return False
mqClient.on_message = self.on_message
(success, mid) = mqClient.subscribe("myTopic", 0)
if success != 0:
return False
mqClient.loop_start()
return mqClient
class MsgReceiverFactory(Factory):
allow_reuse_address = True
def __init__(self, clients):
self.clients = clients
def buildProtocol(self, addr):
return MsgReceiver(self)
if __name__ == "__main__":
try:
clients = []
reactor.listenTCP(43217, MsgReceiverFactory(clients))
reactor.run()
except Exception, err:
print(err.message)
if reactor.running:
reactor.stop()
A simple client that will induce the error when run twice (the first time it runs fine):
Interesting that if I enable the time.sleep(3) it runs fine and doesn't seem to induce the error
#!/usr/bin/python
from __future__ import print_function
import socket
import time
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("localhost", 43217))
data = s.recv(1024)
print(data)
#time.sleep(3)
s.close()