DEV Community

Dênis Mendes
Dênis Mendes

Posted on

1 1

How to connect to SFTP with Golang using PEM and upload a file.

Hi there!

Let's start reading the PEM file:

    /// Read the PEM file.
    pemContentBytes, err := ioutil.ReadFile("google_reserve")
    if err != nil {
        log.Fatal(err)
    }

    password := "123456"

    /// Parse private key with passphrash
    signer, err := ssh.ParsePrivateKeyWithPassphrase(pemContentBytes, []byte(password))
    if err != nil {
        log.Fatalf("SSH PARSE PRIVATE KEY WITH PASSPHRASE FAILED:%v", err)
    }
Enter fullscreen mode Exit fullscreen mode

We have ssh signer so next step is to set up the client with that signer.


    username := "replace_with_sftp_username"
    sftpURL := "replace_with_sftp_url"

    clientConfig := &ssh.ClientConfig{
        User:           username,
        Auth:            []ssh.AuthMethod{ssh.PublicKeys(signer)},
        HostKeyCallback: ssh.InsecureIgnoreHostKey(),
    }

    conn, err := ssh.Dial("tcp", sftpURL, clientConfig)
    if err != nil {
        log.Fatalf("SSH DIAL FAILED:%v", err)
    }
    defer conn.Close()

Enter fullscreen mode Exit fullscreen mode

Now we can start the client to work with the SFTP connection:

    // Create new SFTP client
    sftpNewClient, err := sftp.NewClient(conn)
    if err != nil {
        log.Fatalf("SFTP NEW CLIENT FAILED:%v\n", err)
    }
    defer sftpNewClient.Close()
Enter fullscreen mode Exit fullscreen mode

Below an example how to upload a file:

    fileName := "replace_with_filename.extension"

    sourceFile, err := os.Open(fileName)
    if err != nil {
        return
    }
    defer sourceFile.Close()

    destinationFile, err := sftpNewClient.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC)
    if err != nil {
        log.Fatalf("OS OPEN FILE FAILED: %v\n", err)
    }
    defer destinationFile.Close()

    _, err = io.Copy(destinationFile, sourceFile)
    if err != nil {
        log.Fatalf("IO COPY FAILED: %v\n", err)
    }
Enter fullscreen mode Exit fullscreen mode

It's done :)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay