'Retrieving data via sftp with NMSSH in Swift
I am trying to get a JSON file from my server to my iPhone. I am using NMSSH for my FTP connection and the connection works.
But I can't retrieve any data from my server. It doesn't matter what path I am using ~/ or / or /someFolder/ or someFolder. Every time, I am getting the error:
NMSSH_Test[] NMSSH: Could not open file at path /testDirectory (Error 0: )
Here my code:
class Data {
init() {
let session = NMSSHSession.init(host: "someIp", andUsername: "user")
session.connect()
if session.isConnected{
session.authenticate(byPassword: "password")
if session.isAuthorized {
let sftpsession = NMSFTP(session : session)
sftpsession.contents(atPath: "/testDirectory")
// if (sftpsession.contentsOfDirectory(atPath: "~/") != nil) {
// print("Found Data!")
// }
}
}
}
}
Solution 1:[1]
Try with below code:
let session = NMSSHSession(host: serverHost, port: portNo, andUsername: serverUsername)
session.connect()
if session.isConnected{
let privateKeypath:String = Bundle.main.path(forResource: "mykey", ofType: "")!
let privateKey: String = try! String(contentsOfFile: privateKeypath, encoding: String.Encoding.utf8)
session.authenticateBy(inMemoryPublicKey: "", privateKey: privateKey, andPassword: passwordStr)
if session.isAuthorized == true {
let sftpsession = NMSFTP(session: session)
sftpsession.connect()
if sftpsession.isConnected {
print("download session is connected")
}
else {
print("Error: download session not connected")
return
}
guard let directoryContents = downloadSession.contentsOfDirectory(atPath: "Your Directory Path goes here!")
else {
print("Unable to read contents of file in SSH site")
return
}
print("Data at specified path captured: " + directoryContents)
guard let contentList = downloadSession.contents(atPath: "Enter your path here!")
else {
print("Unable to read contents of file in SSH site")
return
}
print("Printing Contents of file at path")
print(contentList)
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dharman |
