lasso/cmd/lassoctl/cmd/send.go

82 lines
2.2 KiB
Go

/*
Copyright © 2021 Arsen Musayelyan
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cmd
import (
"os"
"os/exec"
"regexp"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
)
// sendCmd represents the send command
var sendCmd = &cobra.Command{
Use: "send <file...> <username@node:path>",
Short: "Send a file to the node via ssh",
Run: func(cmd *cobra.Command, args []string) {
if len(args) < 2 {
cmd.Usage()
os.Exit(1)
}
// Get list of nodes from server
nodes := getNodeList()
// Compile regular expression for target argument
regex := regexp.MustCompile(`(.+)@(.+):(.+)`)
// Find submatches within last argument
submatches := regex.FindStringSubmatch(args[len(args)-1])
// If no submatches found
if submatches == nil {
log.Fatal().Msg("Invalid target argument")
}
// Files are all arguments except last one
files := args[0 : len(args)-1]
// Get variables from submatches
username, nodeName, path := submatches[1], submatches[2], submatches[3]
// Get node from list if it exists
node, ok := nodes[nodeName]
if !ok {
log.Fatal().Str("node", nodeName).Msg("Node does not exist on the server")
}
// Create arguments for scp command
var scpArgs []string
scpArgs = append(scpArgs, files...)
scpArgs = append(scpArgs, username+"@"+node.IP+":"+path)
// Create scp command
scp := exec.Command("scp", scpArgs...)
scp.Stdin = os.Stdin
scp.Stdout = os.Stdout
scp.Stderr = os.Stderr
// Run scp command
if err := scp.Run(); err != nil {
log.Fatal().Err(err).Msg("Error received from scp command")
}
},
}
func init() {
fileCmd.AddCommand(sendCmd)
}