Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
G

goph

> AI 编程
Open source

The native golang ssh client to execute your commands over ssh connection.

2.0K stars0 likes3 views
WebsiteGitHub

About

The native golang ssh client to execute your commands over ssh connection.

Features ❘ Installation ❘ Get Started ❘ Usage Examples ❘ License

  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 multiple auth methods in a single connection.
  • Supports upload files from local to remote.
  • Supports download files from remote to local.
  • Supports connections with ssh agent.
  • Supports connections with custom signers.
  • Supports adding new hosts to known_hosts file.
  • Supports host key callback check from default known_hosts file.
  • Supports file operations like: Open, Create, Chmod... via SFTP.
  • Supports context.Context for command cancellation.
  • Supports SOCKS5 proxy for connecting through intermediaries.
  • Supports proxy jump for connecting through jump hosts.

  Installation

bash
go get github.com/melbahja/goph/v2

  Get Started

Run a command via ssh can be simple as this example:

go
package main

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

func main() {

	// Start new ssh connection with private key.
	client, err := goph.New("root", "192.1.1.3", goph.WithPassword("try_password_first"))
	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))
}

Docs are available in Go Docs.

  Usage Examples

Expand each group then expand individual examples.

  Authentication Examples

Password Authentication
go
client, err := goph.New("root", "192.1.1.3",
	goph.WithPassword("your_password"),
)
Key File Authentication
go
client, err := goph.New("root", "192.1.1.3",
	goph.WithKeyFile("/home/user/.ssh/id_rsa", ""),
)
Protected Private Key (with Passphrase)
go
client, err := goph.New("root", "192.1.1.3",
	goph.WithKeyFile("/home/user/.ssh/id_rsa", "passphrase"),
)
Raw Private Key (from bytes)
go
privateKey, _ := os.ReadFile("/home/user/.ssh/id_rsa")
client, err := goph.New("root", "192.1.1.3",
	goph.WithKey(privateKey, "passphrase"),
)
SSH Agent (auto-detect)
go
if goph.HasAgent() {
	client, err := goph.New("root", "192.1.1.3",
		goph.WithDefaultAgent(),
	)
}
Custom Agent Socket Path
go
client, err := goph.New("root", "192.1.1.3",
	goph.WithAgentSocket("/run/user/1000/keyring/ssh"),
)
Custom Agent Connection (net.Conn)
go
conn, err := net.Dial("unix", "/custom/agent.sock")
if err != nil {
	log.Fatal(err)
}

client, err := goph.New("root", "192.1.1.3",
	goph.WithAgent(conn),
)
Keyboard-Interactive (password prompt)
go
client, err := goph.New("root", "192.1.1.3",
	goph.WithKeyboardInteractive(func(user, instruction, question string, echo bool) (string, error) {
		if strings.Contains(strings.ToLower(question), "password") {
			return "your_password", nil
		}
		return "", fmt.Errorf("unexpected prompt: %s", question)
	}),
)
Keyboard-Interactive OTP / 2FA
go
client, err := goph.New("root", "192.1.1.3",
	goph.WithKeyboardInteractive(func(user, instruction, question string, echo bool) (string, error) {
		if strings.Contains(strings.ToLower(question), "otp") ||
			strings.Contains(strings.ToLower(question), "verification code") {
			fmt.Print(question, " ")
			var code string
			fmt.Scanln(&code)
			return code, nil
		}
		return "", fmt.Errorf("unexpected prompt: %s", question)
	}),
)
Multiple Auth Methods
go
client, err := goph.New("root", "192.1.1.3",
	goph.WithPassword("try_password_first"),
	goph.WithKeyFile("/home/user/.ssh/id_rsa", "passphrase"),
	goph.WithDefaultAgent(),
)
Custom Signer (any ssh.Signer)
go
signer, err := ssh.NewSignerFromKey(myPrivateKey) // or from any source
if err != nil {
	log.Fatal(err)
}

client, err := goph.New("root", "192.1.1.3",
	goph.WithSigner(signer),
)
Custom Auth Method (ssh.AuthMethod)
go
client, err := goph.New("root", "192.1.1.3",
	goph.WithAuth(ssh.Password("pass")),
	goph.WithAuth(ssh.PublicKeysCallback(myCustomCallback)),
)

  Features Examples

Custom Port and Timeout
go
client, err := goph.New("root", "192.1.1.3",
	goph.WithPassword("pass"),
	goph.WithPort(2222),
	goph.WithTimeout(10*time.Second),
)
Known Hosts Verification (Default)
go
// Known hosts verification is ON by default via ~/.ssh/known_hosts
client, err := goph.New("root", "192.1.1.3",
	goph.WithPassword("pass"),
)

// Or specify a custom known_hosts file:
client, err := goph.New("root", "192.1.1.3",
	goph.WithPassword("pass"),
	goph.WithKnownHosts("/path/to/known_hosts"),
)
Disable Host Key Verification (Insecure)
go
client, err := goph.New("root", "192.1.1.3",
	goph.WithPassword("pass"),
	goph.WithInsecureIgnoreHostKey(),
)
Custom Host Key Callback
go
hostKeyCallback := func(hostname string, remote net.Addr, key ssh.PublicKey) error {
	// Check the key against a database or prompt the user
	return nil
}

client, err := goph.New("root", "192.1.1.3",
	goph.WithPassword("pass"),
	goph.WithHostKeyCallback(hostKeyCallback),
)
Banner Callback
go
client, err := goph.New("root", "192.1.1.3",
	goph.WithPassword("pass"),
	goph.WithBannerCallback(func(message string) error {
		log.Printf("SSH Banner: %s", message)
		return nil
	}),
)
Connect Through SOCKS5 Proxy
go
client, err := goph.New("root", "target-host",
	goph.WithPassword("pass"),
	goph.WithProxy("socks5://127.0.0.1:1080"),
)

// With proxy authentication:
client, err = goph.New("root", "target-host",
	goph.WithPassword("pass"),
	goph.WithProxy("socks5://proxyuser:[email protected]:1080"),
)
Connect Through Jump Host (Bastion)
go
// First connect to the jump host
jump, err := goph.New("jumpuser", "bastion.example.com",
	goph.WithKeyFile("/home/user/.ssh/id_rsa", ""),
	goph.WithPort(2222),
)
if err != nil {
	log.Fatal(err)
}
defer jump.Close()

// Then tunnel through it to the target
client, err := goph.New("root", "internal-host",
	goph.WithKeyFile("/home/user/.ssh/id_rsa", ""),
	goph.WithJump(jump),
)
Proxy + Jump Host Together
go
// Put the proxy on the JUMP client, then pass the jump to the target
jump, err := goph.New("jumpuser", "bastion.example.com",
	goph.WithKeyFile("/home/user/.ssh/id_rsa", ""),
	goph.WithProxy("socks5://127.0.0.1:1080"),
)
if err != nil {
	log.Fatal(err)
}
defer jump.Close()

client, err := goph.New("root", "internal-host",
	goph.WithKeyFile("/home/user/.ssh/id_rsa", ""),
	goph.WithJump(jump),
)
Run a Command
go
out, err := client.Run("ls /tmp/")
if err != nil {
	log.Fatal(err)
}
fmt.Println(string(out))
Run with Timeout (Context)
go
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()

// Sends SIGINT and returns error after 1 second
out, err := client.RunContext(ctx, "sleep 5")
Cancel from Another Goroutine
go
ctx, cancel := context.WithCancel(context.Background())
cmd, err := client.CommandContext(ctx, "sleep", "60")
if err != nil {
	log.Fatal(err)
}

// Cancel from another goroutine
go func() {
	time.Sleep(5 * time.Second)
	cancel()
}()

