1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
sftp.go 1.36 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2022-10-24 11:57 . rpc ,close connect,git
package ssh
import (
"errors"
"fmt"
"github.com/pkg/sftp"
"io"
"os"
"time"
)
type Sftp struct {
session *Session
}
func NewSftp(session *Session) *Sftp {
return &Sftp{session: session}
}
func (sf *Sftp) Exec(id int, localFilePath string, remoteFilePath string) *Result {
result := &Result{
Id: id,
Host: sf.session.Host,
LocalPath: localFilePath,
RemotePath: remoteFilePath,
}
start := time.Now()
result.StartTime = start
if err := sf.session.Connect(); err != nil {
result.Error = err
return result
}
var fileSize int64
if s, err := os.Stat(localFilePath); err != nil {
result.Error = err
return result
} else {
fileSize = s.Size()
}
srcFile, err := os.Open(localFilePath)
if err != nil {
result.Error = err
return result
}
defer srcFile.Close()
sftpClient, err := sftp.NewClient(sf.session.Client)
if err != nil {
result.Error = err
return result
}
defer sftpClient.Close()
dstFile, err := sftpClient.Create(remoteFilePath)
if err != nil {
result.Error = err
return result
}
defer dstFile.Close()
n, err := io.Copy(dstFile, io.LimitReader(srcFile, fileSize))
if err != nil {
result.Error = err
return result
}
if n != fileSize {
result.Error = errors.New(fmt.Sprintf("copy: expected %v bytes, got %d", fileSize, n))
return result
}
end := time.Now()
result.EndTime = end
return result
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.8.83

搜索帮助