Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to use su in a shell script? 2

Status
Not open for further replies.

InigoMontoya

IS-IT--Management
Jun 18, 2003
51
US
I have a script that needs to run commands under different users. I thought all I had to do was...
as root...

su - $username0
command
command
exit

su - $username1
command
command
exit

instead of running the scripts inside the new shell it waits until the shell exits then the commands execute.
I need them to execute inside the new shell. Please help...TIA.
 
use a here document...

su - $username0 <<EOF
command
command
exit
EOF
 
You can also use the -c flag: eg. su - $username0 -c &quot;command;command&quot;
 
Thanks! both worked. I will use the -c flag since it's similar to expect's -c flag. Can this be done in expect as well? I've tried spawning a su - $username but the same result. It would wait until the session is closed then continue with the commands.
 
Using expect with su is very simple.

Code:
set rootprompt &quot;root@.*&quot;
spawn su

     expect {
            -re &quot;.*assw.*&quot; {
             send_user &quot;Need password: &quot;
             set pw [gets stdin]
             send &quot;$pw\r&quot;
             expect -re &quot;$rootprompt&quot; {
                         send_user &quot;Logged in as root\n&quot;
                         send_user &quot;Type \&quot;quit\&quot; to quit\n&quot;
                         interact {
                               &quot;quit&quot; {close $id ; wait}
                         }
              }
              eof {send_user &quot;SU failed\n&quot;}
              timeout {send_user &quot;Timed out!!\n&quot;}
     }

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top