Skip to content

Instantly share code, notes, and snippets.

@hongster
Last active August 13, 2021 05:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hongster/396af72c8a699d7e1abaa98b468a4bbd to your computer and use it in GitHub Desktop.
Save hongster/396af72c8a699d7e1abaa98b468a4bbd to your computer and use it in GitHub Desktop.
Sample SFTP connection in Go
package main
import (
"fmt"
"os"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
)
func main() {
host := "127.0.0.1"
username := "foobar"
password := "secret"
port := ":22" // Make sure there is colon ":" prefix
config := &ssh.ClientConfig{
User: username,
Auth: []ssh.AuthMethod{
ssh.Password(password),
},
// `InsecureIgnoreHostKey` is not recommended. Consider other more secured method for verifying host key
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
// Establishing connection
conn, err := ssh.Dial("tcp", host+port, config)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to dial: %v\n", err)
os.Exit(1)
}
// `client` is the handler for performing operations on SFTP server
client, err := sftp.NewClient(conn)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to create client: %v\n", err)
os.Exit(1)
}
// Example for checking available storage space
statVF, err := client.StatVFS("/")
if err != nil {
fmt.Fprintf(os.Stderr, "Fail to get filesystem info: %v\n", err)
os.Exit(1)
}
fmt.Printf("Space available: %d bytes\n", statVF.FreeSpace())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment