-
-
Save hongster/396af72c8a699d7e1abaa98b468a4bbd to your computer and use it in GitHub Desktop.
Sample SFTP connection in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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