golang 使用githubcompkgsftp 包 通过ftp 下载文件
首先,需要安装 github.com/pkg/sftp 包。可以通过以下命令进行安装:
go get github.com/pkg/sftp
然后,可以使用以下代码实现通过 FTP 下载文件:
package main
import (
"fmt"
"io"
"os"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
)
func main() {
// 连接到 FTP 服务器
config := &ssh.ClientConfig{
User: "username",
Auth: []ssh.AuthMethod{
ssh.Password("password"),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
conn, err := ssh.Dial("tcp", "ftp.example.com:22", config)
if err != nil {
panic(err)
}
defer conn.Close()
// 创建 SFTP 客户端
client, err := sftp.NewClient(conn)
if err != nil {
panic(err)
}
defer client.Close()
// 打开远程文件
remoteFile, err := client.Open("/path/to/remote/file")
if err != nil {
panic(err)
}
defer remoteFile.Close()
// 创建本地文件
localFile, err := os.Create("/path/to/local/file")
if err != nil {
panic(err)
}
defer localFile.Close()
// 下载远程文件到本地
_, err = io.Copy(localFile, remoteFile)
if err != nil {
panic(err)
}
fmt.Println("File downloaded successfully!")
}
需要替换 username、password、ftp.example.com、/path/to/remote/file、/path/to/local/file 等参数为实际值
原文地址: https://www.cveoy.top/t/topic/g1ME 著作权归作者所有。请勿转载和采集!