Sample code for 30+ languages & platforms
DataFlex

Run a Single SSH Command and Get the Output

See more SSH Examples

Demonstrates the Chilkat Ssh.QuickCommand method, which runs one noninteractive remote command and returns its stdout as text. The first argument is the command and the second is the charset used to decode the output. Internally it opens a session channel, sends an exec request, and receives the output through EOF.

Background: This collapses the whole open-channel / exec / receive / retrieve sequence into a single call, and it is the right choice for the common case of "run one command and give me the output." Because no PTY is involved the output is clean and parseable, with no prompt or echoed input. Reach for the individual channel methods only when you need stderr separately, the exit status, or an interactive session.

Chilkat DataFlex Downloads

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoSsh
    Integer iSshPort
    String sPassword
    String sOutput
    String sTemp1
    Boolean bTemp1

    Move False To iSuccess

    //  Demonstrates the Ssh.QuickCommand method, which runs one noninteractive remote command and
    //  returns its stdout as text.  The 1st argument is the command and the 2nd is the charset used
    //  to decode the output.  Internally it opens a session channel, sends an exec request, and
    //  receives the output through EOF.

    Get Create (RefClass(cComChilkatSsh)) To hoSsh
    If (Not(IsComObjectCreated(hoSsh))) Begin
        Send CreateComObject of hoSsh
    End

    Move 22 To iSshPort
    Get ComConnect Of hoSsh "ssh.example.com" iSshPort To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoSsh To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    //  Normally you would not hard-code the password in source.  You should instead obtain it
    //  from an interactive prompt, environment variable, or a secrets vault.
    Move "mySshPassword" To sPassword

    Get ComAuthenticatePw Of hoSsh "mySshLogin" sPassword To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoSsh To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    //  Run a single command and collect its output in one call.
    Get ComQuickCommand Of hoSsh "uname -a" "utf-8" To sOutput
    Get ComLastMethodSuccess Of hoSsh To bTemp1
    If (bTemp1 = False) Begin
        Get ComLastErrorText Of hoSsh To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Showln sOutput

    Send ComDisconnect To hoSsh


End_Procedure