README ¶
gosh
A simple SSH client for Go. Inspired by melbahja/goph. Migrated from golib.
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 ¶
- Variables
- func Agent() (ssh.AuthMethod, error)
- func AppendKnownHost(fpath, host string, remote net.Addr, key ssh.PublicKey) error
- func Auth(opts *Options) (ssh.AuthMethod, error)
- func AutoFixedHostKeyCallback(host string, remote net.Addr, key ssh.PublicKey) error
- func DefaultHostKeyCallback() (ssh.HostKeyCallback, error)
- func DefaultKnownHostsPath() (string, error)
- func GetSigner(sshkey, passphrase string) (signer ssh.Signer, err error)
- func HasAgent() bool
- func Key(sshkey string, passphrase string) (ssh.AuthMethod, error)
- func Password(pass string) ssh.AuthMethod
- func Ping(opts *Options) error
- func VerifyKnownHost(fpath, host string, remote net.Addr, key ssh.PublicKey) (bool, error)
- type Client
- func (c *Client) Close() error
- func (c *Client) CombinedOutput(command string) ([]byte, error)
- func (c *Client) CombinedOutputContext(ctx context.Context, command string) ([]byte, error)
- func (c *Client) Command(name string, args ...string) (*Cmd, error)
- func (c *Client) CommandContext(ctx context.Context, name string, args ...string) (*Cmd, error)
- func (c *Client) Dial() error
- func (c *Client) Download(src, dst string) error
- func (c *Client) NewSftp(opts ...sftp.ClientOption) (*sftp.Client, error)
- func (c *Client) Ping() error
- func (c *Client) ReadFile(src string) ([]byte, error)
- func (c *Client) Upload(src, dst string) error
- func (c *Client) WithHostKeyCallback(callback ssh.HostKeyCallback) *Client
- type Cmd
- type Options
Constants ¶
This section is empty.
Variables ¶
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" )
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 ¶
AppendKnownHost appends a host to known hosts file.
func DefaultHostKeyCallback ¶
func DefaultHostKeyCallback() (ssh.HostKeyCallback, error)
DefaultHostKeyCallback returns host key callback from default known_hosts file.
func DefaultKnownHostsPath ¶
DefaultKnownHostsPath returns the path of default knows_hosts file.
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.
Types ¶
type Client ¶
Client SSH client.
func NewDefault ¶
NewDefault creates a Client with DefaultHostKeyCallback, the host public key must be in known hosts.
func NewInsecure ¶
NewInsecure creates a Client that does not verify the server keys.
func (*Client) CombinedOutput ¶
CombinedOutput runs cmd on the remote host and returns its combined standard output and standard error.
func (*Client) CombinedOutputContext ¶
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 ¶
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 ¶
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) ReadFile ¶ added in v0.1.6
ReadFile reads the file named by filename and returns the contents.
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 ¶
CombinedOutput runs cmd on the remote host and returns its combined standard output and standard error.
func (*Cmd) OutputPipe ¶
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) SetSession ¶
SetSession sets ssh.Session of the command.