-
Notifications
You must be signed in to change notification settings - Fork 17
feat(server): 新增 zeabur server exec(DES-802) #263
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
leechenghsiu
merged 2 commits into
main
from
matthewlee/des-802-cli-新增-zeabur-server-exec:在-server-上直接執行命令(免手動-ssh-拼裝)
Jul 10, 2026
The head ref may contain hidden characters: "matthewlee/des-802-cli-\u65B0\u589E-zeabur-server-exec\uFF1A\u5728-server-\u4E0A\u76F4\u63A5\u57F7\u884C\u547D\u4EE4\uFF08\u514D\u624B\u52D5-ssh-\u62FC\u88DD\uFF09"
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,196 @@ | ||
| // Package exec implements `zeabur server exec`: run a command on a dedicated | ||
| // server over SSH and stream its output. | ||
| // | ||
| // Unlike the two-step `server ssh-info` + hand-rolled ssh2/sshpass flow (which | ||
| // embeds the password into a multi-layer-escaped shell script and corrupts | ||
| // passwords containing special characters), this fetches the credentials and | ||
| // opens the connection entirely in-process via golang.org/x/crypto/ssh. The | ||
| // password is never printed nor passed through a shell, so special characters | ||
| // are safe and no external ssh/sshpass client is required (DES-802). | ||
| package exec | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "fmt" | ||
| "os" | ||
| "strings" | ||
| "time" | ||
|
|
||
| "github.com/spf13/cobra" | ||
| "golang.org/x/crypto/ssh" | ||
|
|
||
| "github.com/zeabur/cli/internal/cmdutil" | ||
| ) | ||
|
|
||
| type Options struct { | ||
| id string | ||
| } | ||
|
|
||
| func NewCmdExec(f *cmdutil.Factory) *cobra.Command { | ||
| opts := &Options{} | ||
|
|
||
| cmd := &cobra.Command{ | ||
| Use: "exec [server-id] -- <command> [args...]", | ||
| Short: "Run a command on a dedicated server over SSH", | ||
| Long: `Run a command on a dedicated server over SSH and stream its output. | ||
|
|
||
| Credentials are fetched and used inside the CLI — never printed and never passed | ||
| through a shell — so passwords with special characters work and no external ssh | ||
| or sshpass client is required. | ||
|
|
||
| The command after '--' is joined with spaces and run by the remote login shell, | ||
| matching 'ssh host <command>' semantics. Quote a compound command as a single | ||
| argument to keep it intact.`, | ||
| Example: ` zeabur server exec --id <server-id> -- uname -a | ||
| zeabur server exec <server-id> -- sudo kubectl get pods -A | ||
| zeabur server exec <server-id> -- 'echo start && sudo systemctl status k3s'`, | ||
| Args: cobra.MinimumNArgs(1), | ||
| RunE: func(cmd *cobra.Command, args []string) error { | ||
| // Everything after '--' is the remote command; anything before it is | ||
| // the optional positional server id. cobra reports the '--' position. | ||
| dash := cmd.ArgsLenAtDash() | ||
| if dash < 0 { | ||
| return fmt.Errorf("missing command; use: zeabur server exec [server-id] -- <command>") | ||
| } | ||
|
|
||
| positional := args[:dash] | ||
| remoteArgs := args[dash:] | ||
| if len(remoteArgs) == 0 { | ||
| return fmt.Errorf("no command given after '--'") | ||
| } | ||
| if len(positional) > 1 { | ||
| return fmt.Errorf("unexpected arguments before '--': %v", positional[1:]) | ||
| } | ||
| if len(positional) == 1 { | ||
| if opts.id != "" && opts.id != positional[0] { | ||
| return fmt.Errorf("conflicting server IDs: arg=%q, --id=%q", positional[0], opts.id) | ||
| } | ||
| opts.id = positional[0] | ||
| } | ||
|
|
||
| return runExec(f, opts, strings.Join(remoteArgs, " ")) | ||
| }, | ||
| } | ||
|
|
||
| cmd.Flags().StringVar(&opts.id, "id", "", "Server ID") | ||
|
|
||
| return cmd | ||
| } | ||
|
|
||
| // selectServer prompts the user to pick a server when no id was given (mirrors | ||
| // `server ssh`). The remote command itself stays non-interactive. | ||
| func selectServer(ctx context.Context, f *cmdutil.Factory) (string, error) { | ||
| servers, err := f.ApiClient.ListServers(ctx, f.CurrentOwnerID()) | ||
| if err != nil { | ||
| return "", fmt.Errorf("list servers failed: %w", err) | ||
| } | ||
| if len(servers) == 0 { | ||
| return "", fmt.Errorf("no servers found") | ||
| } | ||
|
|
||
| options := make([]string, len(servers)) | ||
| for i, s := range servers { | ||
| location := s.IP | ||
| if s.City != nil && s.Country != nil { | ||
| location = fmt.Sprintf("%s, %s", *s.City, *s.Country) | ||
| } else if s.Country != nil { | ||
| location = *s.Country | ||
| } | ||
| options[i] = fmt.Sprintf("%s (%s)", s.Name, location) | ||
| } | ||
|
|
||
| idx, err := f.Prompter.Select("Select a server", "", options) | ||
| if err != nil { | ||
| return "", err | ||
| } | ||
| return servers[idx].ID, nil | ||
| } | ||
|
|
||
| func runExec(f *cmdutil.Factory, opts *Options, remoteCmd string) error { | ||
| ctx := context.Background() | ||
|
|
||
| if opts.id == "" { | ||
| if !f.Interactive { | ||
| return fmt.Errorf("--id is required") | ||
| } | ||
| id, err := selectServer(ctx, f) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| opts.id = id | ||
| } | ||
|
|
||
| server, err := f.ApiClient.GetServer(ctx, opts.id) | ||
| if err != nil { | ||
| return fmt.Errorf("get server failed: %w", err) | ||
| } | ||
|
|
||
| username := "root" | ||
| if server.SSHUsername != nil && *server.SSHUsername != "" { | ||
| username = *server.SSHUsername | ||
| } | ||
|
|
||
| var auth []ssh.AuthMethod | ||
| if server.IsManaged { | ||
| pw, err := f.ApiClient.RevealServerPassword(ctx, opts.id) | ||
| if err != nil { | ||
| // Don't swallow an API/authorization failure as "no password" — that | ||
| // hides the real cause. Only an actually-empty password is unavailable. | ||
| return fmt.Errorf("reveal server password failed: %w", err) | ||
| } | ||
| if pw != "" { | ||
| auth = append(auth, ssh.Password(pw)) | ||
| } | ||
| } | ||
| if len(auth) == 0 { | ||
| return fmt.Errorf( | ||
| "no password available for server %s; `server exec` uses password auth for managed servers — for key-based access use `zeabur server ssh`", | ||
| opts.id, | ||
| ) | ||
| } | ||
|
|
||
| config := &ssh.ClientConfig{ | ||
| User: username, | ||
| Auth: auth, | ||
| // Equivalent to `-o StrictHostKeyChecking=no`: dedicated servers are | ||
| // reached by IP with rotating host keys, so pinning would only wedge. | ||
| HostKeyCallback: ssh.InsecureIgnoreHostKey(), | ||
Check failureCode scanning / CodeQL Use of insecure HostKeyCallback implementation High
Configuring SSH ClientConfig with insecure HostKeyCallback implementation from
this source Error loading related location Loading |
||
|
|
||
| Timeout: 15 * time.Second, | ||
| } | ||
| addr := fmt.Sprintf("%s:%d", server.IP, server.SSHPort) | ||
|
|
||
| f.Log.Infof("Connecting to %s@%s ...", username, addr) | ||
|
|
||
| client, err := ssh.Dial("tcp", addr, config) | ||
| if err != nil { | ||
| return fmt.Errorf("ssh connection failed: %w", err) | ||
| } | ||
| defer client.Close() | ||
|
|
||
| session, err := client.NewSession() | ||
| if err != nil { | ||
| return fmt.Errorf("ssh session failed: %w", err) | ||
| } | ||
| defer session.Close() | ||
|
|
||
| // Stream output live (long output like `kubectl logs` shouldn't buffer). | ||
| // Stdin is intentionally left unset: exec is non-interactive, so the remote | ||
| // command sees EOF immediately — attaching a TTY stdin here could hang. | ||
| session.Stdout = os.Stdout | ||
| session.Stderr = os.Stderr | ||
|
|
||
| runErr := session.Run(remoteCmd) | ||
| if runErr != nil { | ||
| // Propagate the remote command's exit code as the CLI's exit code. | ||
| var exitErr *ssh.ExitError | ||
| if errors.As(runErr, &exitErr) { | ||
| session.Close() | ||
| client.Close() | ||
| os.Exit(exitErr.ExitStatus()) | ||
| } | ||
| return fmt.Errorf("command execution failed: %w", runErr) | ||
| } | ||
|
|
||
| return nil | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.