goph

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 18, 2020 License: MIT Imports: 12 Imported by: 96

README

Golang SSH Client.

Fast and easy golang ssh client module.

Goph is a lightweight Go SSH client focusing on simplicity!

InstallationFeaturesUsageExamplesLicense

🚀  Installation and Documentation

go get github.com/melbahja/goph

You can find the docs at go docs.

🤘  Features

  • Easy to use and simple API.
  • Supports known hosts by default.
  • Supports connections with passwords.
  • Supports connections with private keys.
  • Supports connections with protected private keys with passphrase.
  • Supports upload files from local to remote.
  • Supports download files from remote to local.
  • Supports connections with ssh agent (Unix systems only).
  • Supports adding new hosts to known_hosts file.
  • Supports file system operations like: Open, Create, Chmod...

📄  Usage

Run a command via ssh:

package main

import (
	"log"
	"fmt"
	"github.com/melbahja/goph"
)

func main() {

	// Start new ssh connection with private key.
	auth, err := goph.Key("/home/mohamed/.ssh/id_rsa", "")
	if err != nil {
		log.Fatal(err)
	}

	client, err := goph.New("root", "192.1.1.3", auth)
	if err != nil {
		log.Fatal(err)
	}

	// Defer closing the network connection.
	defer client.Close()

	// Execute your command.
	out, err := client.Run("ls /tmp/")

	if err != nil {
		log.Fatal(err)
	}

	// Get your output as []byte.
	fmt.Println(string(out))
}
🔐 Start Connection With Protected Private Key:
auth, err := goph.Key("/home/mohamed/.ssh/id_rsa", "you_passphrase_here")
if err != nil {
	// handle error
}

client, err := goph.New("root", "192.1.1.3", auth)
🔑 Start Connection With Password:
client, err := goph.New("root", "192.1.1.3", goph.Password("you_password_here"))
☛ Start Connection With SSH Agent (Unix systems only):
auth, err := goph.UseAgent()
if err != nil {
	// handle error
}

client, err := goph.New("root", "192.1.1.3", auth)
⤴️ 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")
☛ Execute Bash Commands:
out, err := client.Run("bash -c 'printenv'")
☛ Execute Bash Command With Env Variables:
out, err := client.Run(`env MYVAR="MY VALUE" bash -c 'echo $MYVAR;'`)
🥪 Using Goph Cmd:

Goph.Cmd struct is like the Go standard os/exec.Cmd.

// Get new `Goph.Cmd`
cmd, err := client.Command("ls", "-alh", "/tmp")

if err != nil {
	// handle the error!
}

// You can set env vars, but the server must be configured to `AcceptEnv line`.
cmd.Env = []string{"MY_VAR=MYVALUE"}

// Run you command.
err = cmd.Run()

🗒️ Just like os/exec.Cmd you can run CombinedOutput, Output, Start, Wait, and ssh.Session methods like Signal...

📂 File System Operations Via SFTP:

You can easily get a SFTP client from Goph client:


sftp, err := client.NewSftp()

if err != nil {
	// handle the error!
}

file, err := sftp.Create("/tmp/remote_file")

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

🗒️ For more file operations see SFTP Docs.

🥙  Examples

See Examples.

🤝  Missing a Feature?

Feel free to open a new issue, or contact me.

📘  License

Goph is provided under the MIT License.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultTimeout = 20 * time.Second

DefaultTimeout is the timeout of ssh client connection.

Functions

func AddKnownHost added in v0.3.0

func AddKnownHost(host string, remote net.Addr, key ssh.PublicKey, knownFile string) (err error)

AddKnownHost add a a host to known hosts file.

func CheckKnownHost added in v0.3.0

func CheckKnownHost(host string, remote net.Addr, key ssh.PublicKey, knownFile string) (found bool, err error)

CheckKnownHost checks is host in known hosts file. it returns is the host found in known_hosts file and error, if the host found in known_hosts file and error not nil that means public key mismatch, maybe MAN IN THE MIDDLE ATTACK! you should not handshake.

func DefaultKnownHosts

func DefaultKnownHosts() (ssh.HostKeyCallback, error)

DefaultKnownHosts returns host key callback from default known hosts path, and error if any.

func DefaultKnownHostsPath added in v1.1.0

func DefaultKnownHostsPath() (string, error)

DefaultKnownHostsPath returns default user knows hosts file.

func Dial added in v0.9.0

func Dial(proto string, c *Config) (*ssh.Client, error)

Dial starts a client connection to SSH server based on config.

func GetSigner

func GetSigner(prvFile string, passphrase string) (ssh.Signer, error)

GetSigner returns ssh signer from private key file.

func HasAgent added in v0.9.0

func HasAgent() bool

HasAgent checks if ssh agent exists.

func KnownHosts

func KnownHosts(file string) (ssh.HostKeyCallback, error)

KnownHosts returns host key callback from a custom known hosts path.

Types

type Auth

type Auth []ssh.AuthMethod

Auth represents ssh auth methods.

func Key

func Key(prvFile string, passphrase string) (Auth, error)

Key returns auth method from private key with or without passphrase.

func Password

func Password(pass string) Auth

Password returns password auth method.

func UseAgent added in v0.3.0

func UseAgent() (Auth, error)

UseAgent auth via ssh agent, (Unix systems only)

type Client

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

Client represents Goph client.

func New

func New(user string, addr string, auth Auth) (c *Client, err error)

New starts a new ssh connection, the host public key must be in known hosts.

func NewConn

func NewConn(config *Config) (c *Client, err error)

NewConn returns new client and error if any.

func NewUnknown

func NewUnknown(user string, addr string, auth Auth) (*Client, error)

NewUnknown starts a ssh connection get client without cheking knownhosts. PLEASE AVOID USING THIS, UNLESS YOU KNOW WHAT ARE YOU DOING! if there a "man in the middle proxy", this can harm you! You can add the key to know hosts and use New() func instead!

func (Client) Close added in v0.2.0

func (c Client) Close() error

Close client net connection.

func (Client) Command added in v0.9.0

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

Command returns new Cmd and error if any.

func (Client) Download

func (c Client) Download(remotePath string, localPath string) (err error)

Download file from remote server!

func (Client) NewSftp added in v0.9.0

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

NewSftp returns new sftp client and error if any.

func (Client) Run

func (c Client) Run(cmd string) ([]byte, error)

Run starts a new SSH session and runs the cmd, it returns CombinedOutput and err if any.

func (Client) Upload

func (c Client) Upload(localPath string, remotePath string) (err error)

Upload a local file to remote server!

type Cmd added in v0.9.0

type Cmd struct {

	// Path to command executable filename
	Path string

	// Command args.
	Args []string

	// Session env vars.
	Env []string

	// SSH session.
	*ssh.Session
}

Cmd it's like os/exec.Cmd but for ssh session.

func (*Cmd) CombinedOutput added in v0.9.0

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

CombinedOutput runs cmd on the remote host and returns its combined stdout and stderr.

func (*Cmd) Output added in v0.9.0

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

Output runs cmd on the remote host and returns its stdout.

func (*Cmd) Run added in v0.9.0

func (c *Cmd) Run() error

Run runs cmd on the remote host.

func (*Cmd) Start added in v0.9.0

func (c *Cmd) Start() error

Start runs the command on the remote host.

func (*Cmd) String added in v0.9.0

func (c *Cmd) String() string

String return the command line string.

type Config added in v0.9.0

type Config struct {
	Auth     Auth
	User     string
	Addr     string
	Port     uint
	Timeout  time.Duration
	Callback ssh.HostKeyCallback
}

Config for Client.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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