1828185 Members
2610 Online
109975 Solutions
New Discussion

Re: Scripting

 
SOLVED
Go to solution
dctw
Frequent Advisor

Scripting

Hi, I want to write a script which needs to run some commands as a different user.

Is there a way to write the script without having to manually SU to another user first?
9 REPLIES 9
MarkSyder
Honored Contributor
Solution

Re: Scripting

I've never tried this, but the first thing I would try is to put a line in the script:

su - username -c command

substituting username and command as appropriate. Please let us know if it works.

Mark Syder (like the drink but spelt different)
The triumph of evil requires only that good men do nothing
dctw
Frequent Advisor

Re: Scripting

What if I want to run a series of commands ?
dctw
Frequent Advisor

Re: Scripting

It didn't work. I'm SU from root. It asks me for login credentials.
MarkSyder
Honored Contributor

Re: Scripting

But are you running the script as root? What is the ownership of the script?

If my suggestion worked, you would need a separate su line for each command.

Mark
The triumph of evil requires only that good men do nothing
Hemmetter
Esteemed Contributor

Re: Scripting

Hi dctw,

The same way you manually SU to another user you can do SU inside a script:

su - $OTHER -c "cmd"
But you will be prompted for a password if you are NOT "root" while executing the script.

Better may be to install "sudo" and configure user-A to be allowed to execute some cmds as user-B without password.

sudo -u $OTHER "cmd"

rgds
HGH
dctw
Frequent Advisor

Re: Scripting

Ah... after some modification.. it's fine now...

Thank you so much.

So how do I run a series of commands as a diffferent user?
MarkSyder
Honored Contributor

Re: Scripting

How many commands are in a series? If two or three, do a line with su for each. If more than this, it may be worth putting them in a separate script and making your main script run that on the line with su.

Mark
The triumph of evil requires only that good men do nothing
Dennis Handly
Acclaimed Contributor

Re: Scripting

>So how do I run a series of commands as a different user?

Either use a script as Mark suggested or you can use ";" to separate commands. Or you can use newlines:
su - $OTHER -c "cmd1
cmd2
cmd3"
dctw
Frequent Advisor

Re: Scripting

su - user -c command

Thank you guys so much for the help.