/src/app/Fake.Net.SSH/SSH.fs

https://github.com/fsharp/FAKE · F# · 63 lines · 39 code · 10 blank · 14 comment · 6 complexity · 0e35e9805d299205d2c5ed87169b31fe MD5 · raw file

  1. namespace Fake.Net
  2. open System
  3. open Fake.Core
  4. [<RequireQualifiedAccess>]
  5. /// Contains a task which allows to perform SSH operations
  6. module SSH =
  7. /// The SSH parameter type.
  8. type SSHParams =
  9. { /// Path of the scp.exe
  10. ToolPath : string
  11. /// Path of the private key file (optional)
  12. PrivateKeyPath : string
  13. /// remote User
  14. RemoteUser : string
  15. RemoteHost : string
  16. RemotePort : string
  17. }
  18. /// The SSH default parameters
  19. let SSHDefaults : SSHParams =
  20. { ToolPath = if Environment.isMono then "ssh" else "ssh.exe"
  21. RemoteUser = "fake"
  22. RemoteHost = "localhost"
  23. RemotePort = "22"
  24. PrivateKeyPath = null
  25. }
  26. let private getTarget sshParams =
  27. match sshParams.RemotePort with
  28. | "22" -> $"%s{sshParams.RemoteUser}@%s{sshParams.RemoteHost}"
  29. | _ -> $"%s{sshParams.RemoteUser}@%s{sshParams.RemoteHost}:%s{sshParams.RemotePort}"
  30. let private getPrivateKey privateKeyPath =
  31. if String.IsNullOrEmpty privateKeyPath then "" else $"-i \"%s{privateKeyPath}\""
  32. let buildArguments sshParams command =
  33. let target = sshParams |> getTarget
  34. let privateKey = sshParams.PrivateKeyPath |> getPrivateKey
  35. $"%s{privateKey} %s{target} %s{Args.toWindowsCommandLine [command]}" |> String.trim
  36. /// Performs a command via SSH.
  37. /// ## Parameters
  38. ///
  39. /// - `setParams` - Function used to manipulate the default SSHParams value.
  40. /// - `command` - The target path. Can be something like user@host:directory/TargetFile or a local path.
  41. ///
  42. /// ## Sample
  43. ///
  44. /// SSH (fun p -> { p with ToolPath = "tools/ssh.exe" }) command
  45. let SSH setParams command =
  46. let (sshParams : SSHParams) = setParams SSHDefaults
  47. let target = sshParams |> getTarget
  48. let args = buildArguments sshParams command
  49. Trace.tracefn $"%s{sshParams.ToolPath} %s{args}"
  50. let result = CreateProcess.fromRawCommandLine sshParams.ToolPath args
  51. |> CreateProcess.withTimeout(TimeSpan.MaxValue)
  52. |> Proc.run
  53. if result.ExitCode <> 0 then failwithf $"Error during SSH. Target: %s{target} Command: %s{command}"