Skip to content

Jsch Configuration

Matthias Wiedemann edited this page Dec 22, 2021 · 2 revisions

There are different ways to configure the SSH connection made via Jsch:

1. use openssh ~/.ssh/config and ~/.ssh/known_hosts files

Jsch provides the possibility to reuse existing .ssh/config files. See full documentation at https://www.ssh.com/academy/ssh/config

Example with Public Key Authentication:

~/.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);
...   

Connecting to a legacy server

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

2. config programmatically

Minimal example with Public Key Authentication:

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);

Connecting to a legacy server

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.

3. java system properties

Connecting to a legacy server

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
Clone this wiki locally