golang ssh连接到linux获取指定目录文件并复制到本地
要在Golang中通过SSH连接到Linux服务器,获取指定目录的文件并复制到本地,你可以使用github.com/pkg/sftp包。以下是一个简单的示例代码:
package main
import (
"fmt"
"io"
"log"
"os"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
)
func main() {
// SSH连接配置
config := &ssh.ClientConfig{
User: "username",
Auth: []ssh.AuthMethod{
ssh.Password("password"),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
// SSH连接
client, err := ssh.Dial("tcp", "hostname:port", config)
if err != nil {
log.Fatalf("Failed to dial: %s", err)
}
defer client.Close()
// 创建SFTP会话
sftpClient, err := sftp.NewClient(client)
if err != nil {
log.Fatalf("Failed to create SFTP client: %s", err)
}
defer sftpClient.Close()
// 远程文件路径
remotePath := "/path/to/remote/directory"
// 本地文件路径
localPath := "/path/to/local/directory"
// 获取远程目录下的所有文件
files, err := sftpClient.ReadDir(remotePath)
if err != nil {
log.Fatalf("Failed to read remote directory: %s", err)
}
// 遍历文件列表
for _, file := range files {
// 拼接远程文件路径
remoteFilePath := remotePath + "/" + file.Name()
// 拼接本地文件路径
localFilePath := localPath + "/" + file.Name()
// 打开远程文件
remoteFile, err := sftpClient.Open(remoteFilePath)
if err != nil {
log.Fatalf("Failed to open remote file: %s", err)
}
defer remoteFile.Close()
// 创建本地文件
localFile, err := os.Create(localFilePath)
if err != nil {
log.Fatalf("Failed to create local file: %s", err)
}
defer localFile.Close()
// 复制文件内容
_, err = io.Copy(localFile, remoteFile)
if err != nil {
log.Fatalf("Failed to copy file: %s", err)
}
fmt.Printf("Copied file: %s\n", file.Name())
}
}
请注意,你需要将示例代码中的username,password,hostname,port,/path/to/remote/directory和/path/to/local/directory替换为你自己的实际值。此外,你还需要确保你的应用程序具有与SSH服务器建立连接和在本地创建文件的权限
原文地址: http://www.cveoy.top/t/topic/i0z5 著作权归作者所有。请勿转载和采集!