if err := cmd.Run(); err != nil {
	// context canceled
	fmt.Println("Command stopped:", err)
}
Custom Cancel Function (override SIGINT)
go
cmd, err := client.CommandContext(ctx, "sleep", "30")
if err != nil {
	log.Fatal(err)
}

// Send SIGKILL instead of the default SIGINT on cancellation
cmd.Cancel = func() error {
	return cmd.Signal(ssh.SIGKILL)
}

if err := cmd.Run(); err != nil {
	log.Fatal(err)
}
Using Cmd for Fine Control
go
cmd, err := client.Command("ls", "-alh", "/tmp")
if err != nil {
	log.Fatal(err)
}

// Set env vars (server must accept them)
cmd.Env = []string{"MY_VAR=MYVALUE"}

// Run (CombinedOutput, Output, Start, Wait also available)
err = cmd.Run()

// With context:
cmd, err = client.CommandContext(ctx, "ls", "-alh", "/tmp")
Upload File
go
err := client.Upload("/path/to/local/file", "/path/to/remote/file")
Download File
go
err := client.Download("/path/to/remote/file", "/path/to/local/file")
SFTP File Operations
go
sftp, err := client.NewSftp()
if err != nil {
	log.Fatal(err)
}
defer sftp.Close()

// Create a file
file, err := sftp.Create("/tmp/remote_file")
if err != nil {
	log.Fatal(err)
}
defer file.Close()

file.Write([]byte("Hello world"))

// Open existing file
f, _ := sftp.Open("/etc/hostname")
// ... read from f

// Other methods: MkdirAll, Remove, Rename, ReadDir, Stat, etc.
Execute a Script (streaming from io.Reader)
go
// Execute a script from any io.Reader (e.g. a string, a file handle, an HTTP body)
cmd, err := client.Script(ctx, strings.NewReader("echo hello"))
if err != nil {
	log.Fatal(err)
}
out, err := cmd.CombinedOutput()
Execute a Script File
go
// Read a local script file into memory and execute it on the remote host
cmd, err := client.ScriptFile(ctx, "/path/to/local/script.sh")
if err != nil {
	log.Fatal(err)
}

// Override the interpreter for a PHP script:
cmd, err = client.ScriptFile(ctx, "/path/to/script.php", goph.WithPath("/usr/bin/php"))

// Override the shell path (default: /bin/sh)
cmd, err = client.ScriptFile(ctx, "/path/to/local/script.sh", goph.WithPath("/bin/zsh"))
Override Config Before Dial
go
client, err := goph.New("root", "192.1.1.3",
	goph.WithPassword("pass"),
	goph.WithConfig(func(config *ssh.ClientConfig) error {
		config.Timeout = 30 * time.Second
		config.ClientVersion = "SSH-2.0-MyApp"
		return nil
	}),
)
Low-Level: Custom ssh.ClientConfig (Dial)
go
c := &goph.Client{
	User: "root",
	Addr: "192.1.1.3",
	Port: 22,
}

config := &ssh.ClientConfig{
	Auth:            []ssh.AuthMethod{ssh.Password("pass")},
	HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}

if err := goph.Dial(c, config); err != nil {
	log.Fatal(err)
}
defer c.Close()
Reusable Dialer (Multiple Connections)
go
d := goph.NewDialer(
	goph.WithKeyFile("/home/user/.ssh/id_rsa", ""),
	goph.WithPort(2222),
)

client1, _ := d.New("root", "host1")
client2, _ := d.New("root", "host2", goph.WithPassword("fallback"))

️  Utils and Helpers

Check if Host is Known
go
found, err := goph.CheckKnownHost("myhost", remoteAddr, publicKey, ""

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Godownloadergogolanggolang-module

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
CategoryAI 编程
PricingOpen source

> Related tools

G
GitHub Copilot
GitHub 官方 AI 编程助手,覆盖补全、Chat 与 Agent 模式。
C
Cursor
AI 原生代码编辑器,对话改代码、多文件 Agent 与规则体系是其核心。
S
skills
Skills for Real Engineers. Straight from my .agents directory.