Skip to content

Instantly share code, notes, and snippets.

@kcrawford
Forked from jedy/go_scp.go
Created November 5, 2015 21:04
Show Gist options
  • Save kcrawford/b3fa30235afaad49529b to your computer and use it in GitHub Desktop.
Save kcrawford/b3fa30235afaad49529b to your computer and use it in GitHub Desktop.
an example of scp in golang
// https://blogs.oracle.com/janp/entry/how_the_scp_protocol_works
package main
import (
"fmt"
"golang.org/x/crypto/ssh"
)
const privateKey = `content of id_rsa`
func main() {
signer, _ := ssh.ParsePrivateKey([]byte(privateKey))
clientConfig := &ssh.ClientConfig{
User: "jedy",
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
}
client, err := ssh.Dial("tcp", "127.0.0.1:22", clientConfig)
if err != nil {
panic("Failed to dial: " + err.Error())
}
session, err := client.NewSession()
if err != nil {
panic("Failed to create session: " + err.Error())
}
defer session.Close()
go func() {
w, _ := session.StdinPipe()
defer w.Close()
content := "123456789\n"
fmt.Fprintln(w, "D0755", 0, "testdir") // mkdir
fmt.Fprintln(w, "C0644", len(content), "testfile1")
fmt.Fprint(w, content)
fmt.Fprint(w, "\x00") // transfer end with \x00
fmt.Fprintln(w, "C0644", len(content), "testfile2")
fmt.Fprint(w, content)
fmt.Fprint(w, "\x00")
}()
if err := session.Run("/usr/bin/scp -tr ./"); err != nil {
panic("Failed to run: " + err.Error())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment