Monday, March 20, 2023

golang: sftp connecting to a remote server


package main

import (
  "github.com/pkg/sftp"
  "golang.org/x/crypto/ssh"
  "log"
)

func main() {
 
  // for demo purpose only. Such config is not so secure.
  config := &ssh.ClientConfig {
    User: "myusername",
    Auth: []ssh.AuthMethod {
      ssh.Password("mypassword") },
    HostKeyCallback: ssh.InsecureIgnoreHostKey(),
  }

  // Connect to the server
  conn, err := ssh.Dial("tcp", "myhost:12345", config)

  if err != nil {
    log.Fatal(err)
  }

  defer conn.Close()

  // Open SFTP session
  session, err := sftp.NewClient(conn)

  if err != nil {
    log.Fatal(err)
  }

  defer session.Close()

  fileInfo, err := session.Lstat("my-remote-file")

  if err != nil {
    log.Fatal(err)
  }

  log.Println(fileInfo)
}



No comments:

 
Get This <