Skip to content

Instantly share code, notes, and snippets.

@dvwright
Created June 14, 2017 20:18
Show Gist options
  • Save dvwright/0e7994923e96fea44e9914c40b1dc856 to your computer and use it in GitHub Desktop.
Save dvwright/0e7994923e96fea44e9914c40b1dc856 to your computer and use it in GitHub Desktop.
scp multiple files with password in go
// modified from https://gist.github.com/jedy/3357393 - Thanks!
package main
import (
"fmt"
"golang.org/x/crypto/ssh"
"io/ioutil"
"log"
"os"
)
// sftp host, accepts ssh/scp login
func sftpReports(reports []string) {
config := &ssh.ClientConfig{
User: "Remote User",
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
Auth: []ssh.AuthMethod{
ssh.Password("Send Password - Should Be Using SSH KEY!"),
},
}
client, err := ssh.Dial("tcp", "remotehost:22", config)
if err != nil {
log.Fatal("Failed to dial:", err)
}
session, err := client.NewSession()
if err != nil {
log.Fatalln("Failed to create session: " + err.Error())
}
defer session.Close()
go func() {
srcDir := "/home/reports/"
w, _ := session.StdinPipe()
defer w.Close()
// iterate report files, add contents to pipe for scp to remote host
for _, report := range reports {
log.Println(report + ": ----- Report name -----")
// only if small/medium report files
dat, err := ioutil.ReadFile(srcDir + report)
if err != nil {
log.Fatalln(err)
}
content := string(dat)
fmt.Fprintln(w, "C0644", len(content), report)
fmt.Fprint(w, content)
fmt.Fprint(w, "\x00") // transfer end with \x00
// move file to archive location, contents already added to pipe // go 1.8
err = os.Rename(srcDir+report, srcDir+"/archive/"+report)
if err != nil {
fmt.Println(err)
}
}
}()
// copies pipe payload to users default directory on remote location
if err := session.Run("/usr/bin/scp -tr ./"); err != nil {
log.Fatalln("Failed to run: " + err.Error())
}
log.Println("scp reports success")
}
func main() {
// in reality populated from reading a directory
reports := []string{"report1.csv", "report2.csv", "report3.csv"}
sftpReports(reports)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment