Ftplib ConnectionRefusedError: [Errno 111] Connection refused (python 3.5) - python

I have a script that should connect to a FTP
from ftplib import FTP
with FTP('IP') as ftp:
ftp.login(user='my user', passwd='my password')
ftp.cwd('/MY_DIR')
ftp.dir()
I have an error :
ConnectionRefusedError: [Errno 111] Connection refused
The ftp is an EC2 with vsftpd
pasv_enable=YES
pasv_min_port=1024
pasv_max_port=1048
pasv_address=IP
pasv_addr_resolve=YES
Already tried :
The code work on other FTP with and without TLS (hosted on 1and1, OVH...)
I tried this script in NodeJS
const ftpClient = require('ftp-client');
const client = new ftpClient({
host: "IP",
port: 21,
user: "My user", // defaults to "anonymous"
password: "My password" // defaults to "#anonymous"
});
client.connect(() => {
client.download('/MY_DIR/file','/tmp/file', (res) => {
console.log(res)
})
});
Works perfectly fine so I exclude a firewall problem
I have tried enable TLS
ssl_enable=YES
require_ssl_reuse=NO
then
sudo service vsftpd restart
and use
FTP_TLS instead of FTP
but did not work
Also I tried disable passive mode by setting
pasv_enable=NO
then
sudo service vsftpd restart
and ftp.set_pasv(False)
didn't work either

Solution
After using filezilla to debug the method, turn out that our FTP returned 0.0.0.0 despite we defined in /etc/vsftpd.conf
pasv_adress=IP
this post helped us : https://www.centos.org/forums/viewtopic.php?t=52408
You have to comment
listen_ipv6=YES
and enable
listen=YES
in /etc/vsftpd.conf
Also you can override the ftplib's class FTP if you can't access to vsftpd.conf of the FTP
class CustomFTP(ftplib.FTP):
def makepasv(self):
if self.af == socket.AF_INET:
host, port = ftplib.parse227(self.sendcmd('PASV'))
else:
host, port = ftplib.parse229(self.sendcmd('EPSV'), self.sock.getpeername())
if '0.0.0.0' == host:
""" this ip will be unroutable, we copy Filezilla and return the host instead """
host = self.host
return host, port
to force the previous host if '0.0.0.0' is send

Related

SocketException: Connection refused (OS Error: Connection refused, errno = 111), address = 127.0.0.1, port = 44164

In my flutter app I am using the flask server for testing purpose. I started my server and run the API url in my flutter app. But SocketException: Connection refused (OS Error: Connection refused, errno = 111), address = 127.0.0.1, port = 44164. error is showing.
var headers = {'Content-Type': 'application/json'};
var request =
http.Request('POST', Uri.parse('http://127.0.0.1:5000/addrec'));
request.body = json.encode({
"name": UploadedName,
"grade": Uploadedgrade,
"loaction": Uploadedlocation,
"like": Uploadedlike,
"admission": Uploadedadmission,
"comments": Uploadedcomments,
"entery_time": UploadeddataentryTime
});
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
} else {
print(response.reasonPhrase);
}
I am using actual android device for app running.
This happens because the localhost (or 127.0.0.1) on the device is only accessible to the device itself.
Solution 1
You can reverse-proxy a localhost port to the Android device/emulator running adb reverse on the command prompt like so:
adb reverse tcp:5000 tcp:5000
Solution 2
Use the machine's IP address where the API is running. Also, the API should be listening to the IP 0.0.0.0 to be accessible outside the localhost.
Supposing the API machine's IP is 192.168.1.123 it's going to be something like:
Uri.parse('http://192.168.1.123:5000/addrec')
Just take care because changing the API to listen to 0.0.0.0 is a security risk as the API is going to be accessible to the outside world.
There is another way as far as you use the python server with dynamic ip 0.0.0.0:port
you can just use linux shell
ipconfig
or windows is
ifconfig
to get ur pc ipaddress and access the port
then you use the
ipaddress:port

FTP Connection has Limited Functions, Can't upload or list directory [duplicate]

