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 :)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay