Here is a minimal example on how to use Go as an scp
client:
config := &ssh.ClientConfig{
User: "user",
Auth: []ssh.AuthMethod{
ssh.Password("pass"),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
client, _ := ssh.Dial("tcp", "remotehost:22", config)
defer client.Close()
session, _ := client.NewSession()
defer session.Close()
file, _ := os.Open("filetocopy")
defer file.Close()
stat, _ := file.Stat()
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
hostIn, _ := session.StdinPipe()
defer hostIn.Close()
fmt.Fprintf(hostIn, "C0664 %d %s
", stat.Size(), "filecopyname")
io.Copy(hostIn, file)
fmt.Fprint(hostIn, "\x00")
wg.Done()
}()
session.Run("/usr/bin/scp -t /remotedirectory/")
wg.Wait()
Note that I have ignored all errors only for conciseness.
-
session.StdinPipe()
will create a writable pipe for the remote host. -
fmt.Fprintf(... "C0664 ...")
will signal the start of a file with0664
permission,stat.Size()
size and the remote filenamefilecopyname
. -
io.Copy(hostIn, file)
will write the contents offile
intohostIn
. -
fmt.Fprint(hostIn, "\x00")
will signal the end of the file. -
session.Run("/usr/bin/scp -qt /remotedirectory/")
will run the scp command.
Edit: Added waitgroup per OP's request