Last active
January 3, 2016 11:29
-
-
Save neilellis/8456036 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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