Skip to content

Process Start Example

Andrew Lambert edited this page Nov 26, 2022 · 11 revisions

Process Start Example

This example starts a command on the remote machine and reads from its StdOut stream. The hypothetical command we're running is somecommand --foo-bar, and we want to use the sudo operation to run our command as root. Rather than trying to interact with the sudo password prompt we pass the -S flag to tell it to read the password from stdin. At which point we can write the password to stdin ourselves or echo it through a pipe in the command line. Our hypothetical command might expect the user to type "y" and press Enter, for example to accept a license agreement, so we emulate the behavior of the yes command by writing y+eol over and over to stdin.

  Dim sh As SSH.Channel = SSH.OpenChannel("ssh://user:[email protected]/")
  sh.DataMode = SSH.ExtendedDataMode.Merge ' redirect stderr to stdout
  Call sh.Execute("echo mypassword | sudo -S somecommand --foo-bar")
  Dim result As String
  Do Until sh.EOF
    Call sh.Poll()
    If sh.BytesReadable > 0 Then
      result = result + sh.Read(sh.BytesReadable, 0) ' 0 indicates StdOut/In
    End If
    If sh.BytesWriteable > 1 Then
      sh.Write("y" + EndOfLine.Unix, 0) ' emulate the 'yes' command
    End If
  Loop
  sh.Close()

See also

Clone this wiki locally