I spent 3 hours googling for working SCP implementation in Go
I can't find any working lib or example.
This gist is not working. It is buggy but listed in some answers as working code. https://gist.github.com/jedy/3357393
I haven't tried using it, but a search for SCP on godoc got me scp-go. http://godoc.org/github.com/laher/scp-go/scp
you can use a simple https://github.com/tmc/scp
Code snippet for copying a local file to remote machine using scp is below
package main
import (
"io/ioutil"
"net"
"github.com/tmc/scp"
"golang.org/x/crypto/ssh"
)
func getKeyFile() (key ssh.Signer, err error) {
//usr, _ := user.Current()
file := "Path to your key file(.pem)"
buf, err := ioutil.ReadFile(file)
if err != nil {
return
}
key, err = ssh.ParsePrivateKey(buf)
if err != nil {
return
}
return
}
func main() {
key, err := getKeyFile()
if err != nil {
panic(err)
}
// Define the Client Config as :
config := &ssh.ClientConfig{
User: "root",
Auth: []ssh.AuthMethod{
ssh.PublicKeys(key),
},
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
return nil
},
}
client, err := ssh.Dial("tcp", "<remote ip>:22", config)
if err != nil {
panic("Failed to dial: " + err.Error())
}
session, err := client.NewSession()
if err != nil {
panic("Failed to create session: " + err.Error())
}
err = scp.CopyPath("local file path", "remote path", session)
if err != nil {
panic("Failed to Copy: " + err.Error())
}
defer session.Close()
Hope it helps.
Here is the most advanced SCP client implementation in go.
Beside regular CRUD operations, it also supports batch upload, symbolic links and modification time preservation.
var config *ssh.ClientConfig
//load config ...
timeoutMS := 15000
service, err := scp.NewStorager("127.0.0.1:22", timeoutMS, config)
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
location := "/tmp/myfile"
err = service.Upload(ctx, location, 0644, []byte("somedata"))
if err != nil {
log.Fatal(err)
}
reader, err := service.Download(ctx, location)
if err != nil {
log.Fatal(err)
}