OpenSSL - Raspberry Pi4 failing to communicate to server on windows system - python-3.x

As the title states I get an error trying to communicate from a Raspberry PI 4 and windows system using an SSL connection.
The current client script works perfectly on windows to a server application running on windows.
This is the client script:
from OpenSSL import SSL
import sys, os, select, socket, time
ctx = SSL.Context(SSL.SSLv23_METHOD)
sock = SSL.Connection(ctx, socket.socket(socket.AF_INET, socket.SOCK_STREAM))
sock.connect(('10.0.0.84', 443))
stri = 'hello\r\n'
tobyte = bytes(stri,'utf-8')
print(tobyte)
buf = sock.recv(4096)
while True:
sock.send(tobyte)
time.sleep(60)
The error I get on Raspberry Pi 4:
Traceback (most recent call last): File
"/home/pi/Documents/scripts/openssltest.py", line 15, in
buf = sock.recv(4096)
File "/usr/lib/python3/dist-packages/OpenSSL/SSL.py", line 1791, in recv
self._raise_ssl_error(self._ssl, result) File "/usr/lib/python3/dist-packages/OpenSSL/SSL.py", line 1647, in
_raise_ssl_error
_raise_current_error() File "/usr/lib/python3/dist-packages/OpenSSL/_util.py", line 54, in
exception_from_error_queue
raise exception_type(errors) OpenSSL.SSL.Error: [('SSL routines', 'ssl_choose_client_version', 'unsupported protocol')]
I have the same version of OpenSSL running on the Raspberry Pi and Windows PC
One thing I noticed in Visual Studio Code (for the Raspberry Pi) is that the sock.send() is not recognised but sock.sendall() is. VSC in windows is showing sock.send() as an option.
I am using OpenSSL version 1.1.1k and python 3.7.3 on the Raspberry PI. OpenSSL 1.1.1k and python 3.9.6 on windows. All devices are running on the same network
I have not written the server application but uses a self signed certificate.
Any suggestions would be much appreciated

Adding #mti2935 comment as the answer as this fixed my problem. Just to help anyone in the future
('SSL routines', 'ssl_choose_client_version', 'unsupported protocol')
usually means the server will only allow connections using certain
SSL/TLS protocols (e.g. TLS1.2 or above), but the client does not
support any of the protocols that the server requires (e.g. client
supports TLS1.0 or lower). Can you try connecting to the server from
the command line of the PI, by doing openssl s_client -connect
10.0.0.84:443? Does it connect? If so, what protocol does it use?
The problem was that my client was using a protocol that the server did not support SSLv23_METHOD. Changed the protocol to SSL.TLSv1_METHOD.
Corrected code:
from OpenSSL import SSL
import sys, os, select, socket, time
ctx = SSL.Context(SSL.TLSv1_METHOD)
sock = SSL.Connection(ctx, socket.socket(socket.AF_INET, socket.SOCK_STREAM))
sock.connect(('10.0.0.84', 443))
stri = 'hello\r\n'
tobyte = bytes(stri,'utf-8')
print(tobyte)
buf = sock.recv(4096)
print(buf)
while True:
sock.send(tobyte)
time.sleep(5)

Related

Connect TCP socket failed with: 111 (No connection between python in linux and twincat in windows)

I have been trying to get a connection between TwinCAT 3 on Windows and Python on Ubuntu. I already have the connection between Twincat 3 Windows and Python Windows working, but not to Ubuntu. I have a virtual machine set up through Oracle VM Virtualbox. I tried many things but so far had no success in creating the connection.
I have a bridged adapter network and tried to open the port of the IP address of the virtual machine in linux through sudo ufw allow
I have the following code:
pyads.open_port()
pyads.add_route('10.11.104.206.1.1','127.0.0.1')
pyads.close_port()
plc = pyads.Connection('10.11.104.206.1.1', 851)
plc.open()
try:
# try to connect to PLC
plc.read_state()
print('Connection succeeded')
except Exception:
print('Connection failed')
And this is the error I get:
2020-11-22T22:45:46+0100 Error: Connect TCP socket failed with: 111
Traceback (most recent call last):
File "/home/laurence/ws_moveit/devel/lib/moveit_tutorials/move_panda_LKO.py", line 15, in <module>
exec(compile(fh.read(), python_script, 'exec'), context)
File "/home/laurence/ws_moveit/src/moveit_tutorials/doc/move_panda_LKO/scripts/move_panda_LKO.py", line 64, in <module>
pyads.add_route('10.11.104.206.1.1','127.0.0.1')
File "/usr/local/lib/python3.8/dist-packages/pyads/ads.py", line 188, in add_route
return adsAddRoute(adr.netIdStruct(), ip_address)
File "/usr/local/lib/python3.8/dist-packages/pyads/pyads_ex.py", line 155, in wrapper
return fn(*args, **kwargs)
File "/usr/local/lib/python3.8/dist-packages/pyads/pyads_ex.py", line 177, in adsAddRoute
raise ADSError(error_code)
pyads.pyads_ex.ADSError: ADSError: target port not found ADS Server not started (6).
These are the netid/IPadresses.
-
-
-
CX-52EE70
169.254.64.202
5.82.238.112.1.1
TCP_IP
-
LEENLAPTOP19
127.0.0.1
10.11.104.206.1.1
TCP_IP
I have tried combinations with other netid/IP addresses so sometimes I get other errors (110,113) but usually 111 which means connection refused, but I do not know what I am doing wrong. Any ideas?
Please make sure the plc runtime is running (a plc program) when you connect. If the plc is in config or exception mode the plc runtime ads port (851 (or 801 for TC2)) is not present. That is what the ADS error 6 target port not found is trying to tell us.

AttributeError: 'socket' object has no attribute 'recive'

I have been working on a project with a raspberry pi. I'm trying to communicate between the laptop and the raspberry pi using sockets.
I was trying a youtube tutorial and keep getting this error
Traceback (most recent call last):
File "", line 1, in
s.recive(1024)
AttributeError: 'socket' object has no attribute 'recive'
after failing to run the script I tried typing the code line by line on python shell
import socket
socket.recv(1024)
but still getting the same error
Can anyone explain whats the problem?
Mind first reading the api and examples?
The correct syntax is buffer = socket.recv(1024)
as noted at socket — Low-level networking interface
But also it seems you are missing other basic flow, like the fact that you have to create the connection first.
Take some time first reading examples of the right use of sockets and then start coding.
A good start would be TutorialsPoint - Python 3 - Network Programming
Problem solved with the help of tutorialspoint.com
Simple server
#!/usr/bin/python3 # This is server.py file
import socket
# create a socket object
serversocket = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
port = 9999
# bind to the port
serversocket.bind((host, port))
# queue up to 5 requests
serversocket.listen(5)
while True:
# establish a connection
clientsocket,addr = serversocket.accept()
print("Got a connection from %s" % str(addr))
msg = 'Thank you for connecting'+ "\r\n"
clientsocket.send(msg.encode('ascii'))
clientsocket.close()
Simple client
# create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
port = 9999
# connection to hostname on the port.
s.connect((host, port))
# Receive no more than 1024 bytes
msg = s.recv(1024)
s.close()
print (msg.decode('ascii'))

Python 3.6.4 can connect to Slack locally (via slackclient) but in Azure it cannot

Python 3.6.4 (32 bit x86) using slackclient locally connects to the RTM API and is able to listen in on slack channel changes. That same code running in Azure (64 bit AMD) does not work.
I've made sure that the Azure python install is as close to my local machine as possible. There are a few package discrepancies (see below) though this should not be the issue since these are not being used:
Azure vs. Local Machine
* numpy 1.15.3 vs. numpy 1.16.0
* pyodbc 4.0.24 vs. pyodbc 4.0.25
* pytz 2018.7 vs. pytz 2018.9
* setuptools 38.5.2 vs. setuptools 28.8.0
I've looked at the following links though I am not sure they will help. Some of the instructions for setting up a proxy in Azure are no longer valid (off by several steps). Recently Azure stopped serving a web app of mine (C#/ASP) when I changed the (totally unrelated Python) setting below.
Application settings->General settings->Python version (from Off to 3.4)
It was a real pain to get it back. I think that I will need a proxy though I would imagine Azure should provide better instructions for this. I am somewhat of an Azure newb though not new enough to start changing things willy nilly!
make Python 3.x Slack (slackclient) use a corporate proxy
Custom Slack Bot cannot connect
https://learn.microsoft.com/en-us/azure/active-directory/manage-apps/application-proxy-configure-connectors-with-proxy-servers
https://learn.microsoft.com/en-us/azure/azure-functions/functions-proxies
import time, logging, os
from slackclient import SlackClient
from datetime import datetime
def main():
#proxies = dict(https="proxy.azure.com:443", http="proxy.azure.com:443")
sc = SlackClient(BOT_TOKEN)
CHANNEL_ID = "some channel id"
logger.debug("Listening to channel '{0}' with id '{1}' for the following actions: ".format(CHANNEL_NAME, CHANNEL_ID))
if sc.rtm_connect():
logger.debug("Connected to Slack!")
while True:
# Read latest messages
# If activity is in CHANNEL_ID do something
else:
logger.debug("Couldn't connect to slack")
On my local machine I get the following (I cut out some of the code):
DEBUG - Listening to channel 'news' with id 'CFDQ3BXYZ' for the following actions:
DEBUG - message_replied
DEBUG - message_deleted
DEBUG - message_changed
DEBUG - Connected to Slack!
However, in Azure, I get the following:
DEBUG - Listening to channel 'news' with id 'CFDQ3BXYZ' for the following actions:
DEBUG - message_replied
DEBUG - message_deleted
DEBUG - message_changed
DEBUG - Couldn't connect to Slack!
The Azure error message is as follows:
01-14-2019 23:17:26, urllib3.connectionpool, DEBUG, Starting new HTTPS connection (1): slack.com:443
01-14-2019 23:17:26, urllib3.connectionpool, DEBUG, https://slack.com:443 "POST /api/rtm.start HTTP/1.1" 200 18349
01-14-2019 23:17:26, slackclient.client, WARNING, Failed RTM connect
Traceback (most recent call last):
File "D:\home\python364x64\lib\site-packages\slackclient\server.py", line 192, in connect_slack_websocket
http_proxy_auth=proxy_auth,
File "D:\home\python364x64\lib\site-packages\websocket\_core.py", line 511, in create_connection
websock.connect(url, **options)
File "D:\home\python364x64\lib\site-packages\websocket\_core.py", line 220, in connect
options.pop('socket', None))
File "D:\home\python364x64\lib\site-packages\websocket\_http.py", line 120, in connect
sock = _open_socket(addrinfo_list, options.sockopt, options.timeout)
File "D:\home\python364x64\lib\site-packages\websocket\_http.py", line 164, in _open_socket
sock.setsockopt(*opts)
OSError: [WinError 10042] An unknown, invalid, or unsupported option or level was specified in a getsockopt or setsockopt call
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:\home\python364x64\lib\site-packages\slackclient\client.py", line 140, in rtm_connect
self.server.rtm_connect(use_rtm_start=with_team_state, **kwargs)
File "D:\home\python364x64\lib\site-packages\slackclient\server.py", line 159, in rtm_connect
self.connect_slack_websocket(self.ws_url)
File "D:\home\python364x64\lib\site-packages\slackclient\server.py", line 200, in connect_slack_websocket
raise SlackConnectionError(message=str(e))
slackclient.server.SlackConnectionError: [WinError 10042] An unknown, invalid, or unsupported option or level was specified in a getsockopt or setsockopt call
01-14-2019 23:17:26, Slack_bot_listener, DEBUG, Couldn't connect to slack
Any help will be greatly appreciated!
It appears that WebJobs are restricted to port 80 only. So there is no way to open up ports, etc. on Azure WebJobs at least at this time (see article/post below). So it appears that a VM or some other route is the way to proceed.
Can I open ports on Azure Websites?

Socket connection problem: meet [socket.gaierror] when using socket.connect

I'm learning python socket. I tried to connect to a web, but it showed connection error.
I tried to use telnet to connect to the server and it works fine. I also tried another computer and it also works. I'm using MAC OS Mojave, so I don't know what's wrong with the computer. Could anyone give some suggestions?
The code is like this:
import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('data.pr4e.org', 80))
cmd = 'GET http://data.pr4e.org/romeo.txt HTTP/1.0\r\n\r\n'.encode()
mysock.send(cmd)
while True:
data = mysock.recv(512)
if len(data) < 1:
break
print(data.decode(),end='')
mysock.close()
The error shows:
Traceback (most recent call last):
File "socket1.py", line 4, in <module>
mysock.connect(('data.pr4e.org', 80))
socket.gaierror: [Errno 8] nodename nor servname provided, or not known
It expected to give the metadata and the data in the website.
Thanks very much in advance!!!!

Why a simple UDP Socket gives me OSError: WinError 10048?

I am trying to write a simple socket (server side) to communicate with a process on the same machine, using UDP as Transport Protocol. This is the code:
from socket import *
serverPortS = 1234
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind(('localhost', serverPortS))
print ('Il server e pronto a ricevere')
messageS, clientAddressS =serverSocket.recvfrom(2048)
modifiedMessageS = messageS.upper()
serverSocket.sendto(modifiedMessageS, clientAddressS)
serverSocket.close()
The console gives me the error, just launching the server (no client yet):
Traceback (most recent call last):
File "E:\Laboratorio Python\udp_server.py", line 12, in <module>
serverSocket.bind(('localhost', serverPortS))
OSError: [WinError 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted
I don't know how to fix it or how does it means, and searching on the Web I found more complex problem; would love to hear a possible solution!

Resources