MCPcopy Create free account
hub / github.com/DBCDK/morph / SudoCmdContext

Method SudoCmdContext

ssh/ssh.go:128–183  ·  view source on GitHub ↗
(ctx context.Context, host Host, parts ...string)

Source from the content-addressed store, hash-verified

126}
127
128func (sshCtx *SSHContext) SudoCmdContext(ctx context.Context, host Host, parts ...string) (*exec.Cmd, error) {
129 var err error
130 if parts, err = valCommand(parts); err != nil {
131 return nil, err
132 }
133
134 // ask for password if not done already
135 if sshCtx.AskForSudoPassword && sshCtx.sudoPassword == "" {
136 sshCtx.sudoPassword, err = askForSudoPassword()
137 if err != nil {
138 return nil, err
139 }
140 } else if sshCtx.GetSudoPasswordCommand != "" {
141 command := strings.Fields(sshCtx.GetSudoPasswordCommand)
142 var argsArr = []string{}
143 for i, e := range command {
144 if i != 0 {
145 argsArr = append(argsArr, e)
146 }
147 }
148 passCmd := exec.Command(command[0], argsArr...)
149
150 passOut, err := passCmd.Output()
151 if err != nil {
152 panic(err)
153 }
154 sshCtx.sudoPassword = string(passOut)
155 }
156
157 cmd, cmdArgs := sshCtx.sshArgs(host, nil)
158
159 // normalize sudo
160 if parts[0] == "sudo" {
161 parts = parts[1:]
162 }
163 cmdArgs = append(cmdArgs, "sudo")
164
165 if sshCtx.sudoPassword != "" {
166 cmdArgs = append(cmdArgs, "-S")
167 } else {
168 // no password supplied; request non-interactive sudo, which will fail with an error if a password was required
169 cmdArgs = append(cmdArgs, "-n")
170 }
171
172 cmdArgs = append(cmdArgs, "-p", "''", "-k", "--")
173 cmdArgs = append(cmdArgs, parts...)
174
175 command := exec.CommandContext(ctx, cmd, cmdArgs...)
176 if sshCtx.sudoPassword != "" {
177 err := writeSudoPassword(command, sshCtx.sudoPassword)
178 if err != nil {
179 return nil, err
180 }
181 }
182 return command, nil
183}
184
185func valCommand(parts []string) ([]string, error) {

Callers 2

CmdContextMethod · 0.95
SudoCmdMethod · 0.95

Calls 4

sshArgsMethod · 0.95
valCommandFunction · 0.85
askForSudoPasswordFunction · 0.85
writeSudoPasswordFunction · 0.85

Tested by

no test coverage detected