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.