sshclient

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 5, 2023 License: MIT Imports: 13 Imported by: 21

README

simple sshclient with golang

GoDoc

This package implemented a ssh client. It can run remote command, execute remote script, request terminal and request non-interactive shell simply.

install package

# The -u flag instructs get to update modules providing dependencies
# of packages named on the command line to use newer minor or patch
# releases when available.
go get -u github.com/helloyi/go-sshclient

create a ssh client

  • Dial with passwd
client, err := DialWithPasswd("host:port", "username", "passwd")
if err != nil {
  handleErr(err)
}
defer client.Close()
  • Dial with private key
client, err := DialWithKey("host:port", "username", "prikeyFile")
if err != nil {
  handleErr(err)
}
defer client.Close()
  • Dial with private key and a passphrase to decrypt the key
client, err := DialWithKeyWithPassphrase("host:port", "username", "prikeyFile", "my-passphrase"))
if err != nil {
  handleErr(err)
}
defer client.Close()
  • Dial
config := &ssh.ClientConfig{
	User: user,
	Auth: []ssh.AuthMethod{
		ssh.Password("yourpasswd"),
	},
}
client, err := Dial("network", "host:port", config)
if err != nil {
  handleErr(err)
}
defer client.Close()
  • Dial from remote host

To PR

client0, err := Dial("tcp", "host:port", config{})
if err != nil {
  handleErr(err)
}
defer client0.Close()

client, err := client0.Dail("tcp", "host:port", config{})
if err != nil {
  handleErr(err)
}
defer client.Close()

execute commmand

  • Don't care about output, calling Run
// run one command
if err := client.Cmd("cmd").Run(); err {
  handleErr(err)
}

// run muti command one time
// if there is a command run err, and the next commands will not run
if err := client.Cmd("cmd1").Cmd("cmd2").Cmd("cmd3").Run(); err != nil {
  handleErr(err)
}
  • Get output, calling Output
out, err := client.Cmd("cmd").Output()
if err != nil {
  handleErr(err)
}
fmt.Println(string(out))
  • Return stderr message, when execution error, calling SmartOutput
out, err := client.Cmd("cmd").SmartOutput()
if err != nil {
  // the 'out' is stderr output
  handleErr(err, out)
}
// the 'out' is stdout output
fmt.Println(string(out))
  • Write stdout and stderr to your buffer, calling SetStdio
var (
  stdout bytes.Buffer
  stderr bytes.Buffer
)

if err := client.Cmd("cmd").SetStdio(&stdout, &stderr).Run(); err {
  handleErr(err)
}

// get it
fmt.Println(string(stdout))
fmt.Println(string(stderr))

execute script

  • Run script
script = `
  statment1
  statment2
`

// It's as same as Cmd
client.Script(script).Run()
client.Script(script).Output()
client.Script(script).SmartOutput()
  • Run a shell script file
client.ScriptFile("/path/to/the/script").Run()
client.ScriptFile("/path/to/the/script").Output()
client.ScriptFile("/path/to/the/script").SmartOutput()

get shell

  • Get a non-interactive shell
if err := client.Shell().Start(); err != nil {
  handleErr(err)
}
  • Get a interactive shell
// default terminal
if err := client.Terminal(nil).Start(); err != nil {
  handleErr(err)
}

// with a terminal config
config := &sshclient.TerminalConfig {
  Term: "xterm",
  Height: 40,
  Weight: 80,
  Modes: ssh.TerminalModes {
	  ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
	  ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
  }
}
if err := client.Terminal(config).Start(); err != nil {
  handleErr(err)
}
  • And sometimes, you could set your stdio buffer
var (
  stdin  bytes.Buffer
  stdout bytes.Buffer
  stderr bytes.Buffer
)

// Now, it's like client.Script("script").Run()
stdin.NewBufferString("script")
if err := client.Shell().SetStdio(&stdin, &stdout, &stderr).Start(); err != nil {
  handleErr(err)
}

fmt.Println(stdout.String())
fmt.Println(stderr.String())

remote file operations

Use sftp := client.Sftp() to obtain a RemoteFileSystem. Use sftp.Closer() to close it after use, sftp can be passively closed using the client.Close() if it is used during the client lifetime.

Because it is designed to have a one-to-one configuration-to-instance relationship, you can obtain the same RemoteFileSystem everywhere with the same configuration. Here is an example of the code:

// The following are the same Sftp specified by opts
opts := []client.SftpOption{client.SftpMaxPacket(16384)}
wd, err := client.Sftp(opts...).Getwd()
// ...
err := client.Sftp(opts...).Mkdir("path")
// ...
client.Sftp(opts...).Close()
upload file
  • Get a RemoteFileSystem
sftp := client.Sftp()
  • Then upload local file to remote
// upload
if err := sftp.Upload("host/file/path","remote/file/path"); err != nil {
  handleErr(err)
}
  • Close RemoteFileSystem
if err := sftp.Close(); err != nil {
  handleErr(err)
}

Documentation

Overview

Package sshclient implements an SSH client.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

A Client implements an SSH client that supports running commands and scripts remotely.

func Dial

func Dial(network, addr string, config *ssh.ClientConfig) (*Client, error)

Dial starts a client connection to the given SSH server. This wraps ssh.Dial.

func DialWithKey

func DialWithKey(addr, user, keyfile string) (*Client, error)

DialWithKey starts a client connection to the given SSH server with key authmethod.

func DialWithKeyWithPassphrase

func DialWithKeyWithPassphrase(addr, user, keyfile string, passphrase string) (*Client, error)

DialWithKeyWithPassphrase same as DialWithKey but with a passphrase to decrypt the private key

func DialWithPasswd

func DialWithPasswd(addr, user, passwd string) (*Client, error)

DialWithPasswd starts a client connection to the given SSH server with passwd authmethod.

func (*Client) Close

func (c *Client) Close() error

Close closes the underlying client network connection.

func (*Client) Cmd

func (c *Client) Cmd(cmd string) *RemoteScript

Cmd creates a RemoteScript that can run the command on the client. The cmd string is split on newlines and each line is executed separately.

func (*Client) Dial added in v1.2.0

func (c *Client) Dial(network, addr string, config *ssh.ClientConfig) (*Client, error)

Dial initiates a Client to the addr from the remote host.

func (*Client) Script

func (c *Client) Script(script string) *RemoteScript

Script creates a RemoteScript that can run the script on the client.

func (*Client) ScriptFile

func (c *Client) ScriptFile(fname string) *RemoteScript

ScriptFile creates a RemoteScript that can read a local script file and run it remotely on the client.

func (*Client) Sftp added in v1.2.0

func (c *Client) Sftp(opts ...SftpOption) *RemoteFileSystem

Sftp creates a new SFTP session, using zero or more option functions.

func (*Client) Shell

func (c *Client) Shell() *RemoteShell

Shell create a noninteractive shell on client.

func (*Client) Terminal

func (c *Client) Terminal(config *TerminalConfig) *RemoteShell

Terminal create a interactive shell on client.

func (*Client) UnderlyingClient added in v1.1.0

func (c *Client) UnderlyingClient() *ssh.Client

UnderlyingClient get the underlying client.

type RemoteFile added in v1.2.0

type RemoteFile struct {
	*sftp.File
}

RemoteFile represents a remote file.

type RemoteFileSystem added in v1.2.0

type RemoteFileSystem struct {
	// contains filtered or unexported fields
}

RemoteFileSystem represents a remoote file system.

func (*RemoteFileSystem) Chmod added in v1.2.0

func (rfs *RemoteFileSystem) Chmod(path string, mode os.FileMode) error

func (*RemoteFileSystem) Chown added in v1.2.0

func (rfs *RemoteFileSystem) Chown(path string, uid, gid int) error

func (*RemoteFileSystem) Chtimes added in v1.2.0

func (rfs *RemoteFileSystem) Chtimes(path string, atime time.Time, mtime time.Time) error

func (*RemoteFileSystem) Close added in v1.2.0

func (rfs *RemoteFileSystem) Close() error

Close closes the SFTP session.

func (*RemoteFileSystem) Create added in v1.2.0

func (rfs *RemoteFileSystem) Create(path string) (*RemoteFile, error)

func (*RemoteFileSystem) Download added in v1.2.0

func (rfs *RemoteFileSystem) Download(remotePath, hostPath string) (retErr error)

func (*RemoteFileSystem) Getwd added in v1.2.0

func (rfs *RemoteFileSystem) Getwd() (string, error)

func (*RemoteFileSystem) Glob added in v1.2.0

func (rfs *RemoteFileSystem) Glob(pattern string) (matches []string, err error)
func (rfs *RemoteFileSystem) Link(oldname, newname string) error

func (*RemoteFileSystem) Lstat added in v1.2.0

func (rfs *RemoteFileSystem) Lstat(path string) (os.FileInfo, error)

func (*RemoteFileSystem) Mkdir added in v1.2.0

func (rfs *RemoteFileSystem) Mkdir(path string) error

func (*RemoteFileSystem) MkdirAll added in v1.2.0

func (rfs *RemoteFileSystem) MkdirAll(path string) error

func (*RemoteFileSystem) Open added in v1.2.0

func (rfs *RemoteFileSystem) Open(path string) (*RemoteFile, error)

func (*RemoteFileSystem) OpenFile added in v1.2.0

func (rfs *RemoteFileSystem) OpenFile(path string, f int) (*RemoteFile, error)

