DEV Community

Dênis Mendes
Dênis Mendes

Posted on

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

Discussion (0)