Connect to Localhost with Java FTP - java

I'm developing FTP program on JAVA. I'm using Apache Commons Net Library. My Codes are below.
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class ServerClass {
private static void showServerReply(FTPClient ftpClient) {
String[] replies = ftpClient.getReplyStrings();
if (replies != null && replies.length > 0) {
for (String aReply : replies) {
System.out.println("SERVER: " + aReply);
}
}
}
public static void main(String[] args) {
String server = "127.0.0.1";
int port = 80;
String user = "root";
String pass = "root";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
showServerReply(ftpClient);
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("Operation failed. Server reply code: " + replyCode);
return;
}
boolean success = ftpClient.login(user, pass);
showServerReply(ftpClient);
if (!success) {
System.out.println("Could not login to the server");
return;
} else {
System.out.println("LOGGED IN SERVER");
}
} catch (IOException ex) {
System.out.println("Oops! Something wrong happened");
ex.printStackTrace();
}
}
}
But I can't connect my localhost. I want to login my localhost and see my file.
My errors are below.
Oops! Something wrong happened
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:188)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:209)
at com.emrecanoztas.ftp.ServerClass.main(ServerClass.java:22)
can you help me anybody? Thanks!..

Questions:
Is there an FTP server running?
Is there a message in the FTP server log about the connect request?
Does the FTP server allow connections from localhost?
Is the FTP server listening on localhost or should you use the public IP/name of the computer? (check with netstat)

Try the settings below.
String server = "ftp.icm.edu.pl";
int port = 21;
String user = "anonymous";
String pass = "me#nowhere.com";

Related

JavaMail connection to secureimap.t-online.de is refused

We're running a server in our sports club, which requests (among other functionalities) our emails from t-online. Since a few weeks, the connection is refused most times.
I search around the questions and information on the telekom-page, but have not found any mistakes.
I made sure, the port and the address are correct: https://www.telekom.de/hilfe/festnetz-internet-tv/e-mail/e-mail-server-e-mail-protokolle-und-e-mail-einrichtung/posteingangsserver-und-postausgangsserver?samChecked=true
import java.util.Arrays;
import java.util.Properties;
import java.util.function.Consumer;
import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.SearchTerm;
public class EmailTestMain {
public static void main(String[] args) {
String username = "Email#t-online.de";
String password = "Password";
read(username, password, message -> {
try {
System.out.println(message.getSubject());
} catch (MessagingException e) {
e.printStackTrace();
}
}, Folder.READ_WRITE, null);
}
public static void read(final String username, final String password, Consumer<Message> messageConsumer,
int folderAction, SearchTerm searchTerm) {
final String host = "secureimap.t-online.de";
Properties props = new Properties();
props.setProperty("mail.imap.host", host);
props.setProperty("mail.imap.user", username);
props.setProperty("mail.imap.ssl.enable", "true");
props.setProperty("mail.imap.ssl.tr ust", host); // JAVA truststore
props.setProperty("mail.imap.socketFactory", "993");
props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.imap.socketFactory.fallback", "false");
props.setProperty("mail.imap.port", "993");
// Start SSL connection
Session session = Session.getDefaultInstance(props, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try (Store store = session.getStore("imap")) {
store.connect(host, username, password);
try (Folder emailFolder = store.getFolder("INBOX")) {
emailFolder.open(folderAction);
if (searchTerm != null) {
Arrays.stream(emailFolder.search(searchTerm)).forEach(messageConsumer::accept);
} else {
Arrays.stream(emailFolder.getMessages()).forEach(messageConsumer::accept);
}
}
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
The could should print out all subjects of the emails of the INBOX, but instead throw's an exception:
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: secureimap.t-online.de, 993; timeout -1;
nested exception is:
java.net.ConnectException: Connection refused: connect
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:740)
at javax.mail.Service.connect(Service.java:366)
at javax.mail.Service.connect(Service.java:246)
at de.bamberg.jugger.mail.EmailTestMain.read(EmailTestMain.java:55)
at de.bamberg.jugger.mail.EmailTestMain.main(EmailTestMain.java:21)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:353)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:218)
at com.sun.mail.iap.Protocol.<init>(Protocol.java:134)
at com.sun.mail.imap.protocol.IMAPProtocol.<init>(IMAPProtocol.java:131)
at com.sun.mail.imap.IMAPStore.newIMAPProtocol(IMAPStore.java:763)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:698)
... 4 more

Connection Refused Error Coming At The Time Of Uploading Files From Local Machine To FTP Server

I am trying to upload files from local machine to ftp server and when this code starts first it store 6 folder data sucessfully on ftp server but from 7th folder to 25th folder i am getting connection refused error ... There is no limitation from client side for connections and only i am using these credentials for testing purpose . Can any one help me?
I am getting this issue because of mirror issue in code but i am not able to figureout this issue. Please help me
package com.epath.smoketest.tests;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPSClient;
public class FTPUploadDirectoryTest {
public static void main(String[] args) {
try {
System.out.println("\n"
+ "---------------------------------------------------------------------------------" + "\r\n");
System.out.println("Read FTP Login details from PROPERTIES file" + "\r\n");
System.out.println(
"---------------------------------------------------------------------------------" + "\r\n");
Properties prop = new Properties();
InputStream input = null;
String inputFS = getAutomationInputDataPath() + "//Validation.properties";
input = new FileInputStream(inputFS);
prop.load(input);
// -Input file with test data
System.out.println("Uploading file on ftp server");
String ftp_port = prop.getProperty("ftp_port");
int ftp_host = Integer.parseInt(prop.getProperty("ftp_host"));
String ftp_username = prop.getProperty("ftp_username");
String ftp_password = prop.getProperty("ftp_password");
String server = ftp_port;
int port = ftp_host;
String user = ftp_username;
String pass = ftp_password;
FTPSClient ftpClient = new FTPSClient();
// connect and login to the server
ftpClient.connect(server, port);
ftpClient.login(user, pass);
// use local passive mode to pass firewall
ftpClient.enterLocalPassiveMode();
System.out.println("Connected");
String remoteDirPath = "/www/ngage/screenshots";
String localDirPath = folderPathForUploadingOnFTP;
uploadDirectory(ftpClient, remoteDirPath, localDirPath, "");
// log out and disconnect from the server
ftpClient.logout();
ftpClient.disconnect();
System.out.println("Disconnected");
} catch (IOException ex) {
System.err.println("Error occured....." + ex.getMessage());
ex.printStackTrace();
}
}
public static void uploadDirectory(FTPSClient ftpClient, String remoteDirPath, String localParentDir,
String remoteParentDir) throws IOException {
File localDir = new File(localParentDir);
File[] subFiles = localDir.listFiles();
if (subFiles != null && subFiles.length > 0) {
for (File item : subFiles) {
String remoteFilePath = remoteDirPath + "/" + remoteParentDir + "/" + item.getName();
if (remoteParentDir.equals("")) {
remoteFilePath = remoteDirPath + "/" + item.getName();
}
if (item.isFile()) {
if (!checkFileExists(remoteFilePath, ftpClient)) {
// upload the file
String localFilePath = item.getAbsolutePath();
boolean uploaded = uploadSingleFile(ftpClient, localFilePath, remoteFilePath);
if (uploaded) {
System.out.println("UPLOADED a file to: " + remoteFilePath);
} else {
System.out.println("COULD NOT upload the file: " + localFilePath);
}
} else {
System.out.println("This file alerady exist on ftp server ");
}
} else {
// create directory on the server
boolean created = ftpClient.makeDirectory(remoteFilePath);
if (created) {
System.out.println("CREATED the directory: " + remoteFilePath);
} else {
System.out.println("COULD NOT create the directory: " + remoteFilePath);
}
// upload the sub directory
String parent = remoteParentDir + "/" + item.getName();
if (remoteParentDir.equals("")) {
parent = item.getName();
}
localParentDir = item.getAbsolutePath();
uploadDirectory(ftpClient, remoteDirPath, localParentDir, parent);
}
}
}
ftpClient.makeDirectory(remoteDirPath);
}
public static boolean uploadSingleFile(FTPSClient ftpClient, String localFilePath, String remoteFilePath)
throws IOException {
File localFile = new File(localFilePath);
InputStream inputStream = new FileInputStream(localFile);
try {
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
return ftpClient.storeFile(remoteFilePath, inputStream);
} finally {
inputStream.close();
}
}
public static Boolean checkFileExists(String filePath, FTPSClient ftpClient) throws IOException {
InputStream inputStream = ftpClient.retrieveFileStream(filePath);
int returnCode = ftpClient.getReplyCode();
if (inputStream == null || returnCode == 550) {
return false;
}
inputStream.close();
return true;
}
}
Error coming .
COULD NOT upload the file: \\192.168.10.21\volume1\ngage_dev\engineering\ngage\testing\automated\validation\Build_1.19.1\051\2018-04-23_07-54-39_AM\TC_UA_PSWD_0001_006_1.png
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at org.apache.commons.net.ftp.FTPClient._openDataConnection_(FTPClient.java:920)
at org.apache.commons.net.ftp.FTPSClient._openDataConnection_(FTPSClient.java:627)
at org.apache.commons.net.ftp.FTPClient._retrieveFileStream(FTPClient.java:1980)
at org.apache.commons.net.ftp.FTPClient.retrieveFileStream(FTPClient.java:1967)
at com.epath.smoketest.tests.FTPUploadDirectoryTest.checkFileExists(FTPUploadDirectoryTest.java:124)

Connecting to remote Windows machine with JSch

I want to execute command on remote system and want to get result of the same.
I tried following code:
package rough;
import java.io.InputStream;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class RemoteSSH {
public static void main(String[] args) {
String host = "\\\\10.209.110.114";
String user = "Administrator";
String password = "Admin123";
String command1 = "ipconfig";
try {
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig(config);
session.connect();
System.out.println("Connected");
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command1);
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
channel.connect();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0)
break;
System.out.print(new String(tmp, 0, i));
}
if (channel.isClosed()) {
System.out.println("exit-status: " + channel.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
}
}
channel.disconnect();
session.disconnect();
System.out.println("DONE");
} catch (Exception e) {
e.printStackTrace();
}
}
}
But I am getting following error:
com.jcraft.jsch.JSchException: java.lang.IllegalArgumentException: protocol = socket host = null
at com.jcraft.jsch.Util.createSocket(Util.java:258)
at com.jcraft.jsch.Session.connect(Session.java:186)
at com.jcraft.jsch.Session.connect(Session.java:145)
at rough.RemoteSSH.main(RemoteSSH.java:23)
Caused by: java.lang.IllegalArgumentException: protocol = socket host = null
at sun.net.spi.DefaultProxySelector.select(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at com.jcraft.jsch.Util.createSocket(Util.java:252)
... 3 more
Any solution for it?
I have already tried with pstool also but not getting correct output.
After removing the \\\\ from the hostname, I'm getting:
com.jcraft.jsch.JSchException: java.net.ConnectException: Connection refused: connect
at com.jcraft.jsch.Util.createSocket(Util.java:258)
at com.jcraft.jsch.Session.connect(Session.java:186)
at com.jcraft.jsch.Session.connect(Session.java:145)
at rough.RemoteSSH.main(RemoteSSH.java:23)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
My wild guess is that you have no SSH server running on the target machine.
Note that Windows does not have any built-in SSH server.
Make sure you install some SSH server first.
See Is IIS SFTP natively supported by Windows Server 2012 R2?
Or use a different technology to run the command:
Best way to run remote commands on a Windows server from Java?

Getting connection errors while making a server/client chat program in java

I'm nowhere near done with this project yet I'm just trying to make sure things are working and more specifically that the client and server are connecting, and I'm getting connection errors. Here are my two programs. I'm also not entirely sure how to run both of them at once in eclipse so maybe that is the problem. Any help is much appreciated
import java.net.*;
import java.util.*;
import java.io.*;
public class Server {
public void main(String[] args)throws Exception {
ServerSocket server = new ServerSocket(3333);;
while (true)
{
Socket clientsocket = server.accept();
Scanner sc = new Scanner(clientsocket.getInputStream());
PrintStream p = new PrintStream(clientsocket.getOutputStream());
String message = "Hello from server";
p.print(message);
}
}
And heres the client
public static void main(String[] args)throws Exception {
Client display = new Client();
display.setVisible(true);
try {
Socket server = new Socket("localhost", 3333);
Scanner sc = new Scanner(server.getInputStream());
PrintStream p = new PrintStream(server.getOutputStream());
System.out.println(sc.next());
server.close();
sc.close();
p.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I have some gui stuff above and below the client that I didnt show. When I run these I get the following errors
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at Client.main(Client.java:56)
and line 56 is the line with -- Socket server = new Socket("localhost", 3333);

java.net.UnknownHostException not able to connect to ftp

I have ftp port as: ftp://173.201.0.1/
I am trying to connect it through following:
String Ftp_Path = "ftp://173.201.0.1/";
public List<String> GetFileList()
{
String ftpServerIP = Ftp_Path;
String ftpUserID = Ftp_UserName;
String ftpPassword = Ftp_Password;
FTPFile[] downloadFiles = null;
StringBuilder result = new StringBuilder();
FTPClient ftp = new FTPClient();
List<String> xlsFiles = null;
try {
ftp.connect(Ftp_Path);
ftp.login(ftpUserID, ftpPassword);
downloadFiles=ftp.listFiles();
xlsFiles = new ArrayList<String>();
for(FTPFile i : downloadFiles) {
if(i.toString().endsWith(".xls")) {
xlsFiles.add(i.toString());
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return xlsFiles;
}
But I am getting error on line:
ftp.connect(Ftp_Path);
Following is the error.
java.net.UnknownHostException: ftp://173.201.0.1/
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at org.apache.commons.net.DefaultSocketFactory.createSocket(DefaultSocketFactory.java:92)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:201)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:289)
at com.amazonaws.mws.samples.ImportRulesPropertyClass.GetFileList(ImportRulesPropertyClass.java:33)
at com.amazonaws.mws.samples.ManageReportScheduleSample.main(ManageReportScheduleSample.java:74)
Plase help me.
I am new with java.
You just need to specify the IP.The FTPClient makes a ftp request.It is not similar to http request.Just change
String Ftp_Path = "ftp://173.201.0.1/";
to
String Ftp_Path = "173.201.0.1";
Also check whether the ftp port is up and accessible through telnet

Categories

Resources