ssh

package module
v0.0.0-...-5aaea59 Latest Latest
Warning

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

Go to latest
Published: Mar 12, 2019 License: Apache-2.0 Imports: 23 Imported by: 0

README

项目简介

本项目是基于golang标准库 ssh 和 sftp 开发

本项目是对标准库进行一个简单的高层封装,使得可以在在 Windows Linux Mac 上非常容易的执行 ssh 命令, 以及文件,文件夹的上传,下载等操作.

  1. 当src 为目录时 文件上传下载模仿rsync: 只和源有关.
    // rsync -av src/ dst ./src/* --> /root/dst/*
    // rsync -av src/ dst/ ./src/* --> /root/dst/*
    // rsync -av src dst ./src/* --> /root/dst/src/*
    // rsync -av src dst/ ./src/* --> /root/dst/src/*
  2. 当src 为文件时 当dst为目录,以"/"结尾,则自动拼接上文件名 当dst为文件,不以“/”结尾时,则重命名文件

Install

go get github.com/pytool/ssh

Example

在远程执行ssh命令

提供3个方法: Run() Exec() Output()

  1. Run() : 程序执行后,不再受执行者控制. 适用于启动服务端进程.
  2. Exec() : 在控制台同步实时输出程序的执行结果.
  3. Output() : 会等待程序执行完成后,输出执行结果,在需要对执行的结果进行操作时使用.
package main
import (
	"fmt"
	"github.com/pytool/ssh"
)
func main() {

	c, err := ssh.NewClient("localhost", "22", "root", "ubuntu")
	if err != nil {
		panic(err)
	}
	defer c.Close()

	output, err := c.Output("uptime")
	if err != nil {
		panic(err)
	}

	fmt.Printf("Uptime: %s\n", output)
}

文件下载

package main

import (
	"github.com/pytool/ssh"
)

func main() {

	client, err := ssh.NewClient( "localhost", "22", "root", "ubuntu")
	if err != nil {
		panic(err)
	}
	defer client.Close()
	var remotedir = "/root/test/"
	// download dir
	var local = "/home/ubuntu/go/src/github.com/pytool/ssh/test/download/"
	client.Download(remotedir, local)

	// upload file
	var remotefile = "/root/test/file"

	client.Download(remotefile, local)
}

文件上传

package main

import (
	"github.com/pytool/ssh"
)

func main() {

	client, err := ssh.NewClient( "localhost", "22", "root", "ubuntu")
	if err != nil {
		panic(err)
	}
	defer client.Close()
	var remotedir = "/root/test/"
	// upload dir
	var local = "/home/ubuntu/go/src/github.com/pytool/ssh/test/upload/"
	client.Upload(local, remotedir)

	// upload file
	local = "/home/ubuntu/go/src/github.com/pytool/ssh/test/upload/file"
	client.Upload(local, remotedir)
}

Documentation

Index

Constants

View Source
const DefaultTimeout = 30 * time.Second

Variables

View Source
var Default = DefaultConfig
View Source
var DefaultConfig = &Config{
	Host: "localhost",
	Port: 22,
	User: "root",
}

Functions

func AuthWithAgent

func AuthWithAgent() (ssh.AuthMethod, error)

AuthWithAgent use already authed user

func AuthWithKeyboardPassword

func AuthWithKeyboardPassword(password string) (ssh.AuthMethod, error)

AuthWithKeyboardPassword Generate a password-auth'd ssh ClientConfig

func AuthWithPassword

func AuthWithPassword(password string) (ssh.AuthMethod, error)

AuthWithPassword Generate a password-auth'd ssh ClientConfig

func AuthWithPrivateKey

func AuthWithPrivateKey(keyfile string, passphrase string) (ssh.AuthMethod, error)

AuthWithPrivateKey 自动监测是否带有密码

func AuthWithPrivateKeyString

func AuthWithPrivateKeyString(key string, password string) (ssh.AuthMethod, error)

AuthWithPrivateKeyString 直接通过字符串

func AuthWithPrivateKeyTerminal

func AuthWithPrivateKeyTerminal(keyfile string) (ssh.AuthMethod, error)

AuthWithPrivateKeyTerminal 通过终端读取带密码的 PublicKey

func AuthWithPrivateKeys

func AuthWithPrivateKeys(keyFiles []string, passphrase string) (ssh.AuthMethod, error)

AuthWithPrivateKeys 设置多个 ~/.ssh/id_rsa ,如果加密用passphrase尝试

func FileExist

func FileExist(file string) bool

func HasAgent

func HasAgent() bool

HasAgent reports whether the SSH agent is available

func KeyFile

func KeyFile() string

func Md5File

func Md5File(filename string) (string, error)

Md5File 计算md5

func MkdirAll

func MkdirAll(path string) error

Types

type Client

type Client struct {
	*Config
	SSHClient  *ssh.Client
	SSHSession *ssh.Session
	SFTPClient *sftp.Client
}

func Connect

func Connect(cnf *Config) (client *Client, err error)

func New

func New(cnf *Config) (client *Client, err error)

New 创建SSH client

func NewClient

func NewClient(host, port, user, password string) (client *Client, err error)

NewClient 根据配置

func NewDSN

func NewDSN() (client *Client)

func NewWithAgent

