I have been working on a C# console (.NET Core) FTP client. I am getting the following errors:
Error 1 (request.UsePassive = true): The remote server returned an error: 227 Entering Passive Mode (3,95,98,10,218,239)
Error 2 (request.UsePassive = false): The remote server returned an error: (500) Syntax error, command unrecognized.
C# Code:
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(host);
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
request.EnableSsl = true;
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
request.Timeout = -1;
request.Credentials = new NetworkCredential(userName, password);
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
Console.WriteLine(reader.ReadToEnd());
Console.WriteLine($"Directory List Complete, status {response.StatusDescription}");
reader.Close();
response.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
EnableSSL flag has to be set to true, otherwise I get error 421.
The same code above works if I want to make a directory on the server, i.e if
request.Method = WebRequest.Methods.Ftp.MakeDirectory;
I am successfully able to create (also view) a directory on the Server.
I thought that there might be some issue in my firewall/network so I tried the same functionality on Python and it works fine. Code attached:
from ftplib import FTP_TLS
import os
host = '***********************'
user = '***********************'
password = '***********************'
try:
print ('Establishing connection..')
ftp = FTP_TLS(host)
ftp.debug(0)
ftp.login(user, password)
ftp.set_pasv(True)
print ('Connected..')
except:
print ('Error connecting to FTP server')
ftp.prot_p()
print ('Directory list..')
ftp.dir()
#Upload Code
ftp.cwd('/Inbox')
file = 'C:/Users/userName/source/repos/FTP_Script/FTP_Script/testFile.txt'
with open(file, 'rb') as f:
ftp.storbinary('STOR ' + os.path.basename(file), f)
print ('Files list /Inbox')
ftp.cwd('/Inbox')
ftp.retrlines('LIST')
ftp.quit()
Python Log debug(2):
Establishing connection..
*cmd* 'AUTH TLS'
*put* 'AUTH TLS\r\n'
*get* '234 AUTH TLS OK.\n'
*resp* '234 AUTH TLS OK.'
*cmd* 'USER ************************'
*put* 'USER ************************\r\n'
*get* '331 User ************************ OK. Password required\n'
*resp* '331 User ************************ OK. Password required'
*cmd* 'PASS **********'
*put* 'PASS **********\r\n'
*get* '230-Your bandwidth usage is restricted\n'
*get* '230 OK. Current restricted directory is /\n'
*resp* '230-Your bandwidth usage is restricted\n230 OK. Current restricted directory is /'
Connected..
*cmd* 'PBSZ 0'
*put* 'PBSZ 0\r\n'
*get* '200 PBSZ=0\n'
*resp* '200 PBSZ=0'
*cmd* 'PROT P'
*put* 'PROT P\r\n'
*get* '200 Data protection level set to "private"\n'
*resp* '200 Data protection level set to "private"'
*cmd* 'TYPE A'
*put* 'TYPE A\r\n'
*get* '200 TYPE is now ASCII\n'
*resp* '200 TYPE is now ASCII'
*cmd* 'PASV'
*put* 'PASV\r\n'
*get* '227 Entering Passive Mode (3,95,98,10,219,31)\n'
*resp* '227 Entering Passive Mode (3,95,98,10,219,31)'
*cmd* 'LIST'
*put* 'LIST\r\n'
*get* '150 Accepted data connection\n'
*resp* '150 Accepted data connection'
drwxr-xr-x 2 500 tomcat6 4096 Feb 15 00:24 Documents
drwxr-xr-x 2 500 tomcat6 4096 Feb 26 08:10 Inbox
*get* '226-Options: -l \n'
*get* '226 2 matches total\n'
*resp* '226-Options: -l \n226 2 matches total'
*cmd* 'CWD /Inbox'
*put* 'CWD /Inbox\r\n'
*get* '250 OK. Current directory is /Inbox\n'
*resp* '250 OK. Current directory is /Inbox'
*cmd* 'TYPE I'
*put* 'TYPE I\r\n'
*get* '200 TYPE is now 8-bit binary\n'
*resp* '200 TYPE is now 8-bit binary'
*cmd* 'PASV'
*put* 'PASV\r\n'
*get* '227 Entering Passive Mode (3,95,98,10,218,248)\n'
*resp* '227 Entering Passive Mode (3,95,98,10,218,248)'
*cmd* 'STOR testFile.txt'
*put* 'STOR testFile.txt\r\n'
*get* '150 Accepted data connection\n'
*resp* '150 Accepted data connection'
*get* '226-File successfully transferred\n'
*get* '226 0.504 seconds (measured here), 49.58 bytes per second\n'
*resp* '226-File successfully transferred\n226 0.504 seconds (measured here), 49.58 bytes per second'
Files list /Inbox
*cmd* 'CWD /Inbox'
*put* 'CWD /Inbox\r\n'
*get* '250 OK. Current directory is /Inbox\n'
*resp* '250 OK. Current directory is /Inbox'
*cmd* 'TYPE A'
*put* 'TYPE A\r\n'
*get* '200 TYPE is now ASCII\n'
*resp* '200 TYPE is now ASCII'
*cmd* 'PASV'
*put* 'PASV\r\n'
*get* '227 Entering Passive Mode (3,95,98,10,218,255)\n'
*resp* '227 Entering Passive Mode (3,95,98,10,218,255)'
*cmd* 'LIST'
*put* 'LIST\r\n'
*get* '150 Accepted data connection\n'
*resp* '150 Accepted data connection'
-rw-r--r-- 1 500 tomcat6 19030 Mar 4 06:14 cars.csv
-rw-r--r-- 1 500 tomcat6 25 Mar 4 08:36 testFile.txt
*get* '226-Options: -l \n'
*get* '226 2 matches total\n'
*resp* '226-Options: -l \n226 2 matches total'
*cmd* 'QUIT'
*put* 'QUIT\r\n'
*get* '221-Goodbye. You uploaded 1 and downloaded 0 kbytes.\n'
*get* '221 Logout.\n'
*resp* '221-Goodbye. You uploaded 1 and downloaded 0 kbytes.\n221 Logout.'
Press any key to continue . . .
C# log:
System.Net Information: 0 : [6584] FtpWebRequest#45004109::.ctor(ftp://*********.com/)
System.Net Information: 0 : [6584] FtpWebRequest#45004109::GetResponse(Method=LIST.)
System.Net Information: 0 : [6584] Current OS installation type is 'Client'.
System.Net Information: 0 : [6584] RAS supported: True
System.Net Error: 0 : [6584] Can't retrieve proxy settings for Uri 'ftp://*********.com/'. Error code: 12180.
System.Net Information: 0 : [6584] FtpControlStream#21454193 - Created connection from 10.0.1.4:50056 to 3.95.98.11:21.
System.Net Information: 0 : [6584] Associating FtpWebRequest#45004109 with FtpControlStream#21454193
System.Net Information: 0 : [6584] FtpControlStream#21454193 - Received response [220---------- Welcome to Pure-FTPd [privsep] [TLS] ----------
220-You are user number 3 of 50 allowed.
220-Local time is now 11:37. Server port: 21.
220-This is a private system - No anonymous login
220-IPv6 connections are also welcome on this server.
220 You will be disconnected after 15 minutes of inactivity.]
System.Net Information: 0 : [6584] FtpControlStream#21454193 - Sending command [AUTH TLS]
System.Net Information: 0 : [6584] FtpControlStream#21454193 - Received response [234 AUTH TLS OK.]
System.Net Information: 0 : [6584] TlsStream#58870012::.ctor(host=*********.com, #certs=0, checkCertificateRevocationList=False, sslProtocols=None)
System.Net Information: 0 : [6584] FtpControlStream#21454193 - Sending command [USER *************************]
System.Net Information: 0 : [6584] SecureChannel#60068066::.ctor(hostname=*********.com, #clientCertificates=0, encryptionPolicy=RequireEncryption)
System.Net Information: 0 : [6584] Enumerating security packages:
System.Net Information: 0 : [6584] Negotiate
System.Net Information: 0 : [6584] NegoExtender
System.Net Information: 0 : [6584] Kerberos
System.Net Information: 0 : [6584] NTLM
System.Net Information: 0 : [6584] TSSSP
System.Net Information: 0 : [6584] pku2u
System.Net Information: 0 : [6584] WDigest
System.Net Information: 0 : [6584] Schannel
System.Net Information: 0 : [6584] Microsoft Unified Security Protocol Provider
System.Net Information: 0 : [6584] Default TLS SSP
System.Net Information: 0 : [6584] CREDSSP
System.Net Information: 0 : [6584] SecureChannel#60068066 - Left with 0 client certificates to choose from.
System.Net Information: 0 : [6584] SecureChannel#60068066::.AcquireClientCredentials, new SecureCredential() (flags=(ValidateManual, NoDefaultCred, SendAuxRecord, UseStrongCrypto), m_ProtocolFlags=(Zero), m_EncryptionPolicy=RequireEncryption)
System.Net Information: 0 : [6584] AcquireCredentialsHandle(package = Microsoft Unified Security Protocol Provider, intent = Outbound, scc = System.Net.SecureCredential)
System.Net Information: 0 : [6584] InitializeSecurityContext(credential = System.Net.SafeFreeCredential_SECURITY, context = (null), targetName = *********.com, inFlags = ReplayDetect, SequenceDetect, Confidentiality, AllocateMemory, InitManualCredValidation)
System.Net Information: 0 : [6584] InitializeSecurityContext(In-Buffer length=0, Out-Buffer length=188, returned code=ContinueNeeded).
System.Net Information: 0 : [6584] InitializeSecurityContext(credential = System.Net.SafeFreeCredential_SECURITY, context = 11a8e18:11a4880, targetName = *********.com, inFlags = ReplayDetect, SequenceDetect, Confidentiality, AllocateMemory, InitManualCredValidation)
System.Net Information: 0 : [6584] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=ContinueNeeded).
System.Net Information: 0 : [6584] InitializeSecurityContext(credential = System.Net.SafeFreeCredential_SECURITY, context = 11a8e18:11a4880, targetName = *********.com, inFlags = ReplayDetect, SequenceDetect, Confidentiality, AllocateMemory, InitManualCredValidation)
System.Net Information: 0 : [6584] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=ContinueNeeded).
System.Net Information: 0 : [6584] InitializeSecurityContext(credential = System.Net.SafeFreeCredential_SECURITY, context = 11a8e18:11a4880, targetName = *********.com, inFlags = ReplayDetect, SequenceDetect, Confidentiality, AllocateMemory, InitManualCredValidation)
System.Net Information: 0 : [6584] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=ContinueNeeded).
System.Net Information: 0 : [6584] InitializeSecurityContext(credential = System.Net.SafeFreeCredential_SECURITY, context = 11a8e18:11a4880, targetName = *********.com, inFlags = ReplayDetect, SequenceDetect, Confidentiality, AllocateMemory, InitManualCredValidation)
System.Net Information: 0 : [6584] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=190, returned code=ContinueNeeded).
System.Net Information: 0 : [6584] InitializeSecurityContext(credential = System.Net.SafeFreeCredential_SECURITY, context = 11a8e18:11a4880, targetName = *********.com, inFlags = ReplayDetect, SequenceDetect, Confidentiality, AllocateMemory, InitManualCredValidation)
System.Net Information: 0 : [6584] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=ContinueNeeded).
System.Net Information: 0 : [6584] InitializeSecurityContext(credential = System.Net.SafeFreeCredential_SECURITY, context = 11a8e18:11a4880, targetName = *********.com, inFlags = ReplayDetect, SequenceDetect, Confidentiality, AllocateMemory, InitManualCredValidation)
System.Net Information: 0 : [6584] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=ContinueNeeded).
System.Net Information: 0 : [6584] InitializeSecurityContext(credential = System.Net.SafeFreeCredential_SECURITY, context = 11a8e18:11a4880, targetName = *********.com, inFlags = ReplayDetect, SequenceDetect, Confidentiality, AllocateMemory, InitManualCredValidation)
System.Net Information: 0 : [6584] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=OK).
System.Net Information: 0 : [6584] Remote certificate: [Version]
V3
[Subject]
CN=*.*********.com, OU=Vault, O="*********", L=*********, S=********, C=***
Simple Name: *.*********.com
DNS Name: *********.com
[Issuer]
CN=DigiCert SHA2 Secure Server CA, O=DigiCert Inc, C=US
Simple Name: DigiCert SHA2 Secure Server CA
DNS Name: DigiCert SHA2 Secure Server CA
[Serial Number]
0FAC9742CA8932658537BEEDC6FA6E28
[Not Before]
1/23/2018 12:00:00 AM
[Not After]
1/27/2021 12:00:00 PM
[Thumbprint]
63F31654F0A162D0C1E7509744E56297DCCCAB7F
[Signature Algorithm]
sha256RSA(1.2.840.113549.1.1.11)
[Public Key]
Algorithm: RSA
Length: 2048
Key Blob: 30 82 01 0a 02 82 01 01 00 c7 32 1d d8 48 77 28 dc 80 b6 f0 8a a0 65 1c dc ce 73 6b 93 33 54 bd 99 34 35 68 91 df 7c 70 ee c5 fa 84 62 6b 19 e2 0c 9b 80 6d c9 88 48 80 93 f9 b8 db a6 92 f1 8d d4 4b 98 e1 ed 59 4f dd c4 56 bb 20 60 b0 1b bd e3 58 38 36 11 f0 f6 7f 0b 91 18 83 ec a2 fa 39 74 27 15 46 25 38 9b 6f 37 ce 11 5b 95 23 8a 4f eb 87 57 ac 5c c2 ef ....
System.Net Information: 0 : [6584] SecureChannel#60068066 - Remote certificate was verified as valid by the user.
System.Net Information: 0 : [6584] ProcessAuthentication(Protocol=Tls12, Cipher=Aes256 256 bit strength, Hash=Sha384 0 bit strength, Key Exchange=DiffieHellman 1024 bit strength).
System.Net Information: 0 : [6584] FtpControlStream#21454193 - Received response [331 User ************************* OK. Password required]
System.Net Information: 0 : [6584] FtpControlStream#21454193 - Sending command [PASS ********]
System.Net Information: 0 : [6584] FtpControlStream#21454193 - Received response [230-Your bandwidth usage is restricted
230 OK. Current restricted directory is /]
System.Net Information: 0 : [6584] FtpControlStream#21454193 - Sending command [PBSZ 0]
System.Net Information: 0 : [6584] FtpControlStream#21454193 - Received response [200 PBSZ=0]
System.Net Information: 0 : [6584] FtpControlStream#21454193 - Sending command [PROT P]
System.Net Information: 0 : [6584] FtpControlStream#21454193 - Received response [200 Data protection level set to "private"]
System.Net Information: 0 : [6584] FtpControlStream#21454193 - Sending command [OPTS utf8 on]
System.Net Information: 0 : [6584] FtpControlStream#21454193 - Received response [200 OK, UTF-8 enabled]
System.Net Information: 0 : [6584] FtpControlStream#21454193 - Sending command [PWD]
System.Net Information: 0 : [6584] FtpControlStream#21454193 - Received response [257 "/" is your current location]
System.Net Information: 0 : [6584] FtpControlStream#21454193 - Sending command [TYPE I]
System.Net Information: 0 : [6584] FtpControlStream#21454193 - Received response [200 TYPE is now 8-bit binary]
System.Net Information: 0 : [6584] FtpControlStream#21454193 - Sending command [PASV]
System.Net Information: 0 : [6584] FtpControlStream#21454193 - Received response [227 Entering Passive Mode (3,95,98,10,218,207)]
System.Net Information: 0 : [6584] FtpWebRequest#45004109::(Releasing FTP connection#21454193.)
System.Net Error: 0 : [6584] Exception in FtpWebRequest#45004109::GetResponse - The remote server returned an error: 227 Entering Passive Mode (3,95,98,10,218,207)
..
at System.Net.FtpWebRequest.SyncRequestCallback(Object obj)
at System.Net.FtpWebRequest.RequestCallback(Object obj)
at System.Net.CommandStream.Dispose(Boolean disposing)
at System.IO.Stream.Close()
at System.IO.Stream.Dispose()
at System.Net.ConnectionPool.Destroy(PooledStream pooledStream)
at System.Net.ConnectionPool.PutConnection(PooledStream pooledStream, Object owningObject, Int32 creationTimeout, Boolean canReuse)
at System.Net.FtpWebRequest.FinishRequestStage(RequestStage stage)
at System.Net.FtpWebRequest.GetResponse()
Also tools like WinSCP or FileZilla are working fine.
What am I doing wrong in the C# code?
Thanks in advance.