exec

package
v0.4.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 11, 2025 License: MIT Imports: 8 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ExecCmd = &cobra.Command{
	Use:   "exec [USER@]SERVER COMMAND...",
	Short: "Execute a command on a remote server",
	Long: `Execute a command on a remote server.
	
	This command executes a specified command on a remote server and returns the output.
	It supports SSH-like syntax for specifying the user and server.
	
	Examples:
	  alpacon exec prod-docker docker ps
	  alpacon exec root@prod-docker docker ps
	  alpacon exec admin@web-server ls -la /var/log
	  alpacon exec -u root prod-docker systemctl status nginx
	  alpacon exec -g docker user@server docker images
	`,
	Args: cobra.MinimumNArgs(2),
	Run: func(cmd *cobra.Command, args []string) {
		username, _ := cmd.Flags().GetString("username")
		groupname, _ := cmd.Flags().GetString("groupname")

		if len(args) < 2 {
			utils.CliError("You must specify at least a server name and a command.")
			return
		}

		serverName := args[0]
		commandArgs := args[1:]

		if strings.Contains(serverName, "@") && !strings.Contains(serverName, ":") {
			sshTarget := utils.ParseSSHTarget(serverName)
			if username == "" && sshTarget.User != "" {
				username = sshTarget.User
			}
			serverName = sshTarget.Host
		}

		alpaconClient, err := client.NewAlpaconAPIClient()
		if err != nil {
			utils.CliError("Connection to Alpacon API failed: %s. Consider re-logging.", err)
			return
		}

		command := strings.Join(commandArgs, " ")
		env := make(map[string]string)

		result, err := event.RunCommand(alpaconClient, serverName, command, username, groupname, env)
		if err != nil {
			code, _ := utils.ParseErrorResponse(err)
			if code == utils.CodeAuthMFARequired {
				err := mfa.HandleMFAError(alpaconClient, serverName)
				if err != nil {
					utils.CliError("MFA authentication failed: %s", err)
				}

				for {
					fmt.Println("Waiting for MFA authentication...")
					time.Sleep(5 * time.Second)

					result, err = event.RunCommand(alpaconClient, serverName, command, username, groupname, env)
					if err == nil {
						fmt.Println("MFA authentication has been completed!")
						break
					}
				}
			} else {
				utils.CliError("Failed to execute command on '%s' server: %s.", serverName, err)
				return
			}
		}
		fmt.Println(result)
	},
}

Functions

This section is empty.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL