gosh

package module
v0.1.13 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 19, 2023 License: MIT Imports: 13 Imported by: 0

README

gosh

A simple SSH client for Go. Inspired by melbahja/goph. Migrated from golib.

Go Report Card release license

Getting Started

Run a command via ssh:

package main

import (
	"context"
	"log"
	"time"
	
	"github.com/shipengqi/gosh"
)

func main() {

	// Creates an Options with default parameters.
	opts := gosh.NewOptions()
	// Start connection with private key
	opts.Key = "your private key"
	
	// Start connection with password
	// opts.Username = "your username"
	// opts.Password = "your password"
	
	// Start connection with SSH agent (Unix systems only):
	// opts.UseAgent = true
	
	// Creates a Client that does not verify the server keys
	cli, err := gosh.NewInsecure(opts)
	if err != nil {
		log.Fatal(err)
	}
	err = cli.Dial()
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = cli.Close() }()
	
	cmd, err := cli.Command("echo", "Hello, world!")
	if err != nil {
		log.Fatal(err)
	}
	// Executes your command and returns its standard output.
	output, err := cmd.Output()
	if err != nil {
		log.Fatal(err)
	}

	log.Println(string(output))

	// Executes your command with context.
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
	defer cancel()
	cmd, err = cli.CommandContext(ctx, "echo", "Hello, world!")
	if err != nil {
		log.Fatal(err)
	}

	output, err = cmd.Output()
	if err != nil {
		log.Fatal(err)
	}
	log.Println(string(output))
}
Upload Local File to Remote:
err := client.Upload("/path/to/local/file", "/path/to/remote/file")
Download Remote File to Local:
err := client.Download("/path/to/remote/file", "/path/to/local/file")
ReadFile Read Remote File:
data, err := client.ReadFile("/path/to/remote/file")
Execute Bash Commands:
output, _ := client.CombinedOutput("echo \"Hello, world!\"")
Setenv

To set the environment variables in the ssh session using the Setenv method, it is important to note that This needs to be added to the SSH server side configuration /etc/ssh/sshd_config, as follows

AcceptEnv EXAMPLE_ENV_NAME
File System Operations Via SFTP:
// Create a sftp with options
sftp, _ := cli.NewSftp()
file, _ := sftp.Create("/tmp/remote_file")

file.Write([]byte(`Hello world`))
file.Close()

For more file operations see SFTP Docs.

Documentation

You can find the docs at go docs.

Test

Test with password:

go test -v . -addr <host> -user <username> -pass <password>

Test with private key:

go test -v . -addr <host> -ssh-key <private key>

Documentation

Overview

Package gosh provides a simple SSH client for Go.

Index

Constants

This section is empty.

Variables

View Source
var (
	// DefaultUsername default user of ssh client connection.
	DefaultUsername = "root"

	// DefaultTimeout default timeout of ssh client connection.
	DefaultTimeout = 20 * time.Second

	// DefaultPort default port of ssh client connection.
	DefaultPort     = 22
	DefaultProtocol = "tcp"
)
View Source
var ErrNilSession = errors.New("could not start with nil session, use SetSession() to set a session")

Functions

func Agent

func Agent() (ssh.AuthMethod, error)

Agent returns ssh.AuthMethod of ssh agent, (Unix systems only).

func AppendKnownHost

func AppendKnownHost(fpath, host string, remote net.Addr, key ssh.PublicKey) error

AppendKnownHost appends a host to known hosts file.

func Auth

func Auth(opts *Options) (ssh.AuthMethod, error)

Auth returns a single ssh.AuthMethod.

func AutoFixedHostKeyCallback

func AutoFixedHostKeyCallback(host string, remote net.Addr, key ssh.PublicKey) error

func DefaultHostKeyCallback

func DefaultHostKeyCallback() (ssh.HostKeyCallback, error)

DefaultHostKeyCallback returns host key callback from default known_hosts file.

func DefaultKnownHostsPath

func DefaultKnownHostsPath() (string, error)

DefaultKnownHostsPath returns the path of default knows_hosts file.

func GetSigner

func GetSigner(sshkey, passphrase string) (signer ssh.Signer, err error)

GetSigner returns ssh.Signer from private key file.

func HasAgent

func HasAgent() bool

HasAgent checks if ssh agent exists.

func Key

func Key(sshkey string, passphrase string) (ssh.AuthMethod, error)

Key returns ssh.AuthMethod from private key file.

func Password

func Password(pass string) ssh.AuthMethod

Password returns ssh.AuthMethod of password.

func Ping

func Ping(opts *Options) error

func VerifyKnownHost

func VerifyKnownHost(fpath, host string, remote net.Addr, key ssh.PublicKey) (bool, error)

VerifyKnownHost reports whether the given host in known hosts file and valid.

Types

type Client

type Client struct {
	*ssh.Client
	// contains filtered or unexported fields
}

Client SSH client.

func New

func New(opts *Options) (*Client, error)

New creates a Client without ssh.HostKeyCallback.

func NewDefault

func NewDefault(opts *Options) (*Client, error)

NewDefault creates a Client with DefaultHostKeyCallback, the host public key must be in known hosts.

func NewInsecure

func NewInsecure(opts *Options) (*Client, error)

NewInsecure creates a Client that does not verify the server keys.

func (*Client) Close

func (c *Client) Close() error

Close client ssh connection.

func (*Client) CombinedOutput

func (c *Client) CombinedOutput(command string) ([]byte, error)

CombinedOutput runs cmd on the remote host and returns its combined standard output and standard error.

func (*Client) CombinedOutputContext

func (c *Client) CombinedOutputContext(ctx context.Context, command string) ([]byte, error)

CombinedOutputContext is like CombinedOutput but includes a context.

The provided context is used to kill the process (by calling os.Process.Kill) if the context becomes done before the command completes on its own.

func (*Client) Command

func (c *Client) Command(name string, args ...string) (*Cmd, error)

Command returns the Cmd struct to execute the named program with the given arguments.

It sets only the Path and Args in the returned structure.

func (*Client) CommandContext

func (c *Client) CommandContext(ctx context.Context, name string, args ...string) (*Cmd, error)

CommandContext is like Command but includes a context.

The provided context is used to kill the process (by calling os.Process.Kill) if the context becomes done before the command completes on its own.

func (*Client) Dial

func (c *Client) Dial() error

Dial starts a client connection to the given SSH server.

func (*Client) Download

func (c *Client) Download(src, dst string) error

Download equivalent to the command `scp <host>:<src> <dst>`.

func (*Client) NewSftp

func (c *Client) NewSftp(opts ...sftp.ClientOption) (*sftp.Client, error)

NewSftp returns new sftp client and error if any.

func (*Client) Ping

func (c *Client) Ping() error

Ping alias for Dial.

func (*Client) ReadFile added in v0.1.6

func (c *Client) ReadFile(src string) ([]byte, error)

ReadFile reads the file named by filename and returns the contents.

func (*Client) Upload

func (c *Client) Upload(src, dst string) error

Upload equivalent to the command `scp <src> <host>:<dst>`.

func (*Client) WithHostKeyCallback

func (c *Client) WithHostKeyCallback(callback ssh.HostKeyCallback) *Client

WithHostKeyCallback sets ssh.HostKeyCallback of Client.

type Cmd

type Cmd struct {
	// Path is the path of the command to run.
	//
	// This is the only field that must be set to a non-zero
	// value. If Path is relative, it is evaluated relative
	// to Dir.
	Path string

	// Args holds command line arguments.
	// If the Args field is empty or nil, Run uses {Path}.
	//
	// In typical use, both Path and Args are set by calling Command.
	Args []string
	// contains filtered or unexported fields
}

Cmd represents an external command being prepared or run.

A Cmd cannot be reused after calling its Run, Output or CombinedOutput methods.

func (*Cmd) CombinedOutput

func (c *Cmd) CombinedOutput() ([]byte, error)

CombinedOutput runs cmd on the remote host and returns its combined standard output and standard error.

func (*Cmd) Output

func (c *Cmd) Output() ([]byte, error)

Output runs cmd on the remote host and returns its standard output.

func (*Cmd) OutputPipe

func (c *Cmd) OutputPipe(fn func(reader io.Reader) error) error

OutputPipe runs cmd on the remote host. The reader is a pipe that will be connected to the remote command's standard output when the command starts.

func (*Cmd) Run

func (c *Cmd) Run() error

Run runs cmd on the remote host.

func (*Cmd) SetSession

func (c *Cmd) SetSession(session *ssh.Session)

SetSession sets ssh.Session of the command.

func (*Cmd) Setenv

func (c *Cmd) Setenv(env []string) (err error)

Setenv sets session env vars. env specifies the environment of the process. Each entry is of the form "key=value", and will be ignored if it is not. Note: the server must be configured to `AcceptEnv line`.

func (*Cmd) String

func (c *Cmd) String() string

String returns a human-readable description of c.

type Options

type Options struct {
	Username      string
	Password      string
	Key           string
	KeyPassphrase string
	Addr          string
	Port          int
	UseAgent      bool
	Timeout       time.Duration
}

Options for SSH Client.

func NewOptions

func NewOptions() *Options

NewOptions creates an Options with default parameters.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL