Bootstrap

golang实现sftp发送文件

package main

import (
	"fmt"
	"github.com/pkg/sftp"
	"golang.org/x/crypto/ssh"
	"io"
	"log"
	"net"
	"os"
)

func main() {
	// SSH服务器地址、端口、用户名和私钥文件路径
	username := "test"
	host := "sftp.XXX.com"
	port := 11522
	privateKeyPath := "\\.ssh\\id_rsa"

	// 读取私钥
	key, err := os.ReadFile(privateKeyPath)
	if err != nil {
		log.Fatalf("Failed to read private key: %v", err)
	}

	// 创建Signer
	signer, err := ssh.ParsePrivateKey(key)
	if err != nil {
		log.Fatalf("Failed to parse private key: %v", err)
	}
	// 简化的HostKeyCallback示例,仅用于演示,实际应用中不应这样做!
	hostKeyCallback := func(hostname string, remote net.Addr, key ssh.PublicKey) error {
		return nil // 示例中忽略检查,实际应用需实现正确验证逻辑
	}
	// 设置SSH客户端配置
	config := &ssh.ClientConfig{
		User: username,
		Auth: []ssh.AuthMethod{
			ssh.PublicKeys(signer),
		},
		HostKeyCallback: hostKeyCallback,
	}

	// 建立SSH连接
	conn, err := ssh.Dial("tcp", fmt.Sprintf("%s:%d", host, port), config)
	if err != nil {
		log.Fatalf("Failed to dial: %v", err)
	}
	defer func(conn *ssh.Client) {
		err := conn.Close()
		if err != nil {
			log.Fatalf("Failed to close: %v", err)
		}
	}(conn)

	// 创建SFTP客户端
	sftpClient, err := sftp.NewClient(conn)
	if err != nil {
		log.Fatalf("Failed to create SFTP client: %v", err)
	}
	defer sftpClient.Close()

	// 文件传输示例:从本地发送到远程
	localFilePath := "test123.txt"
	remoteFilePath := "/test123.txt"

	// 打开本地文件
	localFile, err := os.Open(localFilePath)
	if err != nil {
		log.Fatalf("Failed to open local file: %v", err)
	}
	defer func(localFile *os.File) {
		err := localFile.Close()
		if err != nil {
			log.Fatalf("Failed to close local file: %v", err)
		}
	}(localFile)

	// 在远程创建文件并写入
	remoteFile, err := sftpClient.Create(remoteFilePath)
	if err != nil {
		log.Fatalf("Failed to create remote file: %v", err)
	}
	defer func(remoteFile *sftp.File) {
		err := remoteFile.Close()
		if err != nil {
			log.Fatalf("Failed to close remote file: %v", err)			
		}
	}(remoteFile)

	// 执行文件复制
	_, err = io.Copy(remoteFile, localFile)
	if err != nil {
		log.Fatalf("Failed to copy file: %v", err)
	}

	fmt.Println("File transferred successfully.")
}

;