func (*RemoteFileSystem) PosixRename added in v1.2.0

func (rfs *RemoteFileSystem) PosixRename(oldname, newname string) error

func (*RemoteFileSystem) ReadDir added in v1.2.0

func (rfs *RemoteFileSystem) ReadDir(path string) ([]os.FileInfo, error)

func (*RemoteFileSystem) ReadFile added in v1.2.0

func (rfs *RemoteFileSystem) ReadFile(name string) ([]byte, error)
func (rfs *RemoteFileSystem) ReadLink(path string) (string, error)

func (*RemoteFileSystem) RealPath added in v1.2.0

func (rfs *RemoteFileSystem) RealPath(path string) (string, error)

func (*RemoteFileSystem) Remove added in v1.2.0

func (rfs *RemoteFileSystem) Remove(path string) error

func (*RemoteFileSystem) RemoveDirectory added in v1.2.0

func (rfs *RemoteFileSystem) RemoveDirectory(path string) error

func (*RemoteFileSystem) Rename added in v1.2.0

func (rfs *RemoteFileSystem) Rename(oldname, newname string) error

func (*RemoteFileSystem) Stat added in v1.2.0

func (rfs *RemoteFileSystem) Stat(path string) (os.FileInfo, error)

func (*RemoteFileSystem) StatVFS added in v1.2.0

func (rfs *RemoteFileSystem) StatVFS(path string) (*StatVFS, error)
func (rfs *RemoteFileSystem) Symlink(oldname, newname string) error

func (*RemoteFileSystem) Truncate added in v1.2.0

func (rfs *RemoteFileSystem) Truncate(path string, size int64) error

func (*RemoteFileSystem) Upload added in v1.2.0

func (rfs *RemoteFileSystem) Upload(hostPath, remotePath string) (retErr error)

func (*RemoteFileSystem) Wait added in v1.2.0

func (rfs *RemoteFileSystem) Wait() error

func (*RemoteFileSystem) Walk added in v1.2.0

func (rfs *RemoteFileSystem) Walk(root string) (*fs.Walker, error)

func (*RemoteFileSystem) WriteFile added in v1.2.0

func (rfs *RemoteFileSystem) WriteFile(name string, data []byte, perm os.FileMode) error

type RemoteScript

type RemoteScript struct {
	// contains filtered or unexported fields
}

A RemoteScript represents script that can be run remotely.

func (*RemoteScript) Cmd

func (rs *RemoteScript) Cmd(cmd string) *RemoteScript

Cmd appends a command to the RemoteScript.

func (*RemoteScript) Output

func (rs *RemoteScript) Output() ([]byte, error)

Output runs the script on the client and returns its standard output.

func (*RemoteScript) Run

func (rs *RemoteScript) Run() error

Run runs the script on the client.

The returned error is nil if the command runs, has no problems copying stdin, stdout, and stderr, and exits with a zero exit status.

func (*RemoteScript) SetStdio

func (rs *RemoteScript) SetStdio(stdout, stderr io.Writer) *RemoteScript

SetStdio specifies where its standard output and error data will be written.

func (*RemoteScript) SmartOutput

func (rs *RemoteScript) SmartOutput() ([]byte, error)

SmartOutput runs the script on the client. On success, its standard ouput is returned. On error, its standard error is returned.

type RemoteShell

type RemoteShell struct {
	// contains filtered or unexported fields
}

A RemoteShell represents a login shell on the client.

func (*RemoteShell) SetStdio

func (rs *RemoteShell) SetStdio(stdin io.Reader, stdout, stderr io.Writer) *RemoteShell

SetStdio specifies where the its standard output and error data will be written.

func (*RemoteShell) Start

func (rs *RemoteShell) Start() error

Start starts a remote shell on client.

type SftpOption added in v1.2.0

type SftpOption func(*remoteFileSystemConfig)

func SftpMaxConcurrentRequestsPerFile added in v1.2.0

func SftpMaxConcurrentRequestsPerFile(n int) SftpOption

func SftpMaxPacket added in v1.2.0

func SftpMaxPacket(size int) SftpOption

func SftpUseConcurrentReads added in v1.2.0

func SftpUseConcurrentReads(value bool) SftpOption

func SftpUseConcurrentWrites added in v1.2.0

func SftpUseConcurrentWrites(value bool) SftpOption

func SftpUseFstat added in v1.2.0

func SftpUseFstat(value bool) SftpOption

type StatVFS added in v1.2.0

type StatVFS struct {
	*sftp.StatVFS
}

type TerminalConfig

type TerminalConfig struct {
	Term   string
	Height int
	Weight int
	Modes  ssh.TerminalModes
}

A TerminalConfig represents the configuration for an interactive shell session.

Jump to

Keyboard shortcuts

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