I'm using jsch to connect sftp server from java and send a file to a specific directory
private static boolean enviarCSV(String localFile) throws IOException, JSchException, SftpException {
logger.info("Enviando fichero a maquina destino..");
ChannelSftp channelSftp = setupJsch();
channelSftp.connect();
String remoteDir = Config.getParametro("wssf.conf.remoteDir");
channelSftp.put(localFile, remoteDir + localFile);
logger.info("Enviado con exito!");
channelSftp.exit();
return false;
}
private static ChannelSftp setupJsch() throws JSchException {
JSch jsch = new JSch();
String user = Config.getParametro("wssf.conf.login.usuario");
String password = Config.getParametro("wssf.conf.login.password");
String remoteHost = Config.getParametro("wssf.conf.remotehost");
Session jschSession = jsch.getSession(user, remoteHost, 40020);
jschSession.setConfig("StrictHostKeyChecking", "no");
jschSession.setPassword(password);
jschSession.connect();
return (ChannelSftp) jschSession.openChannel("sftp");
}
I need to use public key in order to connect the SFTP server. I'm pretty new in security and I'm not sure how to do it, additionaly I only see examples using private keys, but I think I dont need it , do I ?
Much appreciate if you help me
Thanks
Keys come in pairs. One private, one public.
To authenticate with your public key (that you freely share), you will need to prove to the other side that you in fact also have the matching private key (because anyone could have your public key, but only you have the private one).
You do this by enrcypting or singing something with your private key - which can be verified through your public key.
So for "public key authentification" you in fact have to work with the private key as well ... and can use the examples referring to that :-)
Related
I try to connect SFTP Server using Jsch Library. It works when i use username/password, but with private/public key does not work. i have been read all questions about this theme in Stackoverflow and in other Site webs, but i did not find what i search for.
To test my private key, i have used Terminal(also WinSCP), it works fine, but with Java Code i get this " Auth fail"
This is an Example:
public static void main(String[] args) throws JSchException, SftpException, IOException {
JSch jsch = new JSch();
Properties config=new Properties();
config.put("StrictHostKeyChecking", "no");
jsch.addIdentity("path_to_private_key");
Session session;
session = jsch.getSession("user", "host", 22);
session.setConfig(config);
// session.setPassword("pass");
session.connect();
System.out.println("CONNECT !!! ");
session.disconnect();
}
. I have generated keys using this command: ssh-keygen -C "" -m PEM id_rsa
. past public key in /.ssh/authorized_keys
Any help please?
I would like to send files from my first remote server to another one:
public boolean uploadFile() throws JSchException, SftpException {
ChannelSftp channelSftpA = createChannelSftp();
ChannelSftp channelSftpB = createChannelSftp();
channelSftpA.connect();
channelSftpB.connect();
localFilePath = "/data/upload/readme.txt";
remoteFilePath = "/bingo/pdf/";
channelSftpA.cd(localFilePath);
channelSftpA.put(localFilePath + "readme.txt", remoteFilePath + "readme.txt");
But it doesn't work. Should I put channelB.put into my first channelA.put?
If I understood your question correct, you code will be run from third server, for transferring file you should get file from server A, and that put on server B. By the way users under which you are going to download and upload files should have access to specified folders!
private boolean transferFile() throws JSchException, SftpException {
ChannelSftp channelSftpA = createChannelSftp();
ChannelSftp channelSftpB = createChannelSftp();
channelSftpA.connect();
channelSftpB.connect();
String fileName = "readme.txt";
String remoteFilePathFrom = "/folderFrom/";
String remoteFilePathTo = "/folderTo/";
InputStream srcInputStream = channelSftpA.get(remoteFilePathFrom + fileName);
channelSftpB.put(srcInputStream, remoteFilePathTo + fileName);
System.out.println("Transfer has been completed");
channelSftpA.exit();
channelSftpB.exit();
return true;
}
This question already has an answer here:
Can we use JSch for SSH key-based communication?
(1 answer)
Closed 4 years ago.
I have two servers A and B.
I want to SFTP a file from server A to B.
Public key of server A (~/.ssh/id_rsa.pub) has been added to the ~/.ssh/authorized_keys of server B.
From command line, I can SFTP from server A to B without entering password.
However, from a Java client using library Jsch I am unable to make SFTP connection to server B and I am getting authentication error:
Error occurred during SFTP. Auth fail
com.jcraft.jsch.JSchException: Auth fail
at com.jcraft.jsch.Session.connect(Session.java:519)
at com.jcraft.jsch.Session.connect(Session.java:183)
at Main.main(Main.java:15)
Is there a way I can connect to server B for SFTP purposes using Java client without specifying password?
Below is my Java code for reference:
import com.jcraft.jsch.*;
public class Main {
public static void main(String[] args) {
JSch jsch = new JSch();
Session session = null;
try {
session = jsch.getSession("processor", "remoteserver.myorg.com", 22);
session.setConfig("StrictHostKeyChecking", "no");
System.out.println("Trying to connect...");
session.connect();
System.out.println("Connected successfully.");
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
System.out.println("Doing SFTP...");
sftpChannel.put("/tmp/test.txt", "/some/remote/folder");
System.out.println("Success");
sftpChannel.exit();
session.disconnect();
} catch (JSchException | SftpException e) {
System.err.println("Error occurred during SFTP. " + e.getMessage());
e.printStackTrace();
}
}
}
Use addIdentity() api in jsync and point to your private key file location.
Ref:
Can we use JSch for SSH key-based communication?
String privateKey = "~/.ssh/id_rsa";
jsch.addIdentity(privateKey);
System.out.println("identity added ");
Session session = jsch.getSession(user, host, port);
System.out.println("session created.");
I am using JSch for sftp communication, now i want to use facilitate the key-based authentication, key is loaded on client and server machine once by my network team and all later communication would be only user based for which we have loaded the key.
sftp -oPort=10022 jmark#192.18.0.246
as tjill#192.18.0.135
like this command work fine and connect to the sftp, how i can achieve this functionality programmatically.
if it is not possible using JSch, please suggest some other library. I came across Apache SSHD.
It is possible. Have a look at JSch.addIdentity(...)
This allows you to use key either as byte array or to read it from file.
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class UserAuthPubKey {
public static void main(String[] arg) {
try {
JSch jsch = new JSch();
String user = "tjill";
String host = "192.18.0.246";
int port = 10022;
String privateKey = ".ssh/id_rsa";
jsch.addIdentity(privateKey);
System.out.println("identity added ");
Session session = jsch.getSession(user, host, port);
System.out.println("session created.");
// disabling StrictHostKeyChecking may help to make connection but makes it insecure
// see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
//
// java.util.Properties config = new java.util.Properties();
// config.put("StrictHostKeyChecking", "no");
// session.setConfig(config);
session.connect();
System.out.println("session connected.....");
Channel channel = session.openChannel("sftp");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();
System.out.println("shell channel connected....");
ChannelSftp c = (ChannelSftp) channel;
String fileName = "test.txt";
c.put(fileName, "./in/");
c.exit();
System.out.println("done");
} catch (Exception e) {
System.err.println(e);
}
}
}
I'm trying to use JSch in Java to connect to one of my EC2 instances, but keep getting an "UnknownHostKey" exception message. Here's is (part of) my code:
import com.jcraft.jsch.*;
import java.io.*;
public class JSchTest {
private String serverIp;
public void testSshConnection() {
try {
JSch jsch = new JSch();
jsch.addIdentity("C:\\Users\\Administrator\\.ssh\\id_rsa");
Session session = jsch.getSession("ec2-user", serverIp, 22);
session.connect(30000); // <-- this is where the exception is thrown
ChannelExec channel = (ChannelExec)session.openChannel("shell");
// more code here...
channel.disconnect();
session.disconnect();
} catch (JSchException|IOException ex) {
ex.printStackTrace();
}
}
public void setServerIp(String serverIp) {
this.serverIp = serverIp;
}
}
I've already added my public key to the authorized_keys file on the EC2 instance that I'm connecting to, and I know it works because I can connect to it using PuTTY. However as soon as I hit the line with the session.connect() in it, I get an exception like this:
com.jcraft.jsch.JSchException: UnknownHostKey: 10.114.2.115. RSA key fingerprint is 63:04:cf:60:4a:1d:47:35:12:0e:56:4f:5b:0a:c9:d4
What am I missing? How can I get this to connect?
Try this:
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
As per this link.