1 people like it.

SFTP with SSH.Net

SFTP with SSH.Net

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
32: 
33: 
34: 
35: 
36: 
37: 
38: 
39: 
40: 
41: 
42: 
43: 
44: 
45: 
46: 
47: 
48: 
49: 
50: 
51: 
52: 
53: 
54: 
55: 
56: 
57: 
58: 
59: 
60: 
61: 
62: 
63: 
64: 
65: 
66: 
67: 
68: 
// for FSharp-Interactive:
#r "../packages/SSH.NET/lib/net40/Renci.SshNet.dll"

open Renci.SshNet
open System.IO

/// FSharp Async wrapper for SSH.NET SFTP
type SftpClient with
    member x.ListDirectoryAsync path =
        Async.FromBeginEnd((fun(iar,state) ->
            x.BeginListDirectory(path, iar, state)), x.EndListDirectory)

    member x.DownloadFileAsync path output =
        Async.FromBeginEnd((fun(iar,state) ->
            x.BeginDownloadFile(path, output, iar, state)), x.EndDownloadFile)

    member x.UploadFileAsync input path =
        Async.FromBeginEnd((fun(iar,state) ->
            x.BeginUploadFile(input, path, iar, state)), x.EndUploadFile)
        |> Async.Catch

    member x.SynchronizeDirectoriesAsync sourcePath destinationPath searchPattern =
        Async.FromBeginEnd((fun(iar,state) ->
            x.BeginSynchronizeDirectories(
                sourcePath, destinationPath, searchPattern, iar, state)),
            x.EndSynchronizeDirectories)
        |> Async.Catch

let downloadDir = @"c:\temp"
let uploadfile = @"c:\temp\file.txt"

let sftpExample host port username (password:string) =
    async {
        let workDir = "."
        use client = new SftpClient(host, port, username, password)
        client.Connect()
        printfn "Connected to %s" host

        // Change directory:
        client.ChangeDirectory workDir

        // List files in directory:
        let! listDirectory = client.ListDirectoryAsync workDir
        listDirectory |> Seq.iter(fun file ->
            if file.IsDirectory then printfn "/%s" file.Name
            else printfn "%s" file.Name)

        // Download a file:
        let fileName = "manual_en.pdf"
        use fileStream = File.OpenWrite(Path.Combine(downloadDir, fileName))
        printfn "Downloading %s..." fileName
        do! client.DownloadFileAsync ("./download/"+fileName) fileStream
        printfn "Downloaded %s (%i bytes)" fileName fileStream.Length

        // Upload a file:
        client.ChangeDirectory "upload"
        use fileStream = new FileStream(uploadfile, FileMode.Open)
        printfn "Uploading %s (%i bytes)" uploadfile fileStream.Length
        client.BufferSize <- 4096u // bypass Payload error large files
        let! r = client.UploadFileAsync fileStream (Path.GetFileName uploadfile)
        match r with
        | Choice1Of2 _ -> printfn "Uploaded %s" uploadfile
        | Choice2Of2 err -> printf "Error uploading %s: %O" uploadfile err

    } |> Async.StartAsTask

let test =
   sftpExample "demo.wftpserver.com" 2222 "demo-user" "demo-user"
namespace Renci
namespace Renci.SshNet
namespace System
namespace System.IO
Multiple items
type SftpClient =
  inherit BaseClient
  new : connectionInfo:ConnectionInfo -> SftpClient + 4 overloads
  member AppendAllLines : path:string * contents:IEnumerable<string> -> unit + 1 overload
  member AppendAllText : path:string * contents:string -> unit + 1 overload
  member AppendText : path:string -> StreamWriter + 1 overload
  member BeginDownloadFile : path:string * output:Stream -> IAsyncResult + 2 overloads
  member BeginListDirectory : path:string * asyncCallback:AsyncCallback * state:obj * ?listCallback:Action<int> -> IAsyncResult
  member BeginSynchronizeDirectories : sourcePath:string * destinationPath:string * searchPattern:string * asyncCallback:AsyncCallback * state:obj -> IAsyncResult
  member BeginUploadFile : input:Stream * path:string -> IAsyncResult + 3 overloads
  member BufferSize : uint32 with get, set
  member ChangeDirectory : path:string -> unit
  ...

Full name: Renci.SshNet.SftpClient

--------------------
SftpClient(connectionInfo: ConnectionInfo) : unit
SftpClient(host: string, username: string, password: string) : unit
SftpClient(host: string, username: string, [<System.ParamArray>] keyFiles: PrivateKeyFile []) : unit
SftpClient(host: string, port: int, username: string, password: string) : unit
SftpClient(host: string, port: int, username: string, [<System.ParamArray>] keyFiles: PrivateKeyFile []) : unit
val x : SftpClient
member SftpClient.ListDirectoryAsync : path:string -> Async<System.Collections.Generic.IEnumerable<Sftp.SftpFile>>

Full name: Script.ListDirectoryAsync
val path : string
Multiple items
type Async
static member AsBeginEnd : computation:('Arg -> Async<'T>) -> ('Arg * AsyncCallback * obj -> IAsyncResult) * (IAsyncResult -> 'T) * (IAsyncResult -> unit)
static member AwaitEvent : event:IEvent<'Del,'T> * ?cancelAction:(unit -> unit) -> Async<'T> (requires delegate and 'Del :> Delegate)
static member AwaitIAsyncResult : iar:IAsyncResult * ?millisecondsTimeout:int -> Async<bool>
static member AwaitTask : task:Task -> Async<unit>
static member AwaitTask : task:Task<'T> -> Async<'T>
static member AwaitWaitHandle : waitHandle:WaitHandle * ?millisecondsTimeout:int -> Async<bool>
static member CancelDefaultToken : unit -> unit
static member Catch : computation:Async<'T> -> Async<Choice<'T,exn>>
static member FromBeginEnd : beginAction:(AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member FromBeginEnd : arg:'Arg1 * beginAction:('Arg1 * AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member FromBeginEnd : arg1:'Arg1 * arg2:'Arg2 * beginAction:('Arg1 * 'Arg2 * AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member FromBeginEnd : arg1:'Arg1 * arg2:'Arg2 * arg3:'Arg3 * beginAction:('Arg1 * 'Arg2 * 'Arg3 * AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member FromContinuations : callback:(('T -> unit) * (exn -> unit) * (OperationCanceledException -> unit) -> unit) -> Async<'T>
static member Ignore : computation:Async<'T> -> Async<unit>
static member OnCancel : interruption:(unit -> unit) -> Async<IDisposable>
static member Parallel : computations:seq<Async<'T>> -> Async<'T []>
static member RunSynchronously : computation:Async<'T> * ?timeout:int * ?cancellationToken:CancellationToken -> 'T
static member Sleep : millisecondsDueTime:int -> Async<unit>
static member Start : computation:Async<unit> * ?cancellationToken:CancellationToken -> unit
static member StartAsTask : computation:Async<'T> * ?taskCreationOptions:TaskCreationOptions * ?cancellationToken:CancellationToken -> Task<'T>
static member StartChild : computation:Async<'T> * ?millisecondsTimeout:int -> Async<Async<'T>>
static member StartChildAsTask : computation:Async<'T> * ?taskCreationOptions:TaskCreationOptions -> Async<Task<'T>>
static member StartImmediate : computation:Async<unit> * ?cancellationToken:CancellationToken -> unit
static member StartWithContinuations : computation:Async<'T> * continuation:('T -> unit) * exceptionContinuation:(exn -> unit) * cancellationContinuation:(OperationCanceledException -> unit) * ?cancellationToken:CancellationToken -> unit
static member SwitchToContext : syncContext:SynchronizationContext -> Async<unit>
static member SwitchToNewThread : unit -> Async<unit>
static member SwitchToThreadPool : unit -> Async<unit>
static member TryCancelled : computation:Async<'T> * compensation:(OperationCanceledException -> unit) -> Async<'T>
static member CancellationToken : Async<CancellationToken>
static member DefaultCancellationToken : CancellationToken

Full name: Microsoft.FSharp.Control.Async

--------------------
type Async<'T>

Full name: Microsoft.FSharp.Control.Async<_>
static member Async.FromBeginEnd : beginAction:(System.AsyncCallback * obj -> System.IAsyncResult) * endAction:(System.IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member Async.FromBeginEnd : arg:'Arg1 * beginAction:('Arg1 * System.AsyncCallback * obj -> System.IAsyncResult) * endAction:(System.IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member Async.FromBeginEnd : arg1:'Arg1 * arg2:'Arg2 * beginAction:('Arg1 * 'Arg2 * System.AsyncCallback * obj -> System.IAsyncResult) * endAction:(System.IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member Async.FromBeginEnd : arg1:'Arg1 * arg2:'Arg2 * arg3:'Arg3 * beginAction:('Arg1 * 'Arg2 * 'Arg3 * System.AsyncCallback * obj -> System.IAsyncResult) * endAction:(System.IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
val iar : System.AsyncCallback
val state : obj
SftpClient.BeginListDirectory(path: string, asyncCallback: System.AsyncCallback, state: obj, ?listCallback: System.Action<int>) : System.IAsyncResult
SftpClient.EndListDirectory(asyncResult: System.IAsyncResult) : System.Collections.Generic.IEnumerable<Sftp.SftpFile>
member SftpClient.DownloadFileAsync : path:string -> output:Stream -> Async<unit>

Full name: Script.DownloadFileAsync
val output : Stream
SftpClient.BeginDownloadFile(path: string, output: Stream) : System.IAsyncResult
SftpClient.BeginDownloadFile(path: string, output: Stream, asyncCallback: System.AsyncCallback) : System.IAsyncResult
SftpClient.BeginDownloadFile(path: string, output: Stream, asyncCallback: System.AsyncCallback, state: obj, ?downloadCallback: System.Action<uint64>) : System.IAsyncResult
SftpClient.EndDownloadFile(asyncResult: System.IAsyncResult) : unit
member SftpClient.UploadFileAsync : input:Stream -> path:string -> Async<Choice<unit,exn>>

Full name: Script.UploadFileAsync
val input : Stream
SftpClient.BeginUploadFile(input: Stream, path: string) : System.IAsyncResult
SftpClient.BeginUploadFile(input: Stream, path: string, asyncCallback: System.AsyncCallback) : System.IAsyncResult
SftpClient.BeginUploadFile(input: Stream, path: string, asyncCallback: System.AsyncCallback, state: obj, ?uploadCallback: System.Action<uint64>) : System.IAsyncResult
SftpClient.BeginUploadFile(input: Stream, path: string, canOverride: bool, asyncCallback: System.AsyncCallback, state: obj, ?uploadCallback: System.Action<uint64>) : System.IAsyncResult
SftpClient.EndUploadFile(asyncResult: System.IAsyncResult) : unit
static member Async.Catch : computation:Async<'T> -> Async<Choice<'T,exn>>
member SftpClient.SynchronizeDirectoriesAsync : sourcePath:string -> destinationPath:string -> searchPattern:string -> Async<Choice<System.Collections.Generic.IEnumerable<FileInfo>,exn>>

Full name: Script.SynchronizeDirectoriesAsync
val sourcePath : string
val destinationPath : string
val searchPattern : string
SftpClient.BeginSynchronizeDirectories(sourcePath: string, destinationPath: string, searchPattern: string, asyncCallback: System.AsyncCallback, state: obj) : System.IAsyncResult
SftpClient.EndSynchronizeDirectories(asyncResult: System.IAsyncResult) : System.Collections.Generic.IEnumerable<FileInfo>
val downloadDir : string

Full name: Script.downloadDir
val uploadfile : string

Full name: Script.uploadfile
val sftpExample : host:string -> port:int -> username:string -> password:string -> System.Threading.Tasks.Task<unit>

Full name: Script.sftpExample
val host : string
val port : int
val username : string
val password : string
Multiple items
val string : value:'T -> string

Full name: Microsoft.FSharp.Core.Operators.string

--------------------
type string = System.String

Full name: Microsoft.FSharp.Core.string
val async : AsyncBuilder

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.async
val workDir : string
val client : SftpClient
BaseClient.Connect() : unit
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
SftpClient.ChangeDirectory(path: string) : unit
val listDirectory : System.Collections.Generic.IEnumerable<Sftp.SftpFile>
member SftpClient.ListDirectoryAsync : path:string -> Async<System.Collections.Generic.IEnumerable<Sftp.SftpFile>>
module Seq

from Microsoft.FSharp.Collections
val iter : action:('T -> unit) -> source:seq<'T> -> unit

Full name: Microsoft.FSharp.Collections.Seq.iter
val file : Sftp.SftpFile
property Sftp.SftpFile.IsDirectory: bool
property Sftp.SftpFile.Name: string
val fileName : string
val fileStream : FileStream
type File =
  static member AppendAllLines : path:string * contents:IEnumerable<string> -> unit + 1 overload
  static member AppendAllText : path:string * contents:string -> unit + 1 overload
  static member AppendText : path:string -> StreamWriter
  static member Copy : sourceFileName:string * destFileName:string -> unit + 1 overload
  static member Create : path:string -> FileStream + 3 overloads
  static member CreateText : path:string -> StreamWriter
  static member Decrypt : path:string -> unit
  static member Delete : path:string -> unit
  static member Encrypt : path:string -> unit
  static member Exists : path:string -> bool
  ...

Full name: System.IO.File
File.OpenWrite(path: string) : FileStream
type Path =
  static val DirectorySeparatorChar : char
  static val AltDirectorySeparatorChar : char
  static val VolumeSeparatorChar : char
  static val InvalidPathChars : char[]
  static val PathSeparator : char
  static member ChangeExtension : path:string * extension:string -> string
  static member Combine : [<ParamArray>] paths:string[] -> string + 3 overloads
  static member GetDirectoryName : path:string -> string
  static member GetExtension : path:string -> string
  static member GetFileName : path:string -> string
  ...

Full name: System.IO.Path
Path.Combine([<System.ParamArray>] paths: string []) : string
Path.Combine(path1: string, path2: string) : string
Path.Combine(path1: string, path2: string, path3: string) : string
Path.Combine(path1: string, path2: string, path3: string, path4: string) : string
member SftpClient.DownloadFileAsync : path:string -> output:Stream -> Async<unit>
property FileStream.Length: int64
Multiple items
type FileStream =
  inherit Stream
  new : path:string * mode:FileMode -> FileStream + 14 overloads
  member BeginRead : array:byte[] * offset:int * numBytes:int * userCallback:AsyncCallback * stateObject:obj -> IAsyncResult
  member BeginWrite : array:byte[] * offset:int * numBytes:int * userCallback:AsyncCallback * stateObject:obj -> IAsyncResult
  member CanRead : bool
  member CanSeek : bool
  member CanWrite : bool
  member EndRead : asyncResult:IAsyncResult -> int
  member EndWrite : asyncResult:IAsyncResult -> unit
  member Flush : unit -> unit + 1 overload
  member GetAccessControl : unit -> FileSecurity
  ...

Full name: System.IO.FileStream

--------------------
FileStream(path: string, mode: FileMode) : unit
   (+0 other overloads)
FileStream(handle: Win32.SafeHandles.SafeFileHandle, access: FileAccess) : unit
   (+0 other overloads)
FileStream(path: string, mode: FileMode, access: FileAccess) : unit
   (+0 other overloads)
FileStream(handle: Win32.SafeHandles.SafeFileHandle, access: FileAccess, bufferSize: int) : unit
   (+0 other overloads)
FileStream(path: string, mode: FileMode, access: FileAccess, share: FileShare) : unit
   (+0 other overloads)
FileStream(handle: Win32.SafeHandles.SafeFileHandle, access: FileAccess, bufferSize: int, isAsync: bool) : unit
   (+0 other overloads)
FileStream(path: string, mode: FileMode, access: FileAccess, share: FileShare, bufferSize: int) : unit
   (+0 other overloads)
FileStream(path: string, mode: FileMode, access: FileAccess, share: FileShare, bufferSize: int, options: FileOptions) : unit
   (+0 other overloads)
FileStream(path: string, mode: FileMode, access: FileAccess, share: FileShare, bufferSize: int, useAsync: bool) : unit
   (+0 other overloads)
FileStream(path: string, mode: FileMode, rights: System.Security.AccessControl.FileSystemRights, share: FileShare, bufferSize: int, options: FileOptions) : unit
   (+0 other overloads)
type FileMode =
  | CreateNew = 1
  | Create = 2
  | Open = 3
  | OpenOrCreate = 4
  | Truncate = 5
  | Append = 6

Full name: System.IO.FileMode
field FileMode.Open = 3
property SftpClient.BufferSize: uint32
val r : Choice<unit,exn>
member SftpClient.UploadFileAsync : input:Stream -> path:string -> Async<Choice<unit,exn>>
Path.GetFileName(path: string) : string
union case Choice.Choice1Of2: 'T1 -> Choice<'T1,'T2>
union case Choice.Choice2Of2: 'T2 -> Choice<'T1,'T2>
val err : exn
val printf : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printf
static member Async.StartAsTask : computation:Async<'T> * ?taskCreationOptions:System.Threading.Tasks.TaskCreationOptions * ?cancellationToken:System.Threading.CancellationToken -> System.Threading.Tasks.Task<'T>
val test : System.Threading.Tasks.Task<unit>

Full name: Script.test
Raw view New version

More information

Link:http://fssnip.net/7U7
Posted:24 days ago
Author:Tuomas Hietanen
Tags: sftp