Sample code for 30+ languages & platforms
Swift

Get Received SSH Text into a StringBuilder

See more SSH Examples

Demonstrates the Chilkat Ssh.GetReceivedSb method, which decodes a channel's receive buffer and appends the text to a StringBuilder. The arguments are the channel number, the charset, and the StringBuilder. The receive buffer is cleared afterward.

Background: Because this appends rather than replaces, it is the natural choice for accumulating output across repeated reads — call it in a loop and the StringBuilder grows into the complete transcript. It also avoids creating a new string on every retrieval, which matters when a command produces a large amount of text.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    //  Demonstrates the Ssh.GetReceivedSb method, which decodes the channel's receive buffer and
    //  appends the text to a StringBuilder.  The 1st argument is the channel number, the 2nd is the
    //  charset, and the 3rd is the StringBuilder.  The receive buffer is cleared afterward.

    let ssh = CkoSsh()!

    var sshPort: Int = 22
    success = ssh.connect(hostname: "ssh.example.com", port: sshPort)
    if success == false {
        print("\(ssh.lastErrorText!)")
        return
    }

    //  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.
    var password: String? = "mySshPassword"

    success = ssh.authenticatePw(login: "mySshLogin", password: password)
    if success == false {
        print("\(ssh.lastErrorText!)")
        return
    }

    var channelNum: Int = ssh.openSessionChannel().intValue
    if channelNum < 0 {
        print("\(ssh.lastErrorText!)")
        return
    }

    success = ssh.sendReqExec(channelNum: channelNum, command: "ls -l /tmp")
    if success == false {
        print("\(ssh.lastErrorText!)")
        return
    }

    //  IMPORTANT: Set a read timeout.  ReadTimeoutMs defaults to 0, which means no limit -- without
    //  it, this call waits forever if the server never sends channel close.
    ssh.readTimeoutMs = 15000

    success = ssh.channelReceive(toClose: channelNum)
    if success == false {
        print("\(ssh.lastErrorText!)")
        return
    }

    //  Append the received text to a StringBuilder.  Existing content is preserved.
    let sb = CkoStringBuilder()!
    success = ssh.getReceivedSb(channelNum: channelNum, charset: "utf-8", sb: sb)
    if success == false {
        print("\(ssh.lastErrorText!)")
        return
    }

    print("Characters received: \(sb.length.intValue)")
    var output: String? = sb.getAsString()
    print("\(output!)")

    ssh.disconnect()

}