Compare commits

..

No commits in common. "ae2c8ef4029279bc7cd0a1c63de8bc3ac0fd4f1f" and "3be8ebcd023b930932dc65438b140d251064afe6" have entirely different histories.

170
backup.go
View File

@ -13,75 +13,47 @@ import (
"git.andrewnw.xyz/CyberShell/backy/pkg/backy"
"github.com/kevinburke/ssh_config"
"github.com/spf13/viper"
"golang.org/x/crypto/ssh"
)
// const logFile = "backy.log"
type backupCommand struct {
// command to run
Cmd string
cmd string
// host on which to run cmd
Host string
host string
// Shell specifies which shell to run the command in, if any
// Not applicable when host is not local
Shell string
shell string
// path to the command
path string
// cmdArgs is an array that holds the arguments to cmd
CmdArgs []string
cmdArgs []string
}
// type config struct {
// Commands struct {
// backupCommand `mapstructure:",squash"`
// }
// }
var testCmd = &backupCommand{
Cmd: "hostname",
Shell: "bash",
CmdArgs: []string{},
}
var remoteHost backy.Host
var remoteHost *backy.Host
func main() {
var test = true
if test {
readConfigFile()
} else {
remoteHost.User = "root"
testCmd.runCmd()
// shutdownEmailSvr.runCmd()
// backupEmailSvrRestic.runCmd()
// backupEmailSvrRsync.runCmd()
// startEmailSvr.runCmd()
}
}
func (command *backupCommand) runCmd() {
var cmdArgsStr string
for _, v := range command.CmdArgs {
for _, v := range command.cmdArgs {
cmdArgsStr += fmt.Sprintf(" %s", v)
}
fmt.Printf("\n\nRunning command: " + command.Cmd + " " + cmdArgsStr + " on host " + command.Host + "...\n\n")
if command.Host != "local" {
fmt.Printf("\n\nRunning command: " + command.cmd + " " + cmdArgsStr + " on host " + command.host + "...\n\n")
if command.host != "local" {
remoteHost.Port = 22
remoteHost.Host = command.Host
remoteHost.Host = command.host
sshc, err := connectToSSHHost(&remoteHost)
sshc, err := connectToSSHHost(remoteHost)
if err != nil {
panic(fmt.Errorf("ssh dial: %w", err))
}
@ -92,8 +64,8 @@ func (command *backupCommand) runCmd() {
}
defer s.Close()
cmd := command.Cmd
for _, a := range command.CmdArgs {
cmd := command.cmd
for _, a := range command.cmdArgs {
cmd += " " + a
}
@ -104,31 +76,31 @@ func (command *backupCommand) runCmd() {
if err != nil {
panic(fmt.Errorf("error when running cmd " + cmd + "\n Error: " + err.Error()))
}
// fmt.Printf("Output: %s\n", string(output))
} else {
// shell := "/bin/bash"
var err error
if command.Shell != "" {
cmdArgsStr = fmt.Sprintf("%s %s", command.Cmd, cmdArgsStr)
localCMD := exec.Command(command.Shell, "-c", cmdArgsStr)
if command.shell != "" {
cmdArgsStr = fmt.Sprintf("%s %s", command.cmd, cmdArgsStr)
localCMD := exec.Command(command.shell, "-c", cmdArgsStr)
var stdoutBuf, stderrBuf bytes.Buffer
localCMD.Stdout = io.MultiWriter(os.Stdout, &stdoutBuf)
localCMD.Stderr = io.MultiWriter(os.Stderr, &stderrBuf)
err = localCMD.Run()
if err != nil {
panic(fmt.Errorf("error when running cmd: %s: %w", command.Cmd, err))
panic(fmt.Errorf("error when running cmd: %s: %w", command.cmd, err))
}
return
}
localCMD := exec.Command(command.Cmd, command.CmdArgs...)
// localCMD := exec.Command(command.cmd, command.args...)
var stdoutBuf, stderrBuf bytes.Buffer
localCMD.Stdout = io.MultiWriter(os.Stdout, &stdoutBuf)
localCMD.Stderr = io.MultiWriter(os.Stderr, &stderrBuf)
err = localCMD.Run()
// var stdoutBuf, stderrBuf bytes.Buffer
// localCMD.Stdout = io.MultiWriter(os.Stdout, &stdoutBuf)
// localCMD.Stderr = io.MultiWriter(os.Stderr, &stderrBuf)
// err = localCMD.Run()
if err != nil {
panic(fmt.Errorf("error when running cmd: %s: %w", command.Cmd, err))
panic(fmt.Errorf("error when running cmd: %s: %w", command.cmd, err))
}
// fmt.Printf("%s\n", string(output))
}
@ -175,7 +147,7 @@ func connectToSSHHost(remoteConfig *backy.Host) (*ssh.Client, error) {
panic(fmt.Errorf("parse private key: %w", err))
}
sshConfig := &ssh.ClientConfig{
User: remoteHost.User,
User: "root",
Auth: []ssh.AuthMethod{ssh.PublicKeys(signer)},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
@ -186,91 +158,3 @@ func connectToSSHHost(remoteConfig *backy.Host) (*ssh.Client, error) {
}
return sshc, connectErr
}
func readConfigFile() {
viper.SetConfigName("backy") // name of config file (without extension)
viper.SetConfigType("yaml") // REQUIRED if the config file does not have the extension in the name
viper.AddConfigPath("$HOME/.config/backy") // call multiple times to add many search paths
viper.AddConfigPath(".") // optionally look for config in the working directory
err := viper.ReadInConfig() // Find and read the config file
if err != nil { // Handle errors reading the config file
panic(fmt.Errorf("fatal error config file: %w", err))
}
// if err := viper.ReadInConfig(); err != nil {
// if _, ok := err.(viper.ConfigFileNotFoundError); ok {
// // Config file not found; ignore error if desired
// } else {
// // Config file was found but another error was produced
// }
// }
// Config file found and successfully parsed
// viper.WriteConfig() // writes current config to predefined path set by 'viper.AddConfigPath()' and 'viper.SetConfigName'
// err = viper.Unmarshal(&C)
// if err != nil {
// panic(fmt.Errorf("unable to decode into struct, %v", err))
// }
commandsMap := viper.GetStringMapString("commands")
var cmdNames []string
for k := range commandsMap {
cmdNames = append(cmdNames, k)
}
var cmdStructs []backupCommand
for _, cmdName := range cmdNames {
var backupCmdStruct backupCommand
println(cmdName)
subCmd := viper.Sub(getNestedConfig("commands", cmdName))
hostSet := subCmd.IsSet("host")
host := subCmd.GetString("host")
cmdSet := subCmd.IsSet("cmd")
cmd := subCmd.GetString("cmd")
cmdArgsSet := subCmd.IsSet("cmdargs")
cmdArgs := subCmd.GetStringSlice("cmdargs")
if hostSet {
println("Host:")
println(host)
backupCmdStruct.Host = host
} else {
println("Host is not set")
}
if cmdSet {
println("Cmd:")
println(cmd)
backupCmdStruct.Cmd = cmd
} else {
println("Cmd is not set")
}
if cmdArgsSet {
println("CmdArgs:")
for _, arg := range cmdArgs {
println(arg)
}
backupCmdStruct.CmdArgs = cmdArgs
} else {
println("CmdArgs is not set")
}
cmdStructs = append(cmdStructs, backupCmdStruct)
for _, cmd := range cmdStructs {
fmt.Printf("Cmd is %s\n", cmd.Cmd)
fmt.Printf("Host is %s\n", cmd.Host)
}
}
cmdOrder := viper.GetStringMapStringSlice("cmd-order")
for cmd, orderSlice := range cmdOrder {
println("Cmd name: ", cmd)
println("Cmd order: ")
for _, v := range orderSlice {
println(v)
}
}
}
func getNestedConfig(nestedConfig, key string) string {
return fmt.Sprintf("%s.%s", nestedConfig, key)
}