go语言使用scp的方法实例分析
程序员文章站
2022-11-15 12:48:37
本文实例讲述了go语言使用scp的方法。分享给大家供大家参考。具体如下:
复制代码 代码如下:package main
import (
&n...
本文实例讲述了go语言使用scp的方法。分享给大家供大家参考。具体如下:
复制代码 代码如下:
package main
import (
"code.google.com/p/go.crypto/ssh"
"crypto"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"io"
)
const privatekey = `content of id_rsa`
type keychain struct {
key *rsa.privatekey
}
func (k *keychain) key(i int) (interface{}, error) {
if i != 0 {
return nil, nil
}
return &k.key.publickey, nil
}
func (k *keychain) sign(i int, rand io.reader, data []byte) (sig []byte, err error) {
hashfunc := crypto.sha1
h := hashfunc.new()
h.write(data)
digest := h.sum(nil)
return rsa.signpkcs1v15(rand, k.key, hashfunc, digest)
}
func main() {
block, _ := pem.decode([]byte(privatekey))
rsakey, _ := x509.parsepkcs1privatekey(block.bytes)
clientkey := &keychain{rsakey}
clientconfig := &ssh.clientconfig{
user: "wuhao",
auth: []ssh.clientauth{
ssh.clientauthkeyring(clientkey),
},
}
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, "c0644", len(content), "testfile")
fmt.fprint(w, content)
fmt.fprint(w, "\x00") // 传输以\x00结束
}()
if err := session.run("/usr/bin/scp -qrt ./"); err != nil {
panic("failed to run: " + err.error())
}
}
import (
"code.google.com/p/go.crypto/ssh"
"crypto"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"io"
)
const privatekey = `content of id_rsa`
type keychain struct {
key *rsa.privatekey
}
func (k *keychain) key(i int) (interface{}, error) {
if i != 0 {
return nil, nil
}
return &k.key.publickey, nil
}
func (k *keychain) sign(i int, rand io.reader, data []byte) (sig []byte, err error) {
hashfunc := crypto.sha1
h := hashfunc.new()
h.write(data)
digest := h.sum(nil)
return rsa.signpkcs1v15(rand, k.key, hashfunc, digest)
}
func main() {
block, _ := pem.decode([]byte(privatekey))
rsakey, _ := x509.parsepkcs1privatekey(block.bytes)
clientkey := &keychain{rsakey}
clientconfig := &ssh.clientconfig{
user: "wuhao",
auth: []ssh.clientauth{
ssh.clientauthkeyring(clientkey),
},
}
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, "c0644", len(content), "testfile")
fmt.fprint(w, content)
fmt.fprint(w, "\x00") // 传输以\x00结束
}()
if err := session.run("/usr/bin/scp -qrt ./"); err != nil {
panic("failed to run: " + err.error())
}
}
希望本文所述对大家的go语言程序设计有所帮助。
上一篇: go语言简单的处理http请求的函数实例
下一篇: PIGCMS 如何关闭聊天机器人