Skip to content

shipengqi/gosh

Repository files navigation

gosh

A simple SSH client for Go. Inspired by melbahja/goph. Migrated from golib.

Go Report Card release license

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>

About

A simple SSH client for Go. Inspired by melbahja/goph.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages