SU command in non interactive mode

Can i run the SU command in a non interactive mode. What i want to do is to pass the username and the password as commandline or batch parameters. Please let me if its possible and how to pass them. A sample file will be appreciated.

Thanks,

Will you be typing the user/pass or having them sit in a file? I'd be cautious about leaving a user/pass sitting around. It would be easier to use sudo or RBAC to allow a given user to su.

You could use expect if the above won't do:

#!/usr/bin/expect --

set timeout -1

spawn /bin/su

expect "Password: "
send "mypasswd\r"

expect "\r\n"
send "mycommand\n"

Cheers,

Keith

This didn't work for me:

#!/usr/local/bin/expect --
set timeout -1
spawn /bin/su
expect "Password: "
send "btmRus99\r"
expect "\r\n "
send "/bin/echo Hello>>/tmp/readfil\n"

the response is:

spawn /bin/su
Password:
su: Sorry
send: invalid spawn id (4)
while executing
"send "/bin/echo Hello>>/tmp/readfil\n""
(file "exp" line 7)

If I didn't have a whitespace in expect "\r\n", the program ran but nothing being created in /tmp/readfil.

  • Zac

sorry the script should be:

#!/usr/local/bin/expect --
set timeout -1
spawn /bin/su - btmems
expect "Password: "
send "btmRus99\r"
expect "\r\n"
send "/bin/echo Hello>>/tmp/readfil\n"

where btmems is a user, btmRus99 a password.

I can't get that bit of code working on my system. I'm using a Linux based on SLES10. I have tried sending simply an "ls\r", but nothing happens and when the script finishes I'm logged back out.

Are there anymore suggestions to help this work?

Thanks.

Since you did not mention using su with a new username or ssh I am assuming:

A. you are not concerned with remote systems
B. you are referring to using 'su' to switch to the root user
C. you have the root password to do so

the simple solution here is sudo.

as root (use 'su' regularly the first time) issue the 'visudo' command to edit the '/etc/sudoers' file. Add a line like:

%wheel ALL=(ALL) NOPASSWD: ALL

visudo will open the file in vi/vim.

now add your user to the wheel group:

usermod -G <username>

where <username> is your username and NOT root.

now to su to root without a password simply type the command 'sudo su -' and to run a command as root without switching to root just type 'sudo <command of choice>'

cheers!