Skip to content

Commit

Permalink
Extend util public interface to run command as specified user
Browse files Browse the repository at this point in the history
  • Loading branch information
sfc-gh-ikryvanos committed Nov 29, 2024
1 parent 50d5542 commit c69a033
Showing 1 changed file with 43 additions and 1 deletion.
44 changes: 43 additions & 1 deletion services/exec/client/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,27 @@ func ExecRemoteCommand(ctx context.Context, conn *proxy.Conn, binary string, arg
return result[0].Resp, nil
}

// ExecRemoteCommand is a helper function for execing a command on one or remote hosts
// ExecRemoteCommandAs is a helper function for execing a command on a remote host as specified user
// using a proxy.Conn. If the conn is defined for >1 targets this will return an error.
func ExecRemoteCommandAs(ctx context.Context, conn *proxy.Conn, user string, binary string, args ...string) (*pb.ExecResponse, error) {
if len(conn.Targets) != 1 {
return nil, errors.New("ExecRemoteCommand only supports single targets")
}

result, err := ExecRemoteCommandManyAs(ctx, conn, user, binary, args...)
if err != nil {
return nil, err
}
if len(result) < 1 {
return nil, fmt.Errorf("ExecRemoteCommand error: received empty response")
}
if result[0].Error != nil {
return nil, fmt.Errorf("ExecRemoteCommand error: %v", result[0].Error)
}
return result[0].Resp, nil
}

// ExecRemoteCommandMany is a helper function for execing a command on one or remote hosts
// using a proxy.Conn.
// `binary` refers to the absolute path of the binary file on the remote host.
func ExecRemoteCommandMany(ctx context.Context, conn *proxy.Conn, binary string, args ...string) ([]*pb.RunManyResponse, error) {
Expand All @@ -65,3 +85,25 @@ func ExecRemoteCommandMany(ctx context.Context, conn *proxy.Conn, binary string,

return result, nil
}

// ExecRemoteCommandManyAs is a helper function for execing a command on one or remote hosts as specified user
// using a proxy.Conn.
// `binary` refers to the absolute path of the binary file on the remote host.
func ExecRemoteCommandManyAs(ctx context.Context, conn *proxy.Conn, user string, binary string, args ...string) ([]*pb.RunManyResponse, error) {
c := pb.NewExecClientProxy(conn)
req := &pb.ExecRequest{
User: user,
Command: binary,
Args: args,
}
respChan, err := c.RunOneMany(ctx, req)
if err != nil {
return nil, err
}
result := make([]*pb.RunManyResponse, len(conn.Targets))
for r := range respChan {
result[r.Index] = r
}

return result, nil
}

0 comments on commit c69a033

Please sign in to comment.