Last active
February 28, 2024 16:23
-
-
Save alfajrimutawadhi/5449690b07e413648b9bbbc90540a0c8 to your computer and use it in GitHub Desktop.
golang connect sftp with ssh
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"os" | |
"github.com/pkg/sftp" | |
"golang.org/x/crypto/ssh" | |
kh "golang.org/x/crypto/ssh/knownhosts" | |
) | |
func main() { | |
user := "USER" | |
address := "ADDRESS" | |
port := "PORT" | |
dirKey := "KEY.PEM" // directory file .pem or .cer | |
privateKey, err := os.ReadFile(dirKey) | |
if err != nil { | |
log.Fatal("cannot get pem file") | |
} | |
signer, err := ssh.ParsePrivateKey(privateKey) | |
if err != nil { | |
log.Fatal(err) | |
} | |
homeDir := os.Getenv("HOME") | |
hostKeyCallback, err := kh.New(homeDir+"/.ssh/known_hosts") | |
if err != nil { | |
log.Fatal("could not create hostkeycallback function :", err) | |
} | |
auths := []ssh.AuthMethod{ssh.PublicKeys(signer)} | |
cfg := &ssh.ClientConfig{ | |
User: user, | |
Auth: auths, | |
HostKeyCallback: hostKeyCallback, | |
} | |
cfg.SetDefaults() | |
// create session ssh | |
client, err := ssh.Dial("tcp", address+":"+port, cfg) | |
if err != nil { | |
log.Fatal(err) | |
} | |
session, err := client.NewSession() | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer session.Close() | |
log.Println("we have a session") | |
// create new sftp client | |
sc, err := sftp.NewClient(client) | |
if err != nil { | |
fmt.Sprint(os.Stderr, "Unable to start SFTP subsystem : %v\n", err) | |
os.Exit(1) | |
} | |
defer sc.Close() | |
log.Println("connect to sftp") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment