Skip to content

Instantly share code, notes, and snippets.

@hongster
Last active Aug 13, 2021
Embed
What would you like to do?
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