move UploadFile into package
parent
f5cebdff81
commit
ba483d7c25
@ -0,0 +1,90 @@
|
||||
package commands
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
type UploadFileArgs struct {
|
||||
Command string `json:"command"`
|
||||
LocalFilepath string `json:"local_filepath"`
|
||||
DestinationFilepath string `json:"destination_filepath"`
|
||||
PrivateKeyFile string `json:"private_key_file"`
|
||||
Username string `json:"username"`
|
||||
Host string `json:"host"`
|
||||
}
|
||||
|
||||
func (ufa *UploadFileArgs) ReadArgs() {
|
||||
|
||||
if len(os.Args) != 7 {
|
||||
fmt.Fprintf(os.Stderr, "Usage: %s upload_file <local-file> <remote-path> <private-key> <username> <host>\n", os.Args[0])
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
ufa.Command = os.Args[1]
|
||||
ufa.LocalFilepath = os.Args[2]
|
||||
ufa.DestinationFilepath = os.Args[3]
|
||||
ufa.PrivateKeyFile = os.Args[4]
|
||||
ufa.Username = os.Args[5]
|
||||
ufa.Host = os.Args[6]
|
||||
|
||||
}
|
||||
|
||||
func UploadFile() {
|
||||
|
||||
args := UploadFileArgs{}
|
||||
args.ReadArgs()
|
||||
|
||||
client := GetClient(args.PrivateKeyFile, args.Username, args.Host)
|
||||
defer client.Close()
|
||||
|
||||
session, err := client.NewSession()
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error creating SSH session: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer session.Close()
|
||||
|
||||
source_file, err := os.Open(args.LocalFilepath)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error opening local file: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer source_file.Close()
|
||||
|
||||
info, err := source_file.Stat()
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error stating local file: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
w, err := session.StdinPipe()
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error creating stdin pipe: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
if err := session.Start("scp -t " + args.DestinationFilepath); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error starting scp: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
fmt.Fprintf(w, "C0644 %d %s\n", info.Size(), filepath.Base(args.LocalFilepath))
|
||||
if _, err := io.Copy(w, source_file); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error sending file: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Fprint(w, "\x00")
|
||||
w.Close()
|
||||
|
||||
if err := session.Wait(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error during scp transfer: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
fmt.Println("Success")
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue