Use SSHJ instead:
import net.schmizz.sshj.DefaultConfig;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.common.IOUtils;
import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.transport.verification.HostKeyVerifier;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class SSHJExample {
public static void main(String[] args) {
SSHClient ssh = new SSHClient();
try {
// Use a PromiscuousVerifier to trust any host key
HostKeyVerifier promiscuousVerifier = new PromiscuousVerifier();
// Configure the SSH client with the PromiscuousVerifier
ssh.addHostKeyVerifier(promiscuousVerifier);
// Connect to the remote server
ssh.connect("host");
// Specify the private key for authentication
KeyProvider keyProvider = ssh.loadKeys("/path/to/your/private_key");
// or ssh.loadKeys("/path/to/your/private_key","passphrase");
// Authenticate using the private key
ssh.authPublickey("user", keyProvider);
// Create a session
Session session = ssh.startSession();
try {
// Execute a command on the remote server
Session.Command command = session.exec("ls -la");
// Wait for the command to complete
command.join(5, TimeUnit.SECONDS);
// Get the command output
String output = IOUtils.readFully(command.getInputStream()).toString();
System.out.println("Command output:");
System.out.println(output);
} finally {
session.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ssh.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Dependency:
<dependency>
<groupId>com.hierynomus</groupId>
<artifactId>sshj</artifactId>
<version>0.35.0</version>
</dependency>
A safer solution for the HostsVerifier would be:
Add the host key to the known hosts file: You can manually add the host key of the remote server to the known hosts file on the machine running the code. The known hosts file is typically located at ~/.ssh/known_hosts for the user executing the code. Once the host key is added to the known hosts file, SSHJ will be able to verify it during subsequent connections.
Use a secure host key verifier: Instead of trusting any host key or modifying the known hosts file manually, you can implement a custom HostKeyVerifier that matches the expected host key fingerprint and use it to verify the host key. This approach provides a more secure way to verify the host key. Here's an example:
// Load the known hosts file for host key verification
OpenSSHKnownHosts sshKnownHosts = new OpenSSHKnownHosts();
// Set the known hosts file path
sshKnownHosts.load("~/.ssh/known_hosts"); // Replace with the actual path
// Configure the SSH client with the known hosts verifier
ssh.addHostKeyVerifier(sshKnownHosts);