Scenario / Questions
What’s a good way of running a shell script as a different user. I’m using Debian etch, and I know which user I want to impersonate.
If I was doing it manually, I would do:
su postgres ./backup_db.sh /tmp/test exit
Since I want to automate the process, I need a way to run backup_db.sh as postgres (inheriting the environment, etc)
Find below all possible solutions or suggestions for the above questions..
To run your script as another user as one command, run:
/bin/su -c "/path/to/backup_db.sh /tmp/test" - postgres Breaking it down: /bin/su : switch user -c "/path/to..." : command to run - : option to su, make it a login session (source profile for the user) postgres : user to become
I recommend always using full paths in scripts like this – you can’t always guarantee that you’ll be in the right directory when you su (maybe someone changed the homedir on you, who knows). I also always use the full path to su (/bin/su) because I’m paranoid. It’s possible someone can edit your path and cause you to use a compromised version of su.
If the target user to run has nologin shelll defined, then you can use the -s option to specify the shell:
/bin/su -s /bin/bash -c '/path/to/your/script' testuser
See the following question:
run script as user who has nologin shell
To automate this on a schedule you could put it in the user’s crontab. Cron jobs won’t get the full environment though, but it it might be better to put all the env variables you need in the script itself anyways.
To edit the user’s crontab:
sudo crontab -u postgres -e
This should be an informative read — setuid on shell scripts
If you run su with a “
- username” argument sequence, it will make a login shell for the user to give the same environment as the user. Usually, used to quickly execute your script with your home environment from a different login.
Try the su manpage:
su -c script_run_as_postgres.sh – postgres
Alernately, you could use sudo to allow you to run just that comman as postgres without a password. It takes some setup in your /etc/sudoers, though.
The “su -c … ” method posted by others is a good one. For automation, you could add the script to the crontab of the user you need it to execute as.
If the user already has an entry to sudo and you don’t know superuser’s password then you can try following: This one restarts the postgres initialized at /data/my-db/pgsql/9.6/data
sudo su - postgres -c "/usr/pgsql-9.6/bin/pg_ctl -D /data/my-db/pgsql/9.6/data -l /var/log/pgsql.log restart"
You can also use:
sudo -u postgres script_run_as_postgres.sh
Disclaimer: This has been sourced from a third party syndicated feed through internet. We are not responsibility or liability for its dependability, trustworthiness, reliability and data of the text. We reserves the sole right to alter, delete or remove (without notice) the content in its absolute discretion for any reason whatsoever.