scp

package module
v1.1.4 Latest Latest
Warning

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

Go to latest
Published: Apr 8, 2021 License: MIT Imports: 11 Imported by: 1

README

go-scp Build Status Go Report Card PkgGoDev MIT licensed

A scp client library written in Go. The remote server must have the scp command.

Example

Please refer to the example at godoc.

License

MIT

Documentation

Overview

Package scp provides functions to copy a single file or to copy files and directories under a directory recursively between the localhost and a remote server.

Example
generateTestSshdKey := func() ([]byte, error) {
	key, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return nil, err
	}
	pemdata := pem.EncodeToMemory(
		&pem.Block{
			Type:  "RSA PRIVATE KEY",
			Bytes: x509.MarshalPKCS1PrivateKey(key),
		},
	)
	return pemdata, nil
}

newTestSshdServer := func() (*sshd.Server, net.Listener, error) {
	config := &ssh.ServerConfig{
		PasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
			if c.User() == testSshdUser && string(pass) == testSshdPassword {
				return nil, nil
			}
			return nil, fmt.Errorf("password rejected for %q", c.User())
		},
	}
	testSshdKey, err := generateTestSshdKey()
	if err != nil {
		return nil, nil, err
	}
	private, err := ssh.ParsePrivateKey(testSshdKey)
	if err != nil {
		return nil, nil, err
	}

	config.AddHostKey(private)

	server := sshd.NewServer(testSshdShell, config, nil)
	l, err := net.Listen("tcp", ":0")
	if err != nil {
		return nil, nil, err
	}
	return server, l, err
}

s, l, err := newTestSshdServer()
if err != nil {
	log.Fatalf("fail to create test sshd server; %s", err)
}
defer s.Close()
go s.Serve(l)

config := &ssh.ClientConfig{
	User:            testSshdUser,
	Auth:            []ssh.AuthMethod{ssh.Password(testSshdPassword)},
	HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
client, err := ssh.Dial("tcp", l.Addr().String(), config)
if err != nil {
	log.Fatalf("failed to dial to ssh server: %s", err)
}
defer client.Close()

localDir, err := ioutil.TempDir("", "go-scp-ExampleSendFile-local")
if err != nil {
	log.Fatalf("fail to get tempdir; %s", err)
}
defer os.RemoveAll(localDir)

remoteDir, err := ioutil.TempDir("", "go-scp-ExampleSendFile-remote")
if err != nil {
	log.Fatalf("fail to get tempdir; %s", err)
}
defer os.RemoveAll(remoteDir)

localName := "test1.dat"
remoteName := "dest.dat"
localPath := filepath.Join(localDir, localName)
remotePath := filepath.Join(remoteDir, remoteName)
content := []byte("Hello, SCP\n")
err = ioutil.WriteFile(localPath, content, 0644)
if err != nil {
	log.Fatalf("fail to write file; %s", err)
}

err = scp.NewSCP(client).SendFile(localPath, remotePath)
if err != nil {
	log.Fatalf("fail to send file; %s", err)
}

data, err := ioutil.ReadFile(remotePath)
if err != nil {
	log.Fatalf("fail to read file; %s", err)
}

fmt.Printf("%s", data)
Output:

Hello, SCP

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AcceptFunc

type AcceptFunc func(parentDir string, info os.FileInfo) (bool, error)

AcceptFunc is the type of the function called for each file or directory to determine whether is should be copied or not. In SendDir, parentDir will be a directory under srcDir. In ReceiveDir, parentDir will be a directory under destDir.

type FileInfo

type FileInfo struct {
	// contains filtered or unexported fields
}

FileInfo represents a file or a directory information.

func NewFileInfo

func NewFileInfo(name string, size int64, mode os.FileMode, modTime, accessTime time.Time) *FileInfo

NewFileInfo creates a file information. The filepath.Base(name) is used as the name and the mode is masked with (os.ModePerm | os.ModeDir).

func (*FileInfo) AccessTime

func (i *FileInfo) AccessTime() time.Time

AccessTime returns access time.

func (*FileInfo) IsDir

func (i *FileInfo) IsDir() bool

IsDir is abbreviation for Mode().IsDir().

func (*FileInfo) ModTime

func (i *FileInfo) ModTime() time.Time

ModTime returns modification time.

func (*FileInfo) Mode

func (i *FileInfo) Mode() os.FileMode

Mode returns file mode bits.

func (*FileInfo) Name

func (i *FileInfo) Name() string

Name returns base name of the file.

func (*FileInfo) Size

func (i *FileInfo) Size() int64

Size length in bytes for regular files; system-dependent for others.

func (*FileInfo) Sys

func (i *FileInfo) Sys() interface{}

Sys returns underlying data source (can return nil).

type SCP

type SCP struct {

	// Alternate scp command. If not set, scp is used. This can be used
	// to call scp via sudo by setting it to "sudo scp"
	SCPCommand string
	// The console prints download or upload progress
	ShowSchedule bool
	// contains filtered or unexported fields
}

SCP is the type for the SCP client.

func NewSCP

func NewSCP(client *ssh.Client) *SCP

NewSCP creates the SCP client. It is caller's responsibility to call Dial for ssh.Client before calling NewSCP and call Close for ssh.Client after using SCP.

func (*SCP) Receive

func (s *SCP) Receive(srcFile string, dest io.Writer) (*FileInfo, error)

Receive copies a single remote file to the specified writer and returns the file information. The actual type of the file information is scp.FileInfo, and you can get the access time with fileInfo.(*scp.FileInfo).AccessTime().

func (*SCP) ReceiveDir

func (s *SCP) ReceiveDir(srcDir, destDir string, acceptFn AcceptFunc) error

ReceiveDir copies files and directories under a remote srcDir to to the destDir on the local machine. You can filter the files and directories to be copied with acceptFn. If acceptFn is nil, all files and directories will be copied. The time and permission will be set to the same value of the source file or directory.

func (*SCP) ReceiveFile

func (s *SCP) ReceiveFile(srcFile, destFile string) error

ReceiveFile copies a single remote file to the local machine with the specified name. The time and permission will be set to the same value of the source file.

func (*SCP) Send

func (s *SCP) Send(info *FileInfo, r io.ReadCloser, destFile string) error

Send reads a single local file content from the r, and copies it to the remote file with the name destFile. The time and permission will be set with the value of info. The r will be closed after copying. If you don't want for r to be closed, you can pass the result of ioutil.NopCloser(r).

func (*SCP) SendDir

func (s *SCP) SendDir(srcDir, destDir string, acceptFn AcceptFunc) error

SendDir copies files and directories under the local srcDir to to the remote destDir. You can filter the files and directories to be copied with acceptFn. However this filtering is done at the receiver side, so all file bodies are transferred over the network even if some files are filtered out. If you need more efficiency, it is better to use another method like the tar command. If acceptFn is nil, all files and directories will be copied. The time and permission will be set to the same value of the source file or directory.

func (*SCP) SendFile

func (s *SCP) SendFile(srcFile, destFile string) error

SendFile copies a single local file to the remote server. The time and permission will be set with the value of the source file.

Jump to

Keyboard shortcuts

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