-
-
Save udhos/2a20d1f5515900feb21a52ecd0b6a98f to your computer and use it in GitHub Desktop.
an example of scp in golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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