-
Notifications
You must be signed in to change notification settings - Fork 146
Jsch Configuration
There are different ways to configure the SSH connection made via Jsch:
Jsch provides the possibility to reuse existing .ssh/config
files. See full documentation at https://man.openbsd.org/ssh_config
~/.ssh/config
File:
# some comment
Host host2
HostName host2.somewhere.edu
User foobar
IdentityFile ~/.ssh/old_keys/host2_key
Java Code: You can directly set the content like in https://github.com/mwiede/jsch/blob/master/examples/OpenSSHConfig.java, but you can also read and parse the file like this:
final JSch jSch = new JSch();
final String configFile = System.getProperty("user.home") + File.separator + ".ssh" + File.separator + "config";
final File file = new File(configFile);
if (file.exists()) {
final OpenSSHConfig openSSHConfig = OpenSSHConfig.parseFile(file.getAbsolutePath());
jSch.setConfigRepository(openSSHConfig);
}
final String knownHostsFile= System.getProperty("user.home") + File.separator + ".ssh" + File.separator + "known_hosts";
if(new File(knownHostsFile).exists()) {
jSch.setKnownHosts(knownHostsFile);
}
final Session newSession = jSch.getSession(myHost);
newSession.connect(connectTimeout);
...
In order to connect to a legacy server, it might be necessary to overwrite the default config of Jsch. The same thing is described on https://www.openssh.com/legacy.html.
So for example you can add a legacy key exchange algorithm by putting it in your ~/.ssh/config
file:
Host somehost.example.org
KexAlgorithms +diffie-hellman-group1-sha1
final JSch jSch = new JSch();
jSch.setKnownHosts(new ByteArrayInputStream(myKnownHostsAsString.getBytes()));
jSch.addIdentity("~/.ssh/id_rsa");
final Session newSession = jSch.getSession(myHost);
newSession.connect(connectTimeout);
If you need to override the default config and you want to do it programmatically, simply set it on the Session instance:
session.setConfig("kex", session.getConfig("kex") + ",diffie-hellman-group14-sha1");
You can decide, whether you just set one value or if you just append or prepend another item. The list of available config keys it listed on the Readme.
If you do not have access to the Jsch code, because you are using another library, which just embeds Jsch, then with this option, it is possible to overwrite the ssh connection properties. You need to set the system properties when launching java, i.e.
java -jar my_spring_boot_app.jar -Djsch.kex=ssh-ed25519,diffie-hellman-group14-sha1