goph

package module
v0.0.0-...-c5ee258 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2025 License: MIT Imports: 15 Imported by: 0

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...
  • Supports context.Context for command cancellation.

📄  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 timeout:
context, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
// will send SIGINT and return error after 1 second
out, err := client.RunContext(ctx, "sleep 5")
☛ 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")

// or with context:
// cmd, err := client.CommandContext(ctx, "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

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

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

func DefaultKnownHostsPath() (string, error)

DefaultKnownHostsPath returns default user knows hosts file.

func GetSigner

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

GetSigner returns ssh signer from private key file.

func GetSignerForRawKey

func GetSignerForRawKey(privateKey []byte, passphrase string) (ssh.Signer, error)

GetSignerForRawKey returns ssh signer from private key file.

func HasAgent

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 KeyboardInteractive

func KeyboardInteractive(pass string) Auth

KeyboardInteractive returns password keyboard interactive auth method as fallback of password auth method.

func Password

func Password(pass string) Auth

Password returns password auth method.

func RawKey

func RawKey(privateKey string, passphrase string) (Auth, error)

func UseAgent

func UseAgent() (Auth, error)

UseAgent auth via ssh agent, (Unix systems only)

func UseAgentSelect

func UseAgentSelect(pubkey []byte) (Auth, error)

UseAgent auth via ssh agent, select specific key from all to avoid too many auth failures (Unix systems only)

type Client

type Client struct {
	*ssh.Client
	Config *Config
}

func NewClient

func NewClient(c *Config) (*Client, error)

func (Client) Close

func (c Client) Close() error

Close client net connection.

func (Client) Command

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

Command returns new Cmd and error if any.

func (Client) CommandContext

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

Command returns new Cmd with context 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

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) RunContext

func (c Client) RunContext(ctx context.Context, name string) ([]byte, error)

Run starts a new SSH session with context 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

type Cmd struct {

	// Path to command executable filename
	Path string

	// Command args.
	Args []string

	// Session env vars.
	Env []string

	// SSH session.
	*ssh.Session

	// Context for cancellation
	Context context.Context
}

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

func (*Cmd) CombinedOutput

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

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

func (*Cmd) Output

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

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

func (*Cmd) Run

func (c *Cmd) Run() error

Run runs cmd on the remote host.

func (*Cmd) Start

func (c *Cmd) Start() error

Start runs the command on the remote host.

func (*Cmd) String

func (c *Cmd) String() string

String return the command line string.

type Config

type Config struct {
	Auth         Auth
	Protocol     string
	Addr         string
	Port         uint
	ClientConfig *ssh.ClientConfig
}

func NewConfig

func NewConfig(user string, addr string, port uint, auth Auth) (*Config, error)

Directories

Path Synopsis
examples
goph command

Jump to

Keyboard shortcuts

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