I'm trying to connect to an FTP but I am unable to run any commands.
ftp_server = ip
ftp_username = username
ftp_password = password
ftp = ftplib.FTP(ftp_server)
ftp.login(ftp_username, ftp_password)
'230 Logged on'
ftp.nlst()
The ftp.nlst throws this error:
Error:
[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've tested the connection using FileZilla (running on the same machine) and it works fine.
This is FileZilla log:
Status: Connection established, waiting for welcome message...
Status: Insecure server, it does not support FTP over TLS.
Status: Logged in Status: Retrieving directory listing...
Status: Server sent passive reply with unroutable address. Using server address instead.
Status: Directory listing of "/" successful
Status: Server sent passive reply with unroutable address
The above means that the FTP server is misconfigured. It sends its internal network IP to outside network (to the client – FileZilla or Python ftplib), where it is invalid. FileZilla can detect that and automatically fall back to the original IP address of the server.
Python ftplib does not do this kind of detection.
You need to fix your FTP server to return the correct IP address.
If it is not feasible to fix the server (it's not yours and the admin is not cooperative), you can make ftplib ignore the returned (invalid) IP address and use the original address instead by overriding FTP.makepasv:
class SmartFTP(FTP):
def makepasv(self):
invalidhost, port = super(SmartFTP, self).makepasv()
return self.host, port
ftp = SmartFTP(ftp_server)
# the rest of the code is the same
In recent versions of Python (3.6 and newer), ftplib doesn't consider the IP address in PASV response on its own.
Another solution may be to use IPv6. See Python 3.8.5 FTPS connection.
For a different problem with similar consequences, see vsftpd returns 0,0,0,0 in response to PASV.

Cannot list FTP directory using ftplib – but FTP client works

I'm trying to connect to an FTP but I am unable to run any commands.
ftp_server = ip
ftp_username = username
ftp_password = password
ftp = ftplib.FTP(ftp_server)
ftp.login(ftp_username, ftp_password)
'230 Logged on'
ftp.nlst()
The ftp.nlst throws this error:
Error:
[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've tested the connection using FileZilla (running on the same machine) and it works fine.
This is FileZilla log:
Status: Connection established, waiting for welcome message...
Status: Insecure server, it does not support FTP over TLS.
Status: Logged in Status: Retrieving directory listing...
Status: Server sent passive reply with unroutable address. Using server address instead.
Status: Directory listing of "/" successful
Status: Server sent passive reply with unroutable address
The above means that the FTP server is misconfigured. It sends its internal network IP to outside network (to the client – FileZilla or Python ftplib), where it is invalid. FileZilla can detect that and automatically fall back to the original IP address of the server.
Python ftplib does not do this kind of detection.
You need to fix your FTP server to return the correct IP address.
If it is not feasible to fix the server (it's not yours and the admin is not cooperative), you can make ftplib ignore the returned (invalid) IP address and use the original address instead by overriding FTP.makepasv:
class SmartFTP(FTP):
def makepasv(self):
invalidhost, port = super(SmartFTP, self).makepasv()
return self.host, port
ftp = SmartFTP(ftp_server)
# the rest of the code is the same
In recent versions of Python (3.6 and newer), ftplib doesn't consider the IP address in PASV response on its own.
Another solution may be to use IPv6. See Python 3.8.5 FTPS connection.
For a different problem with similar consequences, see vsftpd returns 0,0,0,0 in response to PASV.

WinError 10061 - Target machine refused connection?

I was running this code:
import ftplib
def bruteLogin(hostname, passwdFile):
pF = open(passwdFile, 'r')
ftp = ftplib.FTP(hostname)
for line in pF.readlines():
userName, passWord = line.split(':', 1)
passWord = passWord.strip('\r\n') # strip any of the two characters
print("[+] Trying: {}/{}".format(userName, passWord))
try:
ftp.login(userName, passWord)
except ftplib.error_perm:
continue
else:
print('\n[*] {} FTP Logon Succeeded: {}/{}'.format(hostname, userName, passWord))
ftp.quit()
return userName, passWord
print('\n[-] Could not brute force FTP credentials.')
return None, None
host = '192.168.95.179'
passwdFile = 'C:/Users/Karrigan/Documents/Python Stuff/userpass.txt'
bruteLogin(host, passwdFile)
And I got an error:
[WinError 10061] No connection could be made because the target machine actively refused it
However, when running a similar version of this code earlier this morning, this error did not occur, but that might not be relevant. What could cause this? (Also, that IP is an example provided from the book Violent Python)
Generally that error message means you're getting blocked by a firewall, or the target machine isn't listening on that port.
So, if it was working earlier, then either someone turned on a firewall or stopped the process listening on that port.
This is because you are trying to send email using your localhost as mail-server.
In development process and if you do not have a mail server setup, and you want to fake sending emails using your local machine, so you have to fake it.
In other words:
Looks like you are trying to send a mail (send_mail()) and your mail settings in your settings.py are not correct.
For debugging purposes you could setup a local smtpserver with this command:
python -m smtpd -n -c DebuggingServer localhost:1025
and adjust your mail settings accordingly:
EMAIL_HOST = 'localhost'
EMAIL_PORT = 1025

Getting "socket.error: [Errno 61] Connection refused" python paramiko

Getting error connection refused error when trying to connect to the host to copy a local file to the host server. Don't have any issue connecting to the server remotely though.
host = "9.29.22.222"
username = "XXX"
password = "XXX"
local_path = "/Users/samuelhii/Desktop/file.txt"
remote_path = "C:\Program Files (x86)\file.txt"
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.connect(host,22,username,password)
sftp = s.open_sftp()
sftp.put(local_path,remote_path)
The connection was refused by the server. This can be caused by several reasons not related to Python programming:
a firewall
the SSH service is configure not to take requests from your IP
bad host ip
… (many more)
Check if you can use the normal SSH client to connect with this host/user/password combination.

Categories

Resources