Wednesday, 27 February 2019

linux - How to start an interactive bash with su


I do not have sudo su over a username, however I have its password. I want to have an script that passes the password and gives me an interactive bash.


I have tried this:


echo mypassword | su - otherusr
Password: Last login: Wed Jul 25 12:09:38 COT 2018
[myuser@myserver ~]$

It returns me to myuser and I do not have an interactive bash with the other user.


I tried also:


echo mypassword | su -c "/bin/bash" - otherusr
echo mypassword | su -s "/bin/bash" - otherusr
echo mypassword | su -c "/bin/bash -i" - otherusr
Password: bash: cannot set terminal process group (-1): Inappropriate ioctl for device
bash: no job control in this shell
bash-4.2$ exit

How can I do that? I want to create an script that returns me an interactive bash session with another user; not just execute a command with another user.



Answer



By default neither sudo nor su reads a password from stdin. They try to use a terminal device directly (some implementations may even complain when used in a pipe). There is sudo -S option to change this behavior, but as far as I know there is no similar option for su.


Solution: use expect.



expect is a program that "talks" to other interactive programs according to a script. Following the script, expect knows what can be expected from a program and what the correct response should be.


[…]


In general, expect is useful for running any program which requires interaction between the program and the user. All that is necessary is that the interaction can be characterized programmatically.



In your case the script may be:


#!/usr/bin/expect 

log_user 0
spawn /bin/su - otherusr
expect "Password: "
send "mypassword\n"
interact

I advise to make this script accessible only to you (chmod go-rwx). Other users shouldn't be allowed to read it because it contains mypassword in plaintext; they shouldn't be allowed to run it, because it gives access to otherusr's shell.


No comments:

Post a Comment

How can I VLOOKUP in multiple Excel documents?

I am trying to VLOOKUP reference data with around 400 seperate Excel files. Is it possible to do this in a quick way rather than doing it m...