Connessione SSH in Kotlin con JSCH
In questo articolo vediamo come connetterci ad un server SSH in Kotlin usando JSCH.
Dall'ultima volta che l'ho usata ho visto che c'è stato un fork con diversi aggiornamenti di sicurezza.
Quindi noi useremo l'ultima versione.
Se usate Maven:
<dependency>
<groupId>com.github.mwiede</groupId>
<artifactId>jsch</artifactId>
<version>0.2.25</version>
</dependency>
Qui sotto un pò di codice:
package org.example
import com.jcraft.jsch.ChannelShell
import com.jcraft.jsch.JSch
import com.jcraft.jsch.Session
import kotlin.system.exitProcess
fun main() {
val host = "HOST"
val username = "USER"
val password = "PASSWORD"
val port = 22
val jsch = JSch()
val session: Session = jsch.getSession(username, host, port)
session.setPassword(password)
session.setConfig("StrictHostKeyChecking", "no")
session.connect()
val channel: ChannelShell = (session.openChannel("shell") as ChannelShell)
channel.inputStream = System.`in`
channel.outputStream = System.out
channel.connect(3000)
while (true) {
if (channel.isClosed) {
exitProcess(channel.exitStatus);
} else {
Thread.sleep(1000);
}
}
}
Questo codice si connetterà al server, e aprira una shell.
Quindi potrete eseguire i comandi che volete.
Enjoy!
kotlin maven ssh jsch
Commentami!