Pages

Sunday, December 7, 2014

How to su with a here doc


Not sure why, but it took me ages to work out the correct syntax to run su with  a shell and a here document.

Turns out the correct syntax, or at least syntax that seems to work, is:

su - <user> -c /bin/bash <<-'EOF'
<some commands...>
EOF

Now this assumes we're running as root, else you'd need to enter a password.
EOF in the above example is just a delimter user to indicate where the here doc ends , it can be more or less any string, but I'd keep it alpha to keep things simple, i.e. avoid punctuation and the like.

e.g.

[root@clivm ~]# cat test.sh
#!/bin/sh

#run the 'id' command to show we're running as root
id
su - fred -c /bin/bash <<-'MEH'
#now run id to show we're runnning as fred and some echos 
#to show where the user 'fred' session starts and ends
# fred's session starts and ends
echo "---running as ${USER}--"
id
echo "now I am fred:"
echo
echo "---about to hit the end delimiter and exit ${USER}'s context"
MEH
# show that we have left fred's context and are running as  root again
id
echo "---running as ${USER}--"

The above example uses MEH as the delimiter.
When run as root it looks like this:
The bold section is executing as user fred.

[root@clivm ~]# sh test.sh
uid=0(root) gid=0(root) groups=0(root) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
---running as fred--
uid=500(fred) gid=500(fred) groups=500(fred) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
now I am fred:

---about to hit the end delimiter and exit fred's context
uid=0(root) gid=0(root) groups=0(root) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
---running as root--
[root@clivm ~]#


No comments:

Post a Comment