Created
January 8, 2024 06:39
-
-
Save arukusays/c1f432921b1945c9db56e416053abc1f to your computer and use it in GitHub Desktop.
SSH client example with Java ( Apache MINA SSHD )
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import java.io.UncheckedIOException; | |
import java.nio.file.FileSystems; | |
import java.nio.file.Path; | |
import java.util.concurrent.TimeUnit; | |
import org.apache.sshd.client.SshClient; | |
import org.apache.sshd.client.session.ClientSession; | |
import org.apache.sshd.common.config.keys.FilePasswordProvider; | |
import org.apache.sshd.common.keyprovider.FileKeyPairProvider; | |
public class SshUtil { | |
/** | |
* SSHで接続してコマンドを実行する。 | |
* | |
* 参考 | |
* https://www.baeldung.com/java-ssh-connection | |
* https://satob.hatenablog.com/entry/2022/02/22/223217?utm_source=pocket_saves | |
* https://github.com/apache/mina-sshd/blob/master/docs/client-setup.md | |
* | |
* @param username | |
* @param password | |
* @param host | |
* @param port | |
* @param defaultTimeoutSeconds | |
* @param command | |
* @return result of command | |
* @throws UncheckedIOException | |
* | |
*/ | |
public static String execute(String username, String password, String host, int port, long defaultTimeoutSeconds, | |
String command) { | |
SshClient client = SshClient.setUpDefaultClient(); | |
client.start(); | |
try (ClientSession session = client.connect(username, host, port) | |
.verify(defaultTimeoutSeconds, TimeUnit.SECONDS).getSession()) { | |
// TODO 適切な認証処理に置き換える | |
// session.addPasswordIdentity(password); | |
// TODO 公開鍵認証方式の場合? | |
Path privateKeyPath = FileSystems.getDefault().getPath("/path/to/.ssh/id_rsa"); | |
FileKeyPairProvider provider = new FileKeyPairProvider(privateKeyPath); | |
provider.setPasswordFinder(FilePasswordProvider.of("")); // パスワードが必要? | |
session.setKeyIdentityProvider(provider); | |
session.auth().verify(defaultTimeoutSeconds, TimeUnit.SECONDS); | |
// 単にコマンドを実行するだけなら下記メソッドが便利? | |
// TODO コマンド実行時もタイムアウトの設定が必要かもしれない(Overrideしないとできない?) | |
return session.executeRemoteCommand(command); | |
} catch (IOException e) { | |
// TODO 使い方(使う箇所)に応じてエラー処理すること | |
throw new UncheckedIOException(e); | |
} finally { | |
client.stop(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment