15

Is it possible to run a command

  • with parameters first of which starts with - (dash) e.g. /usr/bin/echo -n foo
  • as different user and group, for example apache:apache
  • using command su
  • when login shell is set to /sbin/nologin ?

I tried:

  • su -s "/usr/bin/echo" -g apache apache -n foo
    • fails with su: invalid option -- 'n'. It looks like first argument may not start with dash.
  • su -c "/usr/bin/echo -n foo" -g apache apache
    • fails with nologin: invalid option -- 'c'. It looks like -c can't be used if login shell is /sbin/nologin

3 Answers 3

30

sudo to the rescue!

sudo -u <user> -g <group> -- echo -n foo
30
su -s /bin/bash -c "/usr/bin/echo -n foo" -g apache apache
  • -s /bin/bash overrides nologin and allows to interpret value of -c option
  • -c "/usr/bin/echo -n foo" allows to avoid using dash-starting first argument
1
  • 2
    su in CentOS 6 doesn't support -g <group> option. This option is supported in CentOS 7 and 8. Commented Feb 19, 2020 at 18:28
4

If the user's login shell is set to /sbin/nologin then the user can't login and su - generally won't work.

But there is the su -m option to preserve the current user's environment and login shell:

su -m <user> -c "<command>"

For example:

su -m apache -c "echo hello; id"

Prints:

hello
uid=33(apache) gid=33(apache) groups=33(apache)

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.