Our company web site is hosted in ORCSWEB. Some kind of policy and rule has been set on ORCS end. When people try to access our company ftp with wrong credential 3 times and fail then our ftp will be locked. We often upload file through ftp by programatically but some times found ftp lock. So I talk to orcsweb tech support: they said we are try to access our ftp anonymously by code. So the code which I use to access ftp as follows. So please go through my code and tell me what is wrong in my code which causes anonymous access because I try to access with the right credentials.
public static string IsFtpAccessible(string FTPAddress)
{
string strError = "";
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(FTPAddress);
FtpWebResponse res;
StreamReader reader;
ftp.Credentials = new NetworkCredential("myuserid", "00000password");
ftp.KeepAlive = false;
ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
ftp.UsePassive = true;
ftp.UseBinary = true;
ftp.KeepAlive = false;
try
{
using (res = (FtpWebResponse)ftp.GetResponse())
{
reader = new StreamReader(res.GetResponseStream());
}
}
catch(Exception ex)
{
strError = "ERROR:" + ex.Message.ToString();
}
return strError;
}
So tell me what is missing in my code that causes anonymous access.
Anonymous access must be allowed on the server, which I'm assuming is not allowed based on your description. Typically, Anonymous access credentials are supplied like this:
request.Credentials = new NetworkCredential ("anonymous","janeDoe#contoso.com");
The main point is that an email address is the password.
If you only sometimes find that the code based FTP is locked, then this is not where your problem lies.
Related
I have an FTPS site I need to connect to and get a file from. A vendor will be dropping a csv file there daily and I have to retrieve it and process it. My problem is no matter what I try and I can't connect to this site. I realize FTPS is different than SFTP and according to my research my normal method of getting files from FTP should work simply by adding an EnableSsl flag as seen below (ip, port, credentials have been changed obviously):
string uri = "ftp://127.0.0.1:123/";
string filename = "remoteFile.txt";
uri += filename;
var request = (FtpWebRequest)WebRequest.Create(uri);
request.Credentials = new NetworkCredential("user1", "secure-password1");
request.EnableSsl = true;
request.KeepAlive = false;
request.UseBinary = true;
request.UsePassive = true;
ServicePointManager.ServerCertificateValidationCallback = (s, certificate, chain, sslPolicyErrors) => true;
request.Method = WebRequestMethods.Ftp.DownloadFile;
var response = (FtpWebResponse)request.GetResponse(); //<-- error here
Stream responseStream = response.GetResponseStream();
var reader = new StreamReader(responseStream);
var fileContents = reader.ReadToEnd();
reader.Close();
response.Close();
string filePath = #"C:\Temp\localFile.txt";
using var stream = new StreamWriter(filePath);
{
stream.Write(fileContents);
}
I've tried variations of the 4 booleans I set on the request object. In this configuration I get the error in the title. If I switch passive to false I get a timeout. I can connect to this FTP site using WinSCP. There is a certificate on the site and I imported my connection configuration from a co-worker. There is an SHA-1 fingerprint.
I have also tried creating a connection with the WinSCP Nuget package and followed their example, I just can't seem to get the fingerprint correct:
var options = new SessionOptions
{
Protocol = Protocol.Ftp,
HostName = "ftp://127.0.0.1:21/",
UserName = "user1",
Password = "secure-password1",
SshHostKeyFingerprint = "???",
};
using var session = new WinSCP.Session();
session.Open(options);
No matter what I've tried in that finger print property it doesn't match the pattern they want and I can't find a good example of what it should look like. On the WinSCP page it says to obtain the fingerprint from your administrator, ours provided a certificate file that has an RSA section and a Certificate section. I've tried assigning the whole file to that field, the RSA section, certificate, nothing works. I tried the fingerprint displayed in my working session from WinSCP and that doesn't work.
I've found a few questions on this site with this error but all seem to point to server issues. I figure if I can connect and get files using WinSCP then I should be able to do it through code as well.
thanks
As Martin suggested I opened WinSCP, logged into my FTP site using the app. Then I clicked the Session menu and chose Generate URL/Code... Click the .NET assembly code tab at the top and pasted the code into my project
// Set up session options
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Ftp,
HostName = "127.0.0.1",
PortNumber = 21,
UserName = "user1",
Password = "secure-password1",
FtpSecure = FtpSecure.Explicit,
TlsHostCertificateFingerprint = "2f:f5:ab:e5:f7:27:65:12:30:73:3d:9a:b7:12:88:11:62:0e:6f:a1",
};
using (Session session = new Session())
{
// Connect
session.Open(sessionOptions);
// Your code
}
I hope this helps whoever is stuck on this like I was.
We have a SOAP based web service and we are able to read its wsdl when we type in the url in Browser. We sit behind a proxy in our network but its not blocking anything and we are always able to read wsdl using browser.But when we enter the url in Browser say http://ist.services/CoreServices/coreservices?wsdl it asks for username and password which is not same as my windows credentials. So when i enter the username and password shared by the dev team , it returns the wsdl page. Please note that this webservice is developed and deployed on java based server.
How do i do the same in c#.net code and how do i pass the Security Crednetials in DiscoveryClientProtocol? I tried the below code which works for the webservices which doesn't ask for the Security credentials.
// Specify the URL to discover.
string sourceUrl = "http://ist.services/CoreServices/coreservices?wsdl";
string outputDirectory = "C:\\Temp";
DiscoveryClientProtocol client = new DiscoveryClientProtocol();
var credentials = new NetworkCredential("sunuser1", "xxxxxxx", "");
WebProxy proxy = new WebProxy("http://proxy.bingo:8000/", true) { Credentials = credentials };
client.Credentials = credentials;
// Use default credentials to access the URL being discovered.
//client.Credentials = credentials;//CredentialCache.DefaultCredentials;
client.Proxy = proxy;
String DiscoverMode = "DiscoverAny";
String ResolveMode = "ResolveAll";
try
{
DiscoveryDocument doc;
// Check to see if whether the user wanted to read in existing discovery results.
if (DiscoverMode == "ReadAll")
{
DiscoveryClientResultCollection results = client.ReadAll(Path.Combine("C:\\Temp", "results.discomap"));
//SaveMode.Value = "NoSave";
}
else
{
// Check to see if whether the user wants the capability to discover any kind of discoverable document.
if (DiscoverMode == "DiscoverAny")
{
doc = client.DiscoverAny(sourceUrl);
}
else
// Discover only discovery documents, which might contain references to other types of discoverable documents.
{
doc = client.Discover(sourceUrl);
}
// Check to see whether the user wants to resolve all possible references from the supplied URL.
if (ResolveMode == "ResolveAll")
client.ResolveAll();
else
{
// Check to see whether the user wants to resolve references nested more than one level deep.
if (ResolveMode == "ResolveOneLevel")
client.ResolveOneLevel();
else
Console.WriteLine("empty");
}
}
}
catch (Exception e2)
{
//DiscoveryResultsGrid.Columns.Clear();
//Status.Text = e2.Message;
Console.WriteLine(e2.Message);
}
// If documents were discovered, display the results in a data grid.
if (client.Documents.Count > 0)
Console.WriteLine(client);
}
}
Since the code didn't help me much , i opened the fiddler to trace the http calls when i manual read the wsdl in browser and i see it takes the credentials i entered as "Authorization: Basic cGDFDdsfdfsdsfdsgsgfg=" . In fiddler i see three calls with responses 401,302 and 200. But in my c#.net code i don't get the 200 response and it always throws me the 404 error.
I further debugged this and in httpresponse of client object i see the flag status as INVOCATION_FLAGS_INITIALIZED | INVOCATION_FLAGS_NEED_SECURITY
So looks like i need to pass the credentials as Security Credentials rather than Network credentials.
The below code has fixed the issue.
CredentialCache myCredentialCache = new CredentialCache { { new Uri(sourceUrl),
"Basic", networkCredential } };
discoveryClientProtocol.AllowAutoRedirect = true;
discoveryClientProtocol.Credentials = myCredentialCache;
I have an ASP MVC4 site. I have to create a folder on ftp server and I use this code:
FtpWebRequest ftpWebRequest = (FtpWebRequest)WebRequest.Create("ftp://mysite.altervista.org/newfolder");
ftpWebRequest.Method = WebRequestMethods.Ftp.MakeDirectory;
ftpWebRequest.UsePassive = true;
ftpWebRequest.EnableSsl = true;
ftpWebRequest.Credentials = new NetworkCredential("userTest", "psw123456");
ftpWebRequest.KeepAlive = true;
ftpWebRequest.UseBinary = true;
using (var resp = (FtpWebResponse)ftpWebRequest.GetResponse())
{
Console.WriteLine("Result: " + resp.StatusCode);
}
When I run my site in localhost everything works fine, but when I Publish my site to Azure Website, it returns me an exception: "The remote server returned an error: (530) Not logged in."
I think that the problem is not in my code, do I have to change some setting in Azure?
Thank you in advance
remove below 2 lines and try again
ftpWebRequest.UsePassive = true;
ftpWebRequest.EnableSsl = true;
Have tried to check some settings in your FTP server? Maybe, the incoming connections are blocked.
I am using the following method to list the contents of a folder:
private void TestFtp()
{
try
{
// List all of the files from FTP
FtpWebRequest ftprequest = (FtpWebRequest)WebRequest.Create(new Uri("ftp://m3database/recover/"));
ftprequest.Credentials = new NetworkCredential("myusername1", "********");
ftprequest.Method = WebRequestMethods.Ftp.ListDirectory;
ftprequest.UsePassive = false;
ftprequest.Proxy = null;
using (var resp = ftprequest.GetResponse())
{
StreamReader reader = new StreamReader(resp.GetResponseStream());
MessageBox.Show(reader.ReadToEnd());
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
I'm connecting to a single Linux server via FTP. I'm using the credentials for myusername1 and myusername2 to connect.
I am able to list the directory contents when using this function if I am using myusername1 credentials, however if I use myusername2 it comes up with the following error:
The remote server returned an error: (503) Bad sequence of commands.
Things that I have tried:
I have tried setting ftprequest.KeepAlive = false.
I have tried using all permutations of UsePassive, Proxy etc.
I am able to connect to both usernames using FileZilla WITH secure FTP enabled and they both work. Without FTP enabled, neither will connect.
It is peculiar that my code will connect using myusername1 without SSL enabled within my code.
In summary:
myusername1 and myusername2 will not connect on FileZilla without secure FTP enabled.
myusername1 works within my C# method without ftprequest.EnableSsl enabled.
myusername2 will not work within my C# method regardless of whether ftprequest.EnableSsl is enabled.
The Exception is being triggered on the line of my using() statement.
Something else I just noticed, when I hover over my ftprequest, it shows a NotSupportedException, but this appears regardless of which set of credentials I use
If I hover over my initial ftprequest when using myusername2, it shows an Exception thrown before my using():
This might be a shot in the dark, but have you tried using a CredentialCache?
System.Net.NetworkCredential nc = new System.Net.NetworkCredential("user", "password");
System.Net.CredentialCache cc = new System.Net.CredentialCache();
cc.Add(new Uri("ftp://m3database"), "Basic", nc);
System.Net.FtpWebRequest ftprequest = (System.Net.FtpWebRequest)System.Net.WebRequest.Create("ftp://m3database/recover/");
ftprequest.Credentials = cc;
ftprequest.Method = System.Net.WebRequestMethods.Ftp.ListDirectory;
using (var resp = ftprequest.GetResponse())
{
StreamReader reader = new StreamReader(resp.GetResponseStream());
MessageBox.Show(reader.ReadToEnd());
}
}
The credentialcache also gives you a range of authenticationtype options ("NTLM", "Digest", "Kerberos", "Negotiate"... ).
More here --> http://msdn.microsoft.com/en-us/library/59x2s2s6.aspx
I'm connecting to a single Linux server via FTP.
CHMOD the perms on the FTP server/folder for the 2nd User, they should be the same as the 1st User.
CHMOD 777 will allow access required..
Any idea of how to upload a file to Google site from c#?
I am trying to upload but getting a 403 error. However, I am using the same credentials to connect to the site and get the list of attachments and pages present on the site.
Any help would be greatly appreciated!!
They most likely have an anti-CSRF scheme that stores temporal identifiers in the page and/or cookies, this is specifically to hinder bots.
You are most likely submitting a request without the proper CSRF tokens and get rejected. I would recommend analyzing how they handle CSRF, after this point it will most likely boil down to making a WebRequest to the page and so you can get any cookies they get back, along with having the form so you can scrape out any hidden fields that are relevant. Then move those over to your post request that you're attempting to the send the file to.
I figured out the problem and resolved it. Below is the complete function:
public bool UploadAttachment()
{
try
{
//AsyncSendData data = new AsyncSendData();
string parentUrl = Cabinets["Cabinet1"].ToString();
string parentID = parentUrl.Split('/')[7];
AtomEntry entry = new AtomEntry();
entry.Title.Text = "abc.jpg";
AtomCategory cat = new AtomCategory();
cat.Term = ATTACHMENT_TERM;
cat.Label = "attachment";
cat.Scheme = KIND_SCHEME;
entry.Categories.Add(cat);
AtomLink link = new AtomLink();
link.Rel = PARENT_REL;
link.HRef = parentUrl;
entry.Links.Add(link);
AtomContent content = new AtomContent();
FileInfo info = new FileInfo("C:\\Bluehills.txt");
FileStream stream = info.Open(FileMode.Open,FileAccess.ReadWrite,FileShare.ReadWrite);
this.setUserCredentials(userName, password);
Uri postUri = new Uri(makeFeedUri("content"));
entry.Source = new AtomSource();
//this.EntrySend(postUri, entry, GDataRequestType.Insert);
// Send the request and receive the response:
AtomEntry insertedEntry = this.Insert(postUri, stream, (string)DocumentTypes["TXT"], "bluehills");
return true;
}
catch (Exception ex)
{
return false;
}
}