diff --git a/internal/cmd/connect/ssh/ssh.go b/internal/cmd/connect/ssh/ssh.go index 949eadc..b3bc813 100644 --- a/internal/cmd/connect/ssh/ssh.go +++ b/internal/cmd/connect/ssh/ssh.go @@ -25,6 +25,8 @@ const ( var ( localPortForwarding string + command string + options []string ) func NewCommand() *cobra.Command { @@ -34,11 +36,18 @@ func NewCommand() *cobra.Command { Short: descriptionShort, Long: strings.ReplaceAll(descriptionLong, "\t", ""), + PreRun: func(cmd *cobra.Command, args []string) { + if cmd.Flags().Changed("local-port-forwarding") && cmd.Flags().Changed("command") { + fancy.Fatalf(CommandArgsConflict1ErrorMessage) + } + }, Run: RunCommand, } cmd.Flags().StringVarP(&localPortForwarding, "local-port-forwarding", "l", "", `local port forwarding, [local_address:]local_port:destination_host:destination_port. Examples: -l 8080:localhost:80`) + cmd.Flags().StringVarP(&command, "command", "c", "", `command to execute on the remote machine. Examples: -c "ls /home//"`) + cmd.Flags().StringArrayVarP(&options, "option", "o", []string{}, `allow to add more connection options. Examples: -o ControlMaster=auto`) return cmd } @@ -162,6 +171,10 @@ func RunCommand(cmd *cobra.Command, args []string) { "-A", targetSessionSshUsername + "@127.0.0.1", "-i", temporaryPrivatekeyFile} + for _, option := range options { + sshConnectionArgs = append(sshConnectionArgs, "-o", option) + } + if localPortForwarding != "" { sshConnectionArgs = append(sshConnectionArgs, "-L", localPortForwarding) // This line prevents the insterative shell from opening and keeps the server in background. @@ -169,6 +182,11 @@ func RunCommand(cmd *cobra.Command, args []string) { fancy.Printf(SshLocalPortForwardingInfoMessage) } + // Must be the last argument + if command != "" { + sshConnectionArgs = append(sshConnectionArgs, command) + } + sshCommand := exec.Command("ssh", sshConnectionArgs...) sshCommand.Stdin = os.Stdin diff --git a/internal/cmd/connect/ssh/templates.go b/internal/cmd/connect/ssh/templates.go index 83c0828..4cff03c 100644 --- a/internal/cmd/connect/ssh/templates.go +++ b/internal/cmd/connect/ssh/templates.go @@ -59,4 +59,9 @@ const ( Press following combination to kill the connection once you don't need it: {Bold}{White}console ~$ {Green}Cntrl + C {Reset}` + + // CommandArgsConflict1ErrorMessage is the message thrown when the user is trying to establish a connection + // with both --local-port-forwarding (-l) and --command (-c) flags + CommandArgsConflict1ErrorMessage = ` + {Red}You cannot use --local-port-forwarding (-l) and --command (-c) together.` )