package main
import (
"fmt"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
"io"
"log"
"net"
"os"
)
func main() {
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, err := ssh.ParsePrivateKey(key)
if err != nil {
log.Fatalf("Failed to parse private key: %v", err)
}
hostKeyCallback := func(hostname string, remote net.Addr, key ssh.PublicKey) error {
return nil
}
config := &ssh.ClientConfig{
User: username,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
HostKeyCallback: hostKeyCallback,
}
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)
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.")
}