Created
March 25, 2020 23:56
-
-
Save Oppodelldog/a885759d209c6d8a5b7cd4b06bcb92e7 to your computer and use it in GitHub Desktop.
uploading a file via ssh using golang.org/x/crypto/ssh
This file contains hidden or 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
| package sshupload | |
| import ( | |
| "fmt" | |
| "golang.org/x/crypto/ssh" | |
| "io" | |
| "net" | |
| "os" | |
| "path" | |
| "path/filepath" | |
| ) | |
| const username = "me" | |
| const password = "youknowit" | |
| const serverIP = "targetHost" | |
| const serverPort = "22" | |
| const localImage = "out.png" | |
| const remoteImage = "image.png" | |
| func UploadImage() { | |
| config := &ssh.ClientConfig{ | |
| User: username, | |
| Auth: []ssh.AuthMethod{ | |
| ssh.Password(password), | |
| }, | |
| HostKeyCallback: ssh.InsecureIgnoreHostKey(), | |
| } | |
| t := net.JoinHostPort(serverIP, serverPort) | |
| sshConn, err := ssh.Dial("tcp", t, config) | |
| if err != nil { | |
| fmt.Printf("Failed to connect to %v\n", t) | |
| fmt.Println(err) | |
| os.Exit(2) | |
| } | |
| session, err := sshConn.NewSession() | |
| if err != nil { | |
| fmt.Printf("Cannot create SSH session to %v\n", t) | |
| fmt.Println(err) | |
| os.Exit(2) | |
| } | |
| // Close the session when main returns | |
| defer session.Close() | |
| etargetFile := path.Join("/home/targetDir/", remoteImage) | |
| go func() { | |
| w, err := session.StdinPipe() | |
| if err != nil { | |
| return | |
| } | |
| defer w.Close() | |
| fmt.Println("upload image") | |
| src, err := os.Open(localImage) | |
| panicOnError("os.Open", err) | |
| defer src.Close() | |
| srcStat, err := os.Stat(localImage) | |
| if err != nil { | |
| panic(err) | |
| } | |
| targetFile := filepath.Base(etargetFile) | |
| _, err = fmt.Fprintln(w, "C0644", srcStat.Size(), targetFile) | |
| panicOnError("C0644", err) | |
| if srcStat.Size() > 0 { | |
| n, err:= io.Copy(w, src) | |
| panicOnError("Copy", err) | |
| fmt.Println(n) | |
| _, err = fmt.Fprint(w, "\x00") | |
| panicOnError("\x00", err) | |
| } else { | |
| _, err = fmt.Fprint(w, "\x00") | |
| panicOnError("\x00", err) | |
| } | |
| }() | |
| fmt.Println("start upload") | |
| err = session.Run(fmt.Sprintf("scp -tr %s", etargetFile)) | |
| panicOnError("Run scp", err) | |
| session.Close() | |
| session22, err := sshConn.NewSession() | |
| if err != nil { | |
| fmt.Printf("Cannot create SSH session to %v\n", t) | |
| fmt.Println(err) | |
| os.Exit(2) | |
| } | |
| // Close the session when main returns | |
| defer session22.Close() | |
| } | |
| func panicOnError(msg string, err error) { | |
| if err != nil { | |
| panic(fmt.Errorf("%s: %v", msg, err)) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment