func (c *Client) Upload(local, remote string) error {
client, err := sftp.NewClient(c.SSHClient)
if err != nil {
return err
}
defer client.Close()
localFile, err := os.Open(local)
if err != nil {
return err
}
defer localFile.Close()
remoteFile, err := client.Create(remote)
if err != nil {
return err
}
_, err = io.Copy(remoteFile, localFile)
return err
}
我调用此函数将文件上传到SFTP,没有任何返回错误。
使用命令行上传如下: Command execution result
我正在操作此功能
var localFilePath = "./1234.zip"
var remoteDir = "upload/uuuuu.zip"
err = client.Upload(localFilePath, remoteDir)
if err != nil {
panic(err)
}
fmt.Println("ok")
执行结果不返回任何错误,仅返回:上传文件已完成
但是登陆SFTP,没有上传文件,请大家指点! 介绍: 此服务仅允许sftp连接 去版本go1.10.2 linux / amd64简化代码,整个过程就像这样
func Consftp(username, host, privKeyPath, local, remote string) error {
privKey, err := ioutil.ReadFile(privKeyPath)
if err != nil {
return err
}
signer, err := ssh.ParsePrivateKey(privKey)
if err != nil {
return err
}
authMethod := ssh.PublicKeys(signer)
config := &ssh.ClientConfig{
User: username,
Auth: []ssh.AuthMethod{authMethod},
HostKeyCallback: HostKeyCallback,
}
conn, err := ssh.Dial("tcp", host, config)
if err != nil {
return err
}
client, err := sftp.NewClient(conn)
if err != nil {
return err
}
defer client.Close()
localFile, err := os.Open(local)
if err != nil {
return err
}
defer localFile.Close()
remoteFile, err := client.Create(remote)
println(err)
if err != nil {
return err
}
_, err = io.Copy(remoteFile, localFile)
return err
}
代码已满
package until
import (
"io"
"io/ioutil"
"os"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
)
func Consftp(username, host, privKeyPath, local, remote string) error {
privKey, err := ioutil.ReadFile(privKeyPath)
if err != nil {
return err
}
signer, err := ssh.ParsePrivateKey(privKey)
if err != nil {
return err
}
authMethod := ssh.PublicKeys(signer)
config := &ssh.ClientConfig{
User: username,
Auth: []ssh.AuthMethod{authMethod},
HostKeyCallback: HostKeyCallback,
}
conn, err := ssh.Dial("tcp", host, config)
if err != nil {
return err
}
defer conn.Close()
client, err := sftp.NewClient(conn)
if err != nil {
return err
}
defer client.Close()
localFile, err := os.Open(local)
if err != nil {
return err
}
defer localFile.Close()
remoteFile, err := client.Create(remote)
println(err)
if err != nil {
return err
}
_, err = io.Copy(remoteFile, localFile)
return err
}