Implementing remote transfer files using the Go language _golang

Source: Internet
Author: User
Tags auth ssh port

Objective

A previous article describes how to use the Go language to execute remote commands through the SSH protocol: How to implement remote command using the Go language also, you can use the go language to remotely transfer files through the SSH protocol.

In addition to the SSH library, in order to transfer files, you need to use github.com/pkg/sftp this library.

Implementation mode

Do not say much nonsense, directly look at the code. Because it is a remote file transfer based on the SSH protocol, you create the SSH connection first and then create the SFTP client that transmits the file.

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

When you create a sftpclient using the Connect method above, sending the file is simple.

 package main import ("FMT" "Log" "OS" "Path" "Time" "Github.com/pkg/sftp" "Gol Ang.org/x/crypto/ssh ") Func main () {var (err error sftpclient *sftp).  Client)//here Replace the actual SSH connection username, password, host name or IP,SSH port sftpclient, err = connect ("root", "Rootpass", "127.0.0.1",) If Err != Nil {log.
 Fatal (ERR)} defer sftpclient.close ()//To test the local file path and the folder on the remote machine 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!")} 

Get files

The way to get files from a remote machine is slightly different, but it's 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
 )

 //Here Replace the actual SSH connection username, password, host name or IP,SSH port
 sftpclient, err = connect ("root", "Rootpass", "127.0.0.1 ","
 if err!= nil {
 log. Fatal (Err)
 }
 defer sftpclient.close ()

 //Remote file path 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!")
}

Summarize

The above example only demonstrates file transfer, the transfer folder is also very simple, just a few steps to traverse the folder and create a folder, the specific function can view the SFTP library doc. The above is the go language to implement the entire content of remote transmission files, I hope this article will help you learn the go language.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.