-3

While trying to run this code,

public Session buildSSHConnection() throws Exception{

    String user = "user";
    int port = 22;
    Session session = null;
    try {
        JSch jsch = new JSch();
        jsch.addIdentity(this.getClass().getResource("beispiel.key").getFile());
        session = jsch.getSession(user, host, port);
        session.setConfig("StrictHostKeyChecking", "no");
    }catch(JSchException e) {
            session = null;
            throw e;
    }
    return session;
}    

in my runnable jar file, I always get a FileNotFoundException.

I know the file beispiel.key exists in my jar file, as I checked via

jar -tf ssh.jar 

The Stacktrace is

com.jcraft.jsch.JSchException: java.io.FileNotFoundException: file:/home/sebastian/Schreibtisch/ssh.jar!/beispiel.key (Datei oder Verzeichnis nicht gefunden)
at com.jcraft.jsch.KeyPair.load(KeyPair.java:543)
at com.jcraft.jsch.IdentityFile.newInstance(IdentityFile.java:40)
at com.jcraft.jsch.JSch.addIdentity(JSch.java:407)
at com.jcraft.jsch.JSch.addIdentity(JSch.java:367)
at SSHConnection.buildSSHConnection(SSHConnection.java:49)
at SSHConnection.main(SSHConnection.java:64)

Caused by: java.io.FileNotFoundException: file:/home/sebastian/Schreibtisch/ssh.jar!/beispiel.key (Datei oder Verzeichnis nicht gefunden)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at com.jcraft.jsch.Util.fromFile(Util.java:508)
at com.jcraft.jsch.KeyPair.load(KeyPair.java:540)
... 5 more

I found a working alternative for my code:

JSch jsch = new JSch();
InputStream in = this.getClass().getResourceAsStream("beispiel.key");
byte[] c = new byte[in.available()];
in.read(c);
jsch.addIdentity("rsa", c, null, null);

Accessing the file as a Stream works. I didn't try that first because I had a problem finding out the size for my byte array.

Nicholas K
  • 15,148
  • 7
  • 31
  • 57
aquila105
  • 1
  • 3
  • Please provide a [mcve] and the full stack trace of your exception. It's hard to guess what your application is doing and what's wrong. – Selaron Nov 26 '18 at 10:54
  • what is the path you have given for the file? – Pirate Nov 26 '18 at 13:53
  • The 'file' you are trying to open is within your application jar file. You can't access it as a file (which expects it on the file system, not inside a jar file). – Mark Rotteveel Dec 06 '18 at 15:27

1 Answers1

0

Try to set the package name where the file is located in this line:

jsch.addIdentity(this.getClass().getResource("THE_PACKAGE_NAME\beispiel.key").getFile());

If don't works, try to set a slash before the package name, like:

jsch.addIdentity(this.getClass().getResource("\THE_PACKAGE_NAME\beispiel.key").getFile());
snake
  • 11
  • 1