Remote file transfer using Go language
- 2020-06-03 06:53:19
- OfStack
preface
The previous article described how to use Go to execute remote commands via the SSH protocol: How to use Go to execute remote commands similarly, Go can be used to transfer files remotely via the SSH protocol.
In addition to the SSH library, you need to transfer files
github.com/pkg/sftp
This library.
implementation
Without further ado, just look at the code. Since it is a remote file transfer based on the SSH protocol, the SSH connection is created first, and then the sftp client for the transfer file is created.
func connect(user, password, host string, port int) (*sftp.Client, error) {
var (
auth []ssh.AuthMethod
addr string
clientConfig *ssh.ClientConfig
sshClient *ssh.Client
sftpClient *sftp.Client
err error
)
// get auth method
auth = make([]ssh.AuthMethod, 0)
auth = append(auth, ssh.Password(password))
clientConfig = &ssh.ClientConfig{
User: user,
Auth: auth,
Timeout: 30 * time.Second,
}
// connet to ssh
addr = fmt.Sprintf("%s:%d", host, port)
if sshClient, err = ssh.Dial("tcp", addr, clientConfig); err != nil {
return nil, err
}
// create sftp client
if sftpClient, err = sftp.NewClient(sshClient); err != nil {
return nil, err
}
return sftpClient, nil
}
Send a file
After creating sftpClient using the connect method above, sending the file is simple.
package main
import (
"fmt"
"log"
"os"
"path"
"time"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
)
func main() {
var (
err error
sftpClient *sftp.Client
)
// Let me put it in real terms SSH Of the connection User name, password, host name or IP . SSH port
sftpClient, err = connect("root", "rootpass", "127.0.0.1", 22)
if err != nil {
log.Fatal(err)
}
defer sftpClient.Close()
// The local file path used to test and Folders on remote machines
var localFilePath = "/path/to/local/file/test.txt"
var remoteDir = "/remote/dir/"
srcFile, err := os.Open(localFilePath)
if err != nil {
log.Fatal(err)
}
defer srcFile.Close()
var remoteFileName = path.Base(localFilePath)
dstFile, err := sftpClient.Create(path.Join(remoteDir, remoteFileName))
if err != nil {
log.Fatal(err)
}
defer dstFile.Close()
buf := make([]byte, 1024)
for {
n, _ := srcFile.Read(buf)
if n == 0 {
break
}
dstFile.Write(buf)
}
fmt.Println("copy file to remote server finished!")
}
Access to the file
Getting files from a remote machine is slightly different, but also simple.
package main
import (
"fmt"
"log"
"os"
"path"
"time"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
)
func main() {
var (
err error
sftpClient *sftp.Client
)
// Let me put it in real terms SSH Of the connection User name, password, host name or IP . SSH port
sftpClient, err = connect("root", "rootpass", "127.0.0.1", 22)
if err != nil {
log.Fatal(err)
}
defer sftpClient.Close()
// The remote file path used to test and Local folder
var remoteFilePath = "/path/to/remote/path/test.txt"
var localDir = "/local/dir"
srcFile, err := sftpClient.Open(remoteFilePath)
if err != nil {
log.Fatal(err)
}
defer srcFile.Close()
var localFileName = path.Base(remoteFilePath)
dstFile, err := os.Create(path.Join(localDir, localFileName))
if err != nil {
log.Fatal(err)
}
defer dstFile.Close()
if _, err = srcFile.WriteTo(dstFile); err != nil {
log.Fatal(err)
}
fmt.Println("copy file from remote server finished!")
}
conclusion
The above example only demonstrates the file transfer, the transfer folder is also very simple, but more steps to traverse the folder and create the folder, the specific function can see doc in the sftp library. That's all for remote file transfer in Go language. I hope this article is helpful for you to learn Go language.