Skip to content

Instantly share code, notes, and snippets.

@hitxiang
Last active June 19, 2018 02:48
Show Gist options
  • Save hitxiang/7e7d4ba75259acbb9cc1c9737fe9951a to your computer and use it in GitHub Desktop.
Save hitxiang/7e7d4ba75259acbb9cc1c9737fe9951a to your computer and use it in GitHub Desktop.
go sftp client sample
sftp.user=xxx
sftp.connection=xxxx:port-num
sftp.private_key_path=xxx
package util
import (
"io"
"io/ioutil"
"log"
"os"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
"github.com/joho/godotenv"
"golang.org/x/text/encoding"
"golang.org/x/text/transform"
)
var (
userName string
serverConn string
keyFilePath string
)
func init() {
err := godotenv.Load(".env")
if err != nil {
log.Fatalf("Error loading .env file: %v", err)
}
userName = os.Getenv("sftp.user")
serverConn = os.Getenv("sftp.connection")
keyFilePath = os.Getenv("sftp.private_key_path")
}
func download(targetPath string, encoding encoding.Encoding) ([]byte, error) {
publicKey, err := sshPublicKeyFile(keyFilePath)
if err != nil {
return nil, err
}
config := &ssh.ClientConfig{
User: userName,
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
Auth: []ssh.AuthMethod{
publicKey,
},
}
config.SetDefaults()
sshConn, err := ssh.Dial("tcp", serverConn, config)
if err != nil {
return nil, err
}
defer sshConn.Close()
client, err := sftp.NewClient(sshConn)
if err != nil {
return nil, err
}
defer client.Close()
r, err := client.Open(targetPath)
if err != nil {
return nil, err
}
defer r.Close()
decodedReader := io.Reader(r)
if encoding != nil {
decodedReader = transform.NewReader(r, encoding.NewDecoder())
}
buf, err := ioutil.ReadAll(decodedReader)
return buf, err
}
func sshPublicKeyFile(filePath string) (ssh.AuthMethod, error) {
buffer, err := ioutil.ReadFile(filePath)
if err != nil {
return nil, err
}
key, err := ssh.ParsePrivateKey(buffer)
if err != nil {
return nil, err
}
return ssh.PublicKeys(key), nil
}
package util
import (
"fmt"
"testing"
"golang.org/x/text/encoding/japanese"
)
func TestDownload(t *testing.T) {
buf, err := download("/share/xxxxs.csv", japanese.ShiftJIS)
if err != nil {
message := fmt.Sprintf("error happened: %v", err)
t.Fatal(message)
}
fmt.Printf("file context\n: %s", string(buf))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment