Go通过ssh上传文件或遍历上传文件夹

Go通过ssh上传文件或遍历上传文件夹

学习了Go语言后,打算利用最近比较空一点,写一个前端部署工具,不需要每次都复制粘贴的麻烦,所以我们需要用代码远程上传文件

首先上传文件的方法

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!")
}

遍历上传远程文件夹

我们都知道文件夹上传不能直接上传非空文件夹,所以需要我们手动遍历上传文件,手动创建文件夹

func uploadDirectory(sftpClient *sftp.Client, localPath string, remotePath string) {
	//打开本地文件夹流
	localFiles, err := ioutil.ReadDir(localPath)
	if err != nil {
		log.Fatal("路径错误 ", err)
	}
	//先创建最外层文件夹
	sftpClient.Mkdir(remotePath)
	//遍历文件夹内容
	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!")
}

判断起始路径是文件还是文件夹,确定调用哪个方法

func Upload(sftpClient *sftp.Client, localPath string, remotePath string) {
	//获取路径的属性
	s, err := os.Stat(localPath)
	if err != nil {
		fmt.Println("文件路径不存在")
		return
	}
	//判断是否是文件夹
	if(s.IsDir()) {
		uploadDirectory(sftpClient, localPath, remotePath)
	}else{
		uploadFile(sftpClient, localPath, remotePath)
	}
}

你可能感兴趣的:(go)