最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

go語言實現(xiàn)sftp包上傳文件和文件夾到遠程服務器操作

 更新時間:2020年12月18日 09:20:41   作者:奔流入海  
這篇文章主要介紹了go語言實現(xiàn)sftp包上傳文件和文件夾到遠程服務器操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

使用go語言的第三方包:github.com/pkg/sftp和golang.org/x/crypto/ssh實現(xiàn)文件和文件夾傳輸。

1、創(chuàng)建connect方法:

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,
  HostKeyCallback: ssh.InsecureIgnoreHostKey(), //ssh.FixedHostKey(hostKey),
 }
 // 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
}

2、上傳文件

func uploadFile(sftpClient *sftp.Client, localFilePath string, remotePath string) {
 srcFile, err := os.Open(localFilePath)
 if err != nil {
  fmt.Println("os.Open error : ", localFilePath)
  log.Fatal(err)
 }
 defer srcFile.Close()
 var remoteFileName = path.Base(localFilePath)
 dstFile, err := sftpClient.Create(path.Join(remotePath, remoteFileName))
 if err != nil {
  fmt.Println("sftpClient.Create error : ", path.Join(remotePath, remoteFileName))
  log.Fatal(err)
 }
 defer dstFile.Close()
 ff, err := ioutil.ReadAll(srcFile)
 if err != nil {
  fmt.Println("ReadAll error : ", localFilePath)
  log.Fatal(err)
 }
 dstFile.Write(ff)
 fmt.Println(localFilePath + " copy file to remote server finished!")
}

3、上傳文件夾

func uploadDirectory(sftpClient *sftp.Client, localPath string, remotePath string) {
 localFiles, err := ioutil.ReadDir(localPath)
 if err != nil {
  log.Fatal("read dir list fail ", err)
 }
 for _, backupDir := range localFiles {
  localFilePath := path.Join(localPath, backupDir.Name())
  remoteFilePath := path.Join(remotePath, backupDir.Name())
  if backupDir.IsDir() {
   sftpClient.Mkdir(remoteFilePath)
   uploadDirectory(sftpClient, localFilePath, remoteFilePath)
  } else {
   uploadFile(sftpClient, path.Join(localPath, backupDir.Name()), remotePath)
  }
 }
 fmt.Println(localPath + " copy directory to remote server finished!")
}

4、上傳測試

func DoBackup(host string, port int, userName string, password string, localPath string, remotePath string) {
 var (
  err  error
  sftpClient *sftp.Client
 )
 start := time.Now()
 sftpClient, err = connect(userName, password, host, port)
 if err != nil {
  log.Fatal(err)
 }
 defer sftpClient.Close()
 _, errStat := sftpClient.Stat(remotePath)
 if errStat != nil {
  log.Fatal(remotePath + " remote path not exists!")
 }
 backupDirs, err := ioutil.ReadDir(localPath)
 if err != nil {
  log.Fatal(localPath + " local path not exists!")
 }
 uploadDirectory(sftpClient, localPath, remotePath)
 elapsed := time.Since(start)
 fmt.Println("elapsed time : ", elapsed)
}

補充:go實現(xiàn)ssh遠程機器并傳輸文件

核心依賴包:

golang.org/x/crypto/ssh

github.com/pkg/sftp

其中g(shù)olang.org/x/crypto/ssh 可從github上下載,

下載地址:https://github.com/golang/crypto

ssh連接源碼(這里是根據(jù)秘鑰連接):

