1

I know questions similar to this have been asked, but I haven't seen this exact situation answered (though feel free to close if it is indeed a duplicate).

I am on a corporate network, so I do not have access to modify the /etc/sudoers file.

We use sudo -u svc_produser -i to switch users into an interactive shell. Each time, this prompts me for my password. I would like a way of automating passing in my password, and, if possible, immediately running commands when logged in as the service user.

I can't pipe the password in, because -i doesn't work with -S (--stdin).

At previous companies, I have achieved this with expect scripts, but I don't have that at my disposal either.

I do have Python available, but I'm hoping there's a simple Bash-y way to achieve this.

1
  • "I do not have access to modify the /etc/sudoers" - then speak to someone who does. There are lots of dumb ways to solve this problem which will violate the intention of the sudo configuration on your site.
    – symcbean
    Commented Oct 16, 2023 at 16:53

1 Answer 1

2

Yes, you can do this using the askpass option. From man sudo:

-A, --askpass

Normally, if sudo requires a password, it will read it from the user's terminal. If the -A (askpass) option is specified, a (possibly graphical) helper program is executed to read the user's password and output the password to the standard output. If the SUDO_ASKPASS environment variable is set, it specifies the path to the helper program.

So, in its simplest form, you can write a script that prints out your password:

$ cat ~/scripts/foo.sh
#!/bin/sh
printf '%s\n' this_is_my_password

You then set the SUDO_ASKPASS variable to point to it:

export SUDO_ASKPASS=/home/terdon/scripts/foo.sh

And then you run

sudo -A -u svc_produser -i 

for an interactive shell, and if you just want to run a command, you do

sudo -A -u svc_produser command

For example, on my system:

$ sudo -A whoami
root

Now, this is obviously horribly insecure. You can make it slightly better by creating a file that is only readable by you and storing your password there:

$ printf 'this_is_my_password\n' > ~/.hidden_file
$ chmod 600 ~/.hidden_file

Better, don't use printf but instead open an editor window and write the password since the printf approach above will have the password appearing in plaintext in your history. Even better, store this in an encrypted volume that is only decrypted on boot. There are various tweaks and improvements you can do to make this a little safer.

1
  • Ok, I had the variable named wrong, but it's working now! I usually store passwords for this kind of thing in my .ssh dir, so I think this will work. Thank you!
    – bdetweiler
    Commented Oct 16, 2023 at 18:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .