I need to make a bash script to swith from user 1 to user 2 at system start up in linux and run the script to execute a command. I want this all happens without asking me the password of user 2.. Just to turn on the pc and login with usr 1 and everthing then run automatically.
Asked
Active
Viewed 1,172 times
1
-
do you have root access to machine, or access to the other account, you can add your ssh key to other user account and run the command over ssh@localhost as that other user, if you have access to other account. Also this question is more suited for https://unix.stackexchange.com – ralz Dec 21 '18 at 13:01
-
1If the script runs as root, you can use `sudo -u user2 ...` to run anything as `user2` without a password. If the script is *not* run as root, then you need to configure `sudo` to allow `user1` to run some command as user2 without a password. – chepner Dec 21 '18 at 13:01
-
PC? ... maybe you should elaborate a little. – Paul Hodges Dec 21 '18 at 15:39
3 Answers
1
Using sudo command, add the following to your sudoers file (using visudo command) :
user1 ALL=(user2) NOPASSWD: ALL
This allows the user user1 to run any command with the identity user2 using sudo command and without any password authentication. For instance :
user1$ sudo -u user2 whoami
user2
You can reduce the set of commands by listing the allowed commands instead of the "ALL" keyword in sudoers :
user1 ALL=(user2) NOPASSWD: /usr/bin/whoami, /bin/ls

K.Hacene
- 125
- 4
0
You need the script itself to dynamically switch users and run commands?
Store those commands in another script and run that as user2.
echo "command1; command2; etc;">/tmp/file2run
sudo -u user2 bash /tmp/file2run

Paul Hodges
- 13,382
- 1
- 17
- 36
-
Thanks, But how to schedule running the script with every computer restart – mahmoud youssef Dec 22 '18 at 10:39
-
If it's booting up a bash profile, you can call it in the user's ~/.bash_profile. If you want it on *every* bootup, [see this page for some examples](https://stackoverflow.com/questions/12973777/how-to-run-a-shell-script-at-startup). – Paul Hodges Dec 24 '18 at 14:23
0
You can achieve this using here document as well
su user1 - <<END
id
## Do some user1 related activities
END
su user2 - << END
id
## Do some user2 related activities
END
su user1 - <<END
id
## continue user1 related activities
END
if user1 can access user2 without password, then you can put user2 here doc inside user1 here doc and make sure to use different delimiter if you are using nested here doc approach.

k_vishwanath
- 1,326
- 2
- 20
- 28