[Go] go语言里使用scp的范例 →→→→→进入此内容的聊天室

来自 , 2019-10-19, 写在 Go, 查看 141 次.
URL http://www.code666.cn/view/aad5adc3
  1. // https://blogs.oracle.com/janp/entry/how_the_scp_protocol_works
  2. package main
  3.  
  4. import (
  5.         "code.google.com/p/go.crypto/ssh"
  6.         "crypto"
  7.         "crypto/rsa"
  8.         "crypto/x509"
  9.         "encoding/pem"
  10.         "fmt"
  11.         "io"
  12. )
  13.  
  14. const privateKey = `content of id_rsa`
  15.  
  16. type keychain struct {
  17.         key *rsa.PrivateKey
  18. }
  19.  
  20. func (k *keychain) Key(i int) (interface{}, error) {
  21.         if i != 0 {
  22.                 return nil, nil
  23.         }
  24.         return &k.key.PublicKey, nil
  25. }
  26.  
  27. func (k *keychain) Sign(i int, rand io.Reader, data []byte) (sig []byte, err error) {
  28.         hashFunc := crypto.SHA1
  29.         h := hashFunc.New()
  30.         h.Write(data)
  31.         digest := h.Sum(nil)
  32.         return rsa.SignPKCS1v15(rand, k.key, hashFunc, digest)
  33. }
  34.  
  35. func main() {
  36.         block, _ := pem.Decode([]byte(privateKey))
  37.         rsakey, _ := x509.ParsePKCS1PrivateKey(block.Bytes)
  38.         clientKey := &keychain{rsakey}
  39.         clientConfig := &ssh.ClientConfig{
  40.                 User: "wuhao",
  41.                 Auth: []ssh.ClientAuth{
  42.                         ssh.ClientAuthKeyring(clientKey),
  43.                 },
  44.         }
  45.         client, err := ssh.Dial("tcp", "127.0.0.1:22", clientConfig)
  46.         if err != nil {
  47.                 panic("Failed to dial: " + err.Error())
  48.         }
  49.         session, err := client.NewSession()
  50.         if err != nil {
  51.                 panic("Failed to create session: " + err.Error())
  52.         }
  53.         defer session.Close()
  54.         go func() {
  55.                 w, _ := session.StdinPipe()
  56.                 defer w.Close()
  57.                 content := "123456789\n"
  58.                 fmt.Fprintln(w, "C0644", len(content), "testfile")
  59.                 fmt.Fprint(w, content)
  60.                 fmt.Fprint(w, "\x00") // 传输以\x00结束
  61.         }()
  62.         if err := session.Run("/usr/bin/scp -qrt ./"); err != nil {
  63.                 panic("Failed to run: " + err.Error())
  64.         }
  65. }
  66. //go/8188

回复 "go语言里使用scp的范例"

这儿你可以回复上面这条便签

captcha