Repository navigation
Expand file tree
/
Copy pathexec.go
More file actions
74 lines (65 loc) · 1.58 KB
/
Copy pathexec.go
File metadata and controls
74 lines (65 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package ssh
import (
"fmt"
"os"
"github.com/san-gg/mdeploy/pkg/ssh"
"github.com/san-gg/mdeploy/pkg/term"
"github.com/spf13/cobra"
)
type execOptions struct {
host string
user string
}
var execOpt execOptions
func ExecCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "exec COMMAND",
Short: "Execute commands on remote servers",
Long: "Run commands remotely and display their output.",
Args: cobra.MaximumNArgs(1),
RunE: execCmd,
}
flags := cmd.Flags()
flags.StringVarP(&execOpt.host, "host", "H", "", "server host")
flags.StringVarP(&execOpt.user, "user", "U", "", "username")
return cmd
}
func execCmd(cmd *cobra.Command, args []string) error {
trust, err := cmd.Flags().GetBool("trust")
if err != nil {
panic(err)
}
pwd, err := term.ReadPassword()
if err != nil {
fmt.Fprintln(os.Stderr, "failed to read password:", err)
return nil
}
sshsession, err := ssh.ConnectWithPassword(ssh.Options{
Server: execOpt.host,
Port: 22,
User: execOpt.user,
Password: string(pwd),
TrustServerHost: trust,
SftpConcurrency: false,
})
if err != nil {
fmt.Fprintln(os.Stderr, err)
return nil
}
defer sshsession.Close()
if err := sshExec(sshsession, args[0]); err != nil {
fmt.Fprintln(os.Stderr, "failed to execute command:", err)
return nil
}
return nil
}
func sshExec(sshsession ssh.SshSession, cmd string) (err error) {
err = sshsession.Exec(NewLineWriter{}, cmd)
return
}
type NewLineWriter struct{}
func (w NewLineWriter) Write(p []byte) (n int, err error) {
n = len(p)
fmt.Println(string(p))
return
}