Skip to content

Commit e2ddfae

Browse files
authored
Merge pull request #5147 from Aneesh-Hegde/copy-to-host-conditional-sudo
refactor: make sudo optional for copyToHost
2 parents 9a3f1c4 + 411f2dc commit e2ddfae

1 file changed

Lines changed: 18 additions & 5 deletions

File tree

pkg/hostagent/hostagent.go

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1230,10 +1230,7 @@ func copyToHost(ctx context.Context, sshConfig *ssh.SSHConfig, sshAddress string
12301230
"-p", strconv.Itoa(sshPort),
12311231
sshAddress,
12321232
"--",
1233-
)
1234-
args = append(args,
1235-
"sudo",
1236-
"cat",
1233+
"env", "LANG=C", "LC_ALL=C", "cat",
12371234
remote,
12381235
)
12391236
logrus.Infof("Copying config from %s to %s", remote, local)
@@ -1243,7 +1240,23 @@ func copyToHost(ctx context.Context, sshConfig *ssh.SSHConfig, sshAddress string
12431240
cmd := exec.CommandContext(ctx, sshConfig.Binary(), args...)
12441241
out, err := cmd.Output()
12451242
if err != nil {
1246-
return fmt.Errorf("failed to run %v: %#q: %w", cmd.Args, string(out), err)
1243+
var exitErr *exec.ExitError
1244+
if errors.As(err, &exitErr) && strings.Contains(string(exitErr.Stderr), "Permission denied") {
1245+
logrus.Infof("Retrying %s with sudo (permission denied)", remote)
1246+
sudoArgs := sshConfig.Args()
1247+
sudoArgs = append(sudoArgs,
1248+
"-p", strconv.Itoa(sshPort),
1249+
sshAddress,
1250+
"--",
1251+
"sudo", "cat",
1252+
remote,
1253+
)
1254+
cmd = exec.CommandContext(ctx, sshConfig.Binary(), sudoArgs...)
1255+
out, err = cmd.Output()
1256+
}
1257+
if err != nil {
1258+
return fmt.Errorf("failed to run %v: %#q: %w", cmd.Args, string(out), err)
1259+
}
12471260
}
12481261
if err := os.WriteFile(local, out, 0o600); err != nil {
12491262
return fmt.Errorf("can't write to local file %#q: %w", local, err)

0 commit comments

Comments
 (0)