golang

Golang SSH Examples

Secure Shell or SSH is a secure network protocol that allows remote logins of devices in a secure connection.  SSH is one of the most useful and popular network protocols over recent years.

In this article, we will discuss how you can use going to work with SSH protocol.

Golang SSH Package

In this tutorial, we will use the crypto/SSH package. You can import the package as:

import "golang.org/x/crypto/ssh"

SSH Client

We will start by building an SSH client that takes the address of a remote SSH server and connects to it.

Consider the code example as shown below:

package main
import (
    "log"

    "golang.org/x/crypto/ssh"
    "golang.org/x/crypto/ssh/knownhosts"
)

func main() {
    // ssh config
    hostKeyCallback, err := knownhosts.New("/home/debian11/.ssh/known_hosts")
    if err != nil {
        log.Fatal(err)
    }
    config := &ssh.ClientConfig{
        User: "ubuntu",
        Auth: []ssh.AuthMethod{
            ssh.Password("password"),
        },
        HostKeyCallback: hostKeyCallback,
    }
    // connect ot ssh server
    conn, err := ssh.Dial("tcp", "192.168.205.217:22", config)
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()
}

In the previous code example, we start by importing the required modules. We import the crypto/SSH and crypto/knownhosts to connect to the SSH server and parse the host key.

We then create a new host key using the knownhosts.New() method. The function returns a host key callback from the specified host key files.

Next, we create config to log in to the server. This is a structure holding information, such as user and auth method.

The last step is to dial the connection to the server using the ssh.Dial() method.

Create Session

We can create a session using the NewSession method. A code example code is as shown below:

    session, err := conn.NewSession()
    if err != nil {
        log.Fatal(err)
    }
    defer session.Close()

Request Pty

Consider the code example provided below:

    // configure terminal mode
    modes := ssh.TerminalModes{
        ssh.ECHO:          0,     // supress echo

    }
    // run terminal session
    if err := session.RequestPty("xterm", 50, 80, modes); err != nil {
        log.Fatal(err)
    }
    // start remote shell
    if err := session.Shell(); err != nil {
        log.Fatal(err)
    }

In the previous example, we configure the terminal modes. Although you can use the default parameters, in this example, we set the ssh.ECHO value to 0. This prevents the shell from echoing commands back to you.

Next, we request a terminal session using the RequestPty() method. This takes the term as a string, and the height and width of the terminal session as integers and the terminal configuration mode.

Run Command

You can run a single command on the server once a session is established. For example:

var buff bytes.Buffer
session.Stdout = &buff
if err := session.Run(“ls -la”); err != nil {
    log.Fatal(err)
}
fmt.Println(buff.String())

In the previous example, we use the Run function to execute a command on the server.

An output example is shown below:

Conclusion

This guide covers the fundamentals of working with the SSH package in the Go programming language. In addition, creating a session using the NewSession method, requesting a terminal session using the RequestPty() method, and using the Run command were discussed. We hope you found this article helpful. Check out other Linux Hint articles for more tips and information.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list