Michael W.
Michael W.

Reputation: 391

How to read a file via sftp in scala

I am looking for a simple way to read a file (and maybe a directory) via sftp protocol in scala.

My tries:

I am looking for actual working code that uses a library and sftp instead of a plain scp, which I am forced to do. I've found that there are not many examples for this on the web, and the ones I have found are much more complex.

Upvotes: 1

Views: 3329

Answers (1)

Michael W.
Michael W.

Reputation: 391

Here is a working example, using sshj:

import net.schmizz.sshj.SSHClient
import net.schmizz.sshj.sftp.SFTPClient

object Main extends App {
  val hostname = "myServerName"
  val username = "myUserName"
  val password = "thePassword"
  val destinationFile = "C:/Temp/Test.txt"
  val sourceFile = "./Test.txt"

  val ssh = new SSHClient()
  ssh.addHostKeyVerifier("xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx")
  ssh.connect(hostname)
  ssh.authPassword(username, password)
  val sftp: SFTPClient = ssh.newSFTPClient()
  sftp.get(sourceFile, destinationFile)
  sftp.close()
  ssh.disconnect()
}

I tested this on scala version 2.13.4 with the following entries in build.sbt:

libraryDependencies += "com.hierynomus" % "sshj" % "0.31.0"
libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.2.3"

I would not recommend to actually use it this way. Some of these steps should be wrapped in a Try and then some error checking should be done if the file didn't exists or the connection failed and so on. I intentionally left that out for clarity.

I am not saying that this is the only or the right library for this task. It is just the first one that did work for me. Especially the addHostKeyVerifier method was very helpful in my case. There are also other libraries like JSCH, jassh, scala-ssh and scala-ftp wich also could very well do the job.

Upvotes: 5

Related Questions