首页 > 其他分享 >go sftp上传文件

go sftp上传文件

时间:2022-10-06 16:23:12浏览次数:43  
标签:return err nil fmt sftp ssh go 上传

go sftp上传文件

步骤

使用"golang.org/x/crypto/ssh"连接到Linux环境

使用"github.com/pkg/sftp"创建sftp客户端

然后传输文件

package main

import (
   "fmt"
   "github.com/pkg/sftp"
   "golang.org/x/crypto/ssh"
   "io/ioutil"
   "net"
   "os"
   "path"
   "path/filepath"
   "time"
)

func hostKeyCallback(hostname string, remote net.Addr, key ssh.PublicKey) error {
   return nil

}

//获取一个STFP客户端连接
func connect(user, password, host string, port int) (*sftp.Client, error) {

   auth := []ssh.AuthMethod{ssh.Password(password)}

   config := &ssh.ClientConfig{
      User:            user,
      Auth:            auth,
      Timeout:         30 * time.Second,
      HostKeyCallback: hostKeyCallback,
   }

   // connect to ssh
   addr := fmt.Sprintf("%s:%d", host, port)
   client, err := ssh.Dial("tcp", addr, config)
   if err != nil {
      return nil, err
   }

   // create sftp client
   sftpClient, err := sftp.NewClient(client)
   if err != nil {
      return nil, err
   }
   fmt.Printf("连接%s@%s:%d成功!\n", user, host, port)
   return sftpClient, nil
}

//上传文件
func uploadFile(sftpClient *sftp.Client, localFilename string, remotePath string) (int, error) {

   file, err := os.Open(localFilename)
   if err != nil {
      return 0, err

   }
   defer func(srcFile *os.File) {
      err := srcFile.Close()
      if err != nil {
      }
   }(file)

   var remoteFileName = path.Join(remotePath, filepath.Base(localFilename))
   err = sftpClient.MkdirAll(remotePath)
   if err != nil {
      return 0, err
   }

   dstFile, err := sftpClient.Create(remoteFileName)
   if err != nil {
      return 0, err

   }
   defer func(dstFile *sftp.File) {
      err := dstFile.Close()
      if err != nil {

      }
   }(dstFile)

   ff, err := ioutil.ReadAll(file)
   if err != nil {
      return 0, err
   }
   n, err := dstFile.Write(ff)
   if err != nil {
      return n, err
   }
   fmt.Printf("上传文件成功, 保存到:%s\n", remoteFileName)
   return n, nil
}
func main() {
   user := "root"
   password := "******"
   host := "192.168.93.129"
   port := 22
   filename := "a.txt"
   remoteFilePath := "/home/tmp"

   client, err := connect(user, password, host, port)
   if err != nil {
      fmt.Println(fmt.Sprintf("连接%s:%d失败, err:%s", host, port, err))
      return
   }
   _, err = uploadFile(client, filename, remoteFilePath)
   if err != nil {
      fmt.Printf("上传失败, local file:%s, remote path:%s err:%s\n", filename, remoteFilePath, err)
      return
   }

}

参考https://blog.csdn.net/fu_qin/article/details/78741854

标签:return,err,nil,fmt,sftp,ssh,go,上传
From: https://www.cnblogs.com/rainbow-tan/p/16757834.html

相关文章