Skip to content

Instantly share code, notes, and snippets.

@neilellis
Last active January 3, 2016 11:29
Show Gist options
  • Save neilellis/8456036 to your computer and use it in GitHub Desktop.
Save neilellis/8456036 to your computer and use it in GitHub Desktop.
import net.schmizz.sshj.SSHClient
fun String.on(host: String? = "localhost", user: String = "root", retry: Int = 3): String {
val ssh: SSHClient = SSHClient();
ssh.addHostKeyVerifier { a, b, c -> true };
for ( i in 1..retry) {
try {
ssh.connect(host);
return ssh use {
ssh.authPublickey(user);
ssh.startSession()?.use {
session ->
session.exec(this)?.getInputStream()?.use {
ins ->
String(ins.readBytes(2048))
}
}?:throw Exception("Could not start session on $host")
}
} catch (e: Exception) {
if ( i < retry ) {
println("Retrying for the $i time to ssh $user@$host -c $this (${e.getMessage()})")
Thread.sleep(100)
} else {
throw e
}
}
}
throw Exception("Failed to execute '$this' on $host as $user after $retry attempts")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment