go语言使用scp的方法实例分析
本文实例讲述了go语言使用scp的方法。分享给大家供大家参考。具体如下:
packagemain import( "code.google.com/p/go.crypto/ssh" "crypto" "crypto/rsa" "crypto/x509" "encoding/pem" "fmt" "io" ) constprivateKey=`contentofid_rsa` typekeychainstruct{ key*rsa.PrivateKey } func(k*keychain)Key(iint)(interface{},error){ ifi!=0{ returnnil,nil } return&k.key.PublicKey,nil } func(k*keychain)Sign(iint,randio.Reader,data[]byte)(sig[]byte,errerror){ hashFunc:=crypto.SHA1 h:=hashFunc.New() h.Write(data) digest:=h.Sum(nil) returnrsa.SignPKCS1v15(rand,k.key,hashFunc,digest) } funcmain(){ 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) iferr!=nil{ panic("Failedtodial:"+err.Error()) } session,err:=client.NewSession() iferr!=nil{ panic("Failedtocreatesession:"+err.Error()) } defersession.Close() gofunc(){ w,_:=session.StdinPipe() deferw.Close() content:="123456789\n" fmt.Fprintln(w,"C0644",len(content),"testfile") fmt.Fprint(w,content) fmt.Fprint(w,"\x00")//传输以\x00结束 }() iferr:=session.Run("/usr/bin/scp-qrt./");err!=nil{ panic("Failedtorun:"+err.Error()) } }
希望本文所述对大家的Go语言程序设计有所帮助。