How to structure ssh code to re use it along my program

Hi,
I am pretty new to golang, so not sure how to structure my code.
What I have is a program that connects to different servers and does some stuff there, like listing a file, creating a directory, uploading a file, executing a command… But those steps are not sequential, so what I am doing now is configuring and establishing the connection every time I need this.

auths = append(auths, ssh.Password(backupServerPasswd))
	config_destination := &ssh.ClientConfig{
		User: backupServerUser,
		Auth: auths,
	}

client_destination, err := ssh.Dial("tcp", backupServerURL, config_destination)

sftp_destination, err := sftp.NewClient(client_destination)

So what I am wondering is whether would be better to have a function that sets everything up and then I just call this function when I need to do something (since I am doing stuff in to different servers, I guess I would need two functions.)

Cheers

I would probably wrap up the stuff related to a single connection into a type:

import (
	"github.com/pkg/sftp"
	"golang.org/x/crypto/ssh"
)

type connection struct {
	config *ssh.ClientConfig
	ssh    *ssh.Client
	*sftp.Client
	*ssh.Session
}

func Dial(config *ssh.ClientConfig, url string) (*connection, error) {
	conn := &connection{
		config: config,
	}

	var err error
	conn.ssh, err = ssh.Dial("tcp", url, config)
	if err != nil {
		return nil, err
	}

	conn.Session, err = conn.ssh.NewSession()
	if err != nil {
		return nil, err
	}

	conn.Client, err = sftp.NewClient(conn.ssh)
	if err != nil {
		return nil, err
	}

	return conn, nil
}

Methods not shared by sftp.Client and ssh.Session can be called on connection, e.g., conn.Mkdir(path). Shared methods need to be called with, e.g., conn.Session.Close(); though you should consider writing wrappers for those. conn.Close() would ideally close all the related resources.

Then you can name the connections after the servers and get code like backupServer.Mkdir(path).

If you need to deal with reconnecting, you can add that code into wrapper functions on connection.

Hope this helps.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.