Skip to content

Instantly share code, notes, and snippets.

@nullne nullne/go_scp.go forked from jedy/go_scp.go
Last active Oct 11, 2017

Embed
What would you like to do?
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
You can’t perform that action at this time.