It is to make an SSH connection from a self-made application compiled with Java 6 to another machine using the SSHJ library. I used to try to do this using the JSch library, but this article As I wrote in 86c9e9efb5358601b25b), it doesn't work, so I'm trying to change it from the JSch library to the SSHJ library.
I think that you can find many samples that perform password authentication when connecting with SSH, but it seems that there were few samples that perform key authentication (with passphrase), so I will write the sample code that succeeded in connecting as a memorandum. I will.
Simply connecting to SSH is not enough, so I tried to make the code download the file after connecting to SSH.
All-capital alphabets are the parts that need to be specified externally or defined in the code. Also, exception handling is a lot skipped.
Sample.java
SSHClient ssh = new SSHClient();
ssh.addHostKeyVerifier(new PromiscuousVerifier());
try {
ssh.connect(HOST, PORT);
ssh.authPublickey(USER, ssh.loadKeys(PRIVATEKEYFILEPATH, PASSPHRASE));
ssh.newSCPFileTransfer().download(SRCDIR, new FileSystemFile(DSTDIR));
ssh.disconnect();
ssh.close();
} catch (UserAuthException e) {
e.printStackTrace();
} catch (TransportException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The private key file that can be used with SSHJ seems to be a PEM format file.
I think that the private key file and public key file are created using the ssh-keygen
command, but depending on the version of the ssh-keygen
command used, the private key file in the following format is generated by default. ..
If you use this private key file with the SSHJ library, authentication will fail.
-----BEGIN RSA PRIVATE KEY-----
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
:
:
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
-----END RSA PRIVATE KEY-----
To authenticate with the SSHJ library, use a private key file in the following format.
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-128-CBC,xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
:
:
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
-----END RSA PRIVATE KEY-----
To generate a PEM-formatted private key file like the one above, specify -m PEM
as an option for the ssh-keygen
command.
-- that's all --
Recommended Posts