func NewWithAgent(Host, Port, User string) (client *Client, err error)

func NewWithPrivateKey

func NewWithPrivateKey(Host, Port, User, Passphrase string) (client *Client, err error)

func (*Client) Close

func (c *Client) Close()

Close the underlying SSH connection

func (*Client) Download

func (c *Client) Download(remote string, local string) (err error)

Download 下载sftp远程文件 remote 到本地 local like rsync

func (*Client) Exec

func (c *Client) Exec(cmd string) error

Exec Execute cmd on the remote host and bind stderr and stdout

func (*Client) Exec1

func (c *Client) Exec1(cmd string) error

Exec Execute cmd on the remote host and bind stderr and stdout

func (*Client) ExecSu

func (c *Client) ExecSu(cmd, passwd string) ([]byte, error)

ExecSu Execute cmd via sudo. Do not include the sudo command in the cmd string. For example: Client.ExecSudo("uptime", "password"). If you are using passwordless sudo you can use the regular Exec() function.

func (*Client) FileExist

func (c *Client) FileExist(filepath string) (bool, error)

FileExist 文件是否存在

func (*Client) IsDir

func (c *Client) IsDir(path string) bool

IsDir 检查远程是否是个目录

func (*Client) IsExist

func (c *Client) IsExist(path string) bool

IsExist 检查远程是文件是否存在

func (*Client) IsFile

func (c *Client) IsFile(path string) bool

IsFile 检查远程是否是个文件

func (*Client) IsNotExist

func (c *Client) IsNotExist(path string) bool

IsNotExist 检查远程是文件是否不存在

func (*Client) Md5File

func (c *Client) Md5File(path string) string

Md5File 检查远程是文件是否存在

func (*Client) Mkdir

func (c *Client) Mkdir(path string, fi os.FileInfo) error

func (*Client) MkdirAll

func (c *Client) MkdirAll(dirpath string) error

MkdirAll 创建目录,递归

func (*Client) Output

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

Output Execute cmd on the remote host and return stderr and stdout

func (*Client) ReadAll

func (c *Client) ReadAll(filepath string) ([]byte, error)

ReadAll Read a remote file and return the contents.

func (*Client) Remove

func (c *Client) Remove(path string) error

Remove a file from the remote server

func (*Client) RemoveAll

func (c *Client) RemoveAll(remoteDir string) error

RemoveAll 递归删除目录,文件

func (*Client) RemoveDir

func (c *Client) RemoveDir(remoteDir string) error

func (*Client) RemoveDirectory

func (c *Client) RemoveDirectory(path string) error

RemoveDirectory Remove a directory from the remote server

func (*Client) RemoveFile

func (c *Client) RemoveFile(remoteFile string) error

func (*Client) Run

func (c *Client) Run(cmd string)

Run Execute cmd on the remote host for daemon service

func (*Client) RunScript

func (c *Client) RunScript(scriptPath string) ([]byte, error)

RunScript Executes a shell script file on the remote machine. It is copied in the tmp folder and ran in a single session. chmod +x is applied before running. Returns an SshResponse and an error if any has occured

func (*Client) Size

func (c *Client) Size(path string) int64

Size 获取文件大小

func (*Client) Upload

func (c *Client) Upload(local string, remote string) (err error)

Upload 上传本地文件 local 到sftp远程目录 remote like rsync rsync -av src/ dst ./src/* --> /root/dst/* rsync -av src/ dst/ ./src/* --> /root/dst/* rsync -av src dst ./src/* --> /root/dst/src/* rsync -av src dst/ ./src/* --> /root/dst/src/*

func (*Client) UploadDir

func (c *Client) UploadDir(localDir string, remoteDir string) (err error)

UploadDir files without checking diff status

func (*Client) UploadFile

func (c *Client) UploadFile(localFile, remote string) error

UploadFile 上传本地文件 localFile 到sftp远程目录 remote

type Config

type Config struct {
	User       string
	Host       string
	Port       int
	Password   string
	KeyFiles   []string
	Passphrase string

	StickySession bool
	// DisableAgentForwarding, if true, will not forward the SSH agent.
	DisableAgentForwarding bool

	// HandshakeTimeout limits the amount of time we'll wait to handshake before
	// saying the connection failed.
	HandshakeTimeout time.Duration

	// KeepAliveInterval sets how often we send a channel request to the
	// server. A value < 0 disables.
	KeepAliveInterval time.Duration

	// Timeout is how long to wait for a read or write to succeed.
	Timeout time.Duration
}

func WithHost

func WithHost(host string) *Config

func WithKey

func WithKey(keyfile, passphrase string) *Config

func WithPassword

func WithPassword(password string) *Config

func WithUser

func WithUser(user string) *Config

func (*Config) Connect

func (cnf *Config) Connect() (client *Client, err error)

func (*Config) SetKeys

func (c *Config) SetKeys(keyfiles []string) *Config

func (*Config) WithHost

func (c *Config) WithHost(host string) *Config

func (*Config) WithKey

func (c *Config) WithKey(keyfile, passphrase string) *Config

func (*Config) WithPassword

func (c *Config) WithPassword(password string) *Config

func (*Config) WithUser

func (c *Config) WithUser(user string) *Config

Directories

Path Synopsis
example

Jump to

Keyboard shortcuts

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