var keypath = "key/id_rsa"
//獲取秘鑰
func publicKey(path string) ssh.AuthMethod {
 keypath, err := homedir.Expand(path)
 if err != nil {
 fmt.Println("獲取秘鑰路徑失敗", err)
 }
 key, err1 := ioutil.ReadFile(keypath)
 if err1 != nil {
 fmt.Println("讀取秘鑰失敗", err1)
 }
 signer, err2 := ssh.ParsePrivateKey(key)
 if err2 != nil {
 fmt.Println("ssh 秘鑰簽名失敗", err2)
 }
 return ssh.PublicKeys(signer)
}
//獲取ssh連接
func GetSSHConect(ip, user string, port int) (*ssh.Client) {
 con := &ssh.ClientConfig{
 User: user,
 Auth: []ssh.AuthMethod{publicKey(keypath)},
 HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
 return nil
 },
 }
 addr := fmt.Sprintf("%s:%d", ip, port)
 client, err := ssh.Dial("tcp", addr, con)
 if err != nil {
 fmt.Println("Dail failed: ", err)
 panic(err)
 }
 return client
}
// 遠程執(zhí)行腳本
func Exec_Task(ip, user, localpath, remotepath string) int {
 port := 22
 client := GetSSHConect(ip, user, port)
 UploadFile(ip, user, localpath, remotepath, port)
 session, err := client.NewSession()
 if err != nil {
 fmt.Println("創(chuàng)建會話失敗", err)
 panic(err)
 }
 defer session.Close()
 remoteFileName := path.Base(localpath)
 dstFile := path.Join(remotepath, remoteFileName)
 err1 := session.Run(fmt.Sprintf("/usr/bin/sh %s", dstFile))
 if err1 != nil {
 fmt.Println("遠程執(zhí)行腳本失敗", err1)
 return 2
 } else {
 fmt.Println("遠程執(zhí)行腳本成功")
 return 1
 }
}

文件傳輸功能:

//獲取ftp連接
func getftpclient(client *ssh.Client) (*sftp.Client) {
 ftpclient, err := sftp.NewClient(client)
 if err != nil {
 fmt.Println("創(chuàng)建ftp客戶端失敗", err)
 panic(err)
 }
 return ftpclient
}
//上傳文件
func UploadFile(ip, user, localpath, remotepath string, port int) {
 client := GetSSHConect(ip, user, port)
 ftpclient := getftpclient(client)
 defer ftpclient.Close()
 remoteFileName := path.Base(localpath)
 fmt.Println(localpath, remoteFileName)
 srcFile, err := os.Open(localpath)
 if err != nil {
 fmt.Println("打開文件失敗", err)
 panic(err)
 }
 defer srcFile.Close()
 dstFile, e := ftpclient.Create(path.Join(remotepath, remoteFileName))
 if e != nil {
 fmt.Println("創(chuàng)建文件失敗", e)
 panic(e)
 }
 defer dstFile.Close()
 buffer := make([]byte, 1024)
 for {
 n, err := srcFile.Read(buffer)
 if err != nil {
 if err == io.EOF {
 fmt.Println("已讀取到文件末尾")
 break
 } else {
 fmt.Println("讀取文件出錯", err)
 panic(err)
 }
 }
 dstFile.Write(buffer[:n]) 
 //注意,由于文件大小不定,不可直接使用buffer,否則會在文件末尾重復寫入,以填充1024的整數(shù)倍
 }
 fmt.Println("文件上傳成功")
}
//文件下載
func DownLoad(ip, user, localpath, remotepath string, port int) {
 client := GetSSHConect(ip, user, port)
 ftpClient := getftpclient(client)
 defer ftpClient.Close()
 srcFile, err := ftpClient.Open(remotepath)
 if err != nil {
 fmt.Println("文件讀取失敗", err)
 panic(err)
 }
 defer srcFile.Close()
 localFilename := path.Base(remotepath)
 dstFile, e := os.Create(path.Join(localpath, localFilename))
 if e != nil {
 fmt.Println("文件創(chuàng)建失敗", e)
 panic(e)
 }
 defer dstFile.Close()
 if _, err1 := srcFile.WriteTo(dstFile); err1 != nil {
 fmt.Println("文件寫入失敗", err1)
 panic(err1)
 }
 fmt.Println("文件下載成功")
}

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。

相關(guān)文章

  • Go語言JSON解析器gjson使用方法詳解

    Go語言JSON解析器gjson使用方法詳解

    這篇文章主要介紹了Go語言json解析框架與gjson,JSON?解析是我們不可避免的常見問題,在Go語言中,我們可以借助gjson庫來方便的進行json屬性的提取與解析,需要的朋友可以參考一下
    2022-12-12
  • Golang中優(yōu)秀的消息隊列NSQ基礎(chǔ)安裝及使用詳解

    Golang中優(yōu)秀的消息隊列NSQ基礎(chǔ)安裝及使用詳解

    這篇文章主要介紹了Golang中優(yōu)秀的消息隊列NSQ基礎(chǔ)安裝及使用詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-12-12
  • 解決golang http.FileServer 遇到的坑

    解決golang http.FileServer 遇到的坑

    這篇文章主要介紹了解決golang http.FileServer 遇到的坑,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-12-12
  • 詳解Golang如何優(yōu)雅判斷interface是否為nil

    詳解Golang如何優(yōu)雅判斷interface是否為nil

    這篇文章主要為大家詳細介紹了Golang如何優(yōu)雅判斷interface是否為nil的相關(guān)知識,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起了解下
    2024-01-01
  • golang?對象深拷貝的常見方式及性能

    golang?對象深拷貝的常見方式及性能

    這篇文章主要介紹了golang?對象深拷貝的常見方式及性能,Go語言中所有賦值操作都是值傳遞,如果結(jié)構(gòu)中不含指針,則直接賦值就是深度拷貝,文章圍繞主題展開更多相關(guān)資料,需要的小伙伴可以參考一下
    2022-06-06
  • Golang開發(fā)中常用的代碼片段匯總

    Golang開發(fā)中常用的代碼片段匯總

    這篇文章主要給大家匯總了在Golang開發(fā)中常用的代碼片段,這些代碼片段都是在日常工作中編寫golang應用時使用到,需要的朋友可以參考借鑒,下面跟著小編一起來學習學習吧。
    2017-07-07
  • Golang使用Gin框架實現(xiàn)路由分類處理請求流程詳解

    Golang使用Gin框架實現(xiàn)路由分類處理請求流程詳解

    Gin是一個golang的微框架,封裝比較優(yōu)雅,具有快速靈活,容錯方便等特點,這篇文章主要介紹了Golang使用Gin框架實現(xiàn)路由分類處理請求,感興趣的同學可以參考下文
    2023-05-05
  • go使用makefile腳本編譯應用的方法小結(jié)

    go使用makefile腳本編譯應用的方法小結(jié)

    makefile可以看作是make工具的腳本文件, 而make主要用來處理一系列命令。常用的比如用來編譯和打包文件, 在C/C++的編譯打包中應用最廣泛了,這篇文章主要介紹了go使用makefile腳本編譯應用,需要的朋友可以參考下
    2022-08-08
  • 使用docker構(gòu)建golang線上部署環(huán)境的步驟詳解

    使用docker構(gòu)建golang線上部署環(huán)境的步驟詳解

    這篇文章主要介紹了使用docker構(gòu)建golang線上部署環(huán)境的步驟,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧。
    2017-11-11
  • Go語言底層原理互斥鎖的實現(xiàn)原理

    Go語言底層原理互斥鎖的實現(xiàn)原理

    這篇文章主要介紹了Go語言底層原理互斥鎖的實現(xiàn)原理,Go?sync包提供了兩種鎖類型,分別是互斥鎖sync.Mutex和讀寫互斥鎖sync.RWMutex,都屬于悲觀鎖,更多相關(guān)內(nèi)容需要的朋友可以查看下面文章內(nèi)容
    2022-08-08

最新評論

平遥县| 买车| 加查县| 弋阳县| 马公市| 青川县| 广西| 绍兴县| 赫章县| 永年县| 新平| 铅山县| 呼玛县| 诸暨市| 全南县| 陈巴尔虎旗| 新昌县| 阿拉尔市| 舒兰市| 彰化县| 黔东| 陇西县| 深圳市| 金湖县| 喜德县| 缙云县| 丹凤县| 中西区| 陆河县| 汉中市| 韶关市| 泽普县| 克什克腾旗| 锦州市| 綦江县| 临泉县| 自贡市| 亚东县| 华池县| 东台市| 泌阳县|