This question already has answers here:
Python FTP implicit TLS connection issue
(7 answers)
Closed 3 years ago.
I am trying to connect to connect to a FTP site to download some files:
from ftplib import FTP_TLS
from ftplib import FTP
import ssl
import ftplib
FTP_TLS.ssl_version = ssl.PROTOCOL_TLSv1_2
ftps = FTP_TLS(timeout=100)
ftps.set_debuglevel(2)
ftps.connect('IP', port)
ftps.auth()
ftps.prot_p()
ftps.login('username', 'password')
The program tries for sometime before it fails with the following error:
get ''
Traceback (most recent call last): File "FTP.py", line 12, in
ftps.connect('IP', port) File "C:_data\learn\Miniconda\lib\ftplib.py", line 155, in connect
self.welcome = self.getresp() File "C:_data\learn\Miniconda\lib\ftplib.py", line 236, in getresp
resp = self.getmultiline() File "C:_data\learn\Miniconda\lib\ftplib.py", line 222, in getmultiline
line = self.getline() File "C:_data\learn\Miniconda\lib\ftplib.py", line 210, in getline
raise EOFError EOFError
I am not sure what the cause of this error is . I can connect to the ftp server using the same details with a FTP client (FileZilla). Can anyone point out if there is issue with my code and possible options to fix this.
Edit 1
As suggested below posting FileZilla logs :
Status: Connecting to IP:Port...
Status: Connection established, initializing TLS...
Status: Verifying certificate...
Status: TLS connection established, waiting for welcome message...
Status: Logged in
Status: Retrieving directory listing...
Status: Directory listing of "/" successful
FIleZilla explicitly pops up a certificate which I press OK on my desktop after which the connection is established. I am assuming the failure here is because my code doesn't accept the certificate. Any help is appreciated.
For anyone looking for an answer, the issue was that implicit FTPS connections need the socket to be ssl wrapped automatically.I used the below piece of code written by George Leslie-Waksman
import ftplib
import ssl
class ImplicitFTP_TLS(ftplib.FTP_TLS):
"""FTP_TLS subclass that automatically wraps sockets in SSL to support implicit FTPS."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._sock = None
#property
def sock(self):
"""Return the socket."""
return self._sock
#sock.setter
def sock(self, value):
"""When modifying the socket, ensure that it is ssl wrapped."""
if value is not None and not isinstance(value, ssl.SSLSocket):
value = self.context.wrap_socket(value)
self._sock = value
If this resolves your issue, kindly upvote the original answer -->https://stackoverflow.com/a/36049814/392233
Related
I'm trying to do a FTPS (or FTP) connection to a FTP server. This is done on Python 3.8.5 32 bit via Visual Studio Code.
Here is the code:
import ftplib
session = ftplib.FTP_TLS('server address')
#session.connect ('server address', 991)
session.login(user='username',passwd='password')
#session.prot_p()
session.set_pasv(True)
session.cwd("files")
print(session.pwd())
filename = "ftpTest.txt"
my_file = open('filepath\\ftpTest.txt', 'wb') # Open a local file to store the downloaded file
session.retrbinary('RETR ' + filename, my_file.write, 1024)
session.quit()
I am able to get the session.pwd (which display /files) but the connection timeout at line 11 (session.retrbinary) in approximately 22 sec with the following error:
Exception has occurred: TimeoutError
[WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
I had tried setting session.set_pasv to both True and False following Python ftplib timing out. Setting it True raised the TimeoutError and setting it False raise the following error at line 11:
Exception has occurred: error_perm
500 Illegal PORT command
and also tried setting a different port (991) following Python SSL FTP connection timing out and it raised the Timeout Error at line 3.
Using FTP without TLS raised the following error at line 4 (session.login):
Exception has occurred: error_perm
530 Non-anonymous sessions must use encryption.
Turning off my McAfee LiveSafe firewall didnt help either.
Btw file transfer works with Filezilla, was able to freely transfer.
Setting up the secure data connection and changing the session af to INET6 seemed to work for me. This was suggested to me by a colleague, and as to why it works is beyond me. If anyone can provide a proper explanation, please do.
Code:
session.login(user='username',passwd='password')
session.prot_p()
session.af = socket.AF_INET6
I'm using the this module [1]: https://github.com/kragniz/python-etcd3 to communicate with etcdv3. I have created all the necessary certs and tested client secure connection with curl. However atempting a simple get operation fails. Code snippet and exception below.
import etcd3
ca='/Users/PKI/etcd/ca.pem'
cert='/Users/PKI/etcd/client.pem'
key='/Users/PKI/etcd/client-key.pem'
etcd = etcd3.client(ca_cert=ca, cert_cert=cert, cert_key=key)
etcd.get('foo')
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
status = StatusCode.UNAVAILABLE
details = "failed to connect to all addresses"
debug_error_string = "{"created":"#1594500226.366466000","description":"Failed to pick subchannel","file":"src/core/ext/filters/client_channel/client_channel.cc","file_line":3948,"referenced_errors":[{"created":"#1594500226.366461000","description":"failed to connect to all addresses","file":"src/core/ext/filters/client_channel/lb_policy/pick_first/pick_first.cc","file_line":394,"grpc_status":14}]}"
>
> /usr/local/lib/python3.8/site-packages/etcd3/client.py(46)handler()
-> return f(*args, **kwargs)
I haven't done much with grpc so I'm not sure if there are options I should pass to init the etcd3 client.
I'm running Rasbian Buster and use Msmtp to send emails from the command line and it works just fine.
When I try to send emails using Python it fails miserably, I've tried various python examples from the net, e.g.
# Sending Email Alerts via Zoho
#
#
import smtplib
server = smtplib.SMTP_SSL('smtp.zoho.com',port=465) #server for sending the email
server.ehlo() # simple starting of the connection
server.login('test_email#zoho.com','pwd_12345') # login credentials and password
msg = """From:test_email#zoho.com
Subject: Test Email \n
To: recipient_email#gmail.com \n"""
# This is where the email content goes. It could be information about the error, time of day, where in the script, etc.
server.sendmail('test_email#zoho.com','recipient_email#gmail.com',msg) # this is where the email is sent to the recipient
server.quit() # exit the connection
... but I unfortunately I always get the following error:
Traceback (most recent call last):
File "/usr/lib/python3.7/smtplib.py", line 387, in getreply
line = self.file.readline(_MAXLINE + 1)
File "/usr/lib/python3.7/socket.py", line 589, in readinto
return self._sock.recv_into(b)
ConnectionResetError: [Errno 104] Connection reset by peer
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/pi/test_email_python_06.py", line 6, in <module>
server = smtplib.SMTP('smtpauths.bluewin.ch',port=465) #server for sending the email
File "/usr/lib/python3.7/smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python3.7/smtplib.py", line 338, in connect
(code, msg) = self.getreply()
File "/usr/lib/python3.7/smtplib.py", line 391, in getreply
+ str(e))
smtplib.SMTPServerDisconnected: Connection unexpectedly closed: [Errno 104] Connection reset by peer
As a newbee any hint would be appreciated.
Thanks!
This issue has been solved!
My ISP uses SSL on port 465 and my command line email client MSMTP works just great using that.
As I was so desperate, so that I startet to play around and just use port 25 and "Bingo" the sending of emails works now just fine, the funny part is that my ISP suggest to use port 465.
I have been trying to connect to broker port 1884. But it gets every time connection refused error.
def __init__(self, host='127.0.0.1', port=8080, broker_address='127.0.0.1', broker_port=1884, start_config=None):
self.app = Bottle()
"""Create the http service app"""
self.broker = SimpleBroker(address=broker_address, port=broker_port)
self.broker.start()
"""Create and run the broker (broker always runs as a daemon)"""
self.brokerAddress = broker_address
"""address of the API broker - usually identical to own address, but others for testing"""
self.mqttc = Client()
"""mqtt client for publishing messages to API broker - delivered to edge and preprocessing layer"""
self.mqttc.connect(host=broker_address, port=broker_port)
"""connect to the broker upon startup"""
and then the execution part:
if __name__ == "__main__":
myAPI = APIServer('127.0.0.1', 8080, '127.0.0.1', start_config='all wheels')
myAPI.start()
The error message:
Traceback (most recent call last):
File "/root/PycharmProjects/Thesis2019/API/APIServer.py", line 328, in <module>
myAPI = APIServer('127.0.0.1', 8080, '127.0.0.1', start_config='all wheels')
File "/root/PycharmProjects/Thesis2019/API/APIServer.py", line 42, in __init__
self.mqttc.connect(host=broker_address, port=broker_port)
File "/root/PycharmProjects/Thesis2019/venv/lib/python3.6/site-packages/paho/mqtt/client.py", line 839, in connect
return self.reconnect()
File "/root/PycharmProjects/Thesis2019/venv/lib/python3.6/site-packages/paho/mqtt/client.py", line 962, in reconnect
sock = socket.create_connection((self._host, self._port), source_address=(self._bind_address, 0))
File "/usr/lib/python3.6/socket.py", line 724, in create_connection
raise err
File "/usr/lib/python3.6/socket.py", line 713, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused
On the other hand when i execute it in debug mode, i got :
[2019-04-09 23:43:05,243] :: WARNING :: hbmqtt.broker.plugins.topic_taboo :: 'topic-check' section not found in context configuration
[2019-04-09 23:43:05,243] :: INFO :: transitions.core :: Exited state new
[2019-04-09 23:43:05,244] :: INFO :: transitions.core :: Entered state starting
[2019-04-09 23:43:05,248] :: INFO :: hbmqtt.broker :: Listener 'default' bind to 127.0.0.1:1884 (max_connections=100)
[2019-04-09 23:43:05,248] :: INFO :: transitions.core :: Exited state starting
[2019-04-09 23:43:05,248] :: INFO :: transitions.core :: Entered state started
Additional to all the connection refused part, it just starts it without problem in debug mode i guess?
The Pycharm is launched with root privilege.
Firewall is checked, and it is disabled.
None of these ports are open, checked it with lsof.
I use Python 3.6, hbmqtt 0.9.5
It works on Windows, but not on Mac or Linux
Why i have connection refused error each time i try to execute it ? What am i missing?
Thanks in advance for the ideas.
The solution is:
The Mosquitto default port connection is set to 1883 in the config file, where I was trying to connect through port 1884.
I thought that, this properties are set whenever you change the number. Which is not correct since they are static. not changing dynamically.(sure there is a way too.)
Apart from that, the API Broker and Broker port numbers have to be swapped. I don't know why but windows can bind on top of it without problems. but Mac OS and Linux are throwing Connection Refused error.
The Pycharm is launched with root privilege.
Firewall is checked, and it is disabled.
None of these ports are open, checked it with lsof.
Check config file of the Mosquitto, if the allow_annoymous is True
Control your port connections 10 times.
These are still valid check before going crazy. %90 of the problems are caused because of one of these issues.
If you have further help or questions, you can comment in here and I will try to help for future inquiries.
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?