Bash script : Login to postgres home from shell script - bash

I have to take a data dump from my postgres database.
How do I log in to the postgres home ? . I have the following script but it doesn't work :
#!/bin/sh$
export PASSWORD= something
echo $PASSWORD | sudo -S su postgres
pg_dump somedb > dump.txt+`date +%Y-%m-%d`
However when I run this script I do not get logged to postgres#gauss:$ at the same time script doesn't throw an error. Is there something I am doing wrong here ?

The reason your script fails is that the line
echo $PASSWORD | sudo -S su postgres
causes su to fork a subordinate shell. That shell tries to read from the standard input which has already been exhausted by sudo -S in reading the password. When the shell finds no more input (EOF) it exits. The next line of your script then executes as if that quoted line never happened, and therefore runs under your UID.
See j.hloetzek's answer for a much better way to do what you want.
Also the script as pasted has a two syntax errors in it, but you shouldn't use that approach anyway.

You cannot pipe the password to the sudo command, but can allow in /etc/sudoers certain commands to be run without password (check exact syntax!)
username YOURUSERNAME = NOPASSWD: /sbin/su postgres

Related

How to ssh/sudo su - oracle/run some commands

I have already looked at the following links but didn't managed to make it work:
SSH to server, Sudo su - then run commands in bash
Can I ssh somewhere, run some commands, and then leave myself a prompt?
Run ssh and immediately execute command
I'm trying to automate the following sequence to log in to the database
$ ssh <myserver>
me#myserver$ sudo su - oracle
<enter password>
oracle#myserver$ bash
oracle#myserver$ export ORAENV_ASK=NO
oracle#myserver$ export ORACLE_SID=ORACLEDB
oracle#myserver$ . oraenv
oracle#myserver$ echo $ORACLE_HOME
I tried the command (based on the links above) but that does not work :
ssh -t myserver "echo password | sudo -S su - oracle ; bash ; export ORAENV_ASK=NO"
How can I combine thoses commands in a shell script (or even perl one), execute it and then leave myself at a prompt so I can run sqlplus after? Is that even possible?
Note:
ssh does not need password because we use authorized_keys, BUT Password-less sudo is not an option nor using su directly (I'm not root and cannot change that), the command needs to be "sudo su - oracle" exactly.
Thanks
You can't do that in shell, but you can do it with expect (apt-get install expect if on Debian variants).
This is a very simple expect file. You need to do some research to make it work in your environment but this gives the general idea.
spawn ssh foo#x.x.x.x
expect "~$"
send "sudo bash\r"
expect {
password {send "foobar\r";exp_continue}
"#"
}
send "id\r"
expect "root"
You would run this as expect /path/to/your/expectfile.
This will log in, do sudo with password "foobar", execute id and exit. Would this be of any help?
Hannu

Run sudo as specific user without password

I used the following command in my script
sudo su - user -c bash <<EOF
cp /home/test.txt /opt/
EOF
If I use the sudo su - user on terminal, Unix don't ask me the Password but if I try to run the script the terminal ask me the Password and if I delete the EOF part the rest of code run when I quit the session.
I want to run the command in user mode sudo but the terminal don't Need ask me the Password.
If I use
sudo su - user <<EOF
code
EOF
I have an error in .bash_profile: too many argument
I want to run the command in user mode sudo but the terminal don't
Need ask me the Password.
The scenario you are experiencing is caused by the users cached credentials for sudo, which allow sudo to maintain a session and any further sudo command will not prompt for passwords.
Check this:
Open a new terminal and run sudo whatever, then close it and open another new terminal and run sudo whatever, you will see that sudo asks for password every time...
If you still need to do that, then you have the following options:
Prevent sudo to ask for password permanently:
run sudo visudo and look for the line root ALL=(ALL) ALL, then add a line
username ALL=(ALL) NOPASSWD: ALL
then save and exit.
Note: This is a security risk
Or Prevent sudo to ask for password permanently only for specific script:
run sudo visudo and look for the line root ALL=(ALL) ALL, then add a line
username ALL=NOPASSWD: path_to_the_script
then save and exit
Provide password inside the script, by running your sudo command like this:
sudo -S <<< "password" command
Note: This is a security risk too.
I guess you need to execute your command as a different user. This might be your answer: Run a shell script as another user that has no password
sudo -H -u otheruser bash -c 'echo "I am $USER, with uid $UID"'
It is a quote from the link. Probably the following is better for you:
sudo -H -u otheruser bash <<EOF
cp /home/test.txt /opt/
EOF
UPDATE: You may wish to create a specific sudo rule to run a specific command without password (inside /etc/sudoers file -remember to use visudo to edit it-):
otheruser ALL=NOPASSWD: /full/path/to/your_command.sh
(of course you need root access to edit sudoers, I hope you can do it).
And create the script called your_command.sh that contains your logic. You'll then be allowed to run it without password:
sudo -H -u otheruser your_command.sh
I know, it's not a "single line command" but it is safe as it allows only one specific command without password. And it doesn't require a password, of course!
Then don't use sudo, then it won't ask for password, but you will to be have logged in as root!

How do I run a shell script with administrator privileges through AppleScript without prompting for a password?

I want to have my AppleScript application run a Python script with sudo, but I don't want the application to prompt the user for a password (our users do not have sudo privileges).
The Python script has been added to the /etc/sudoers file appropriately (ALL ALL=NOPASSWD: /path/to/script.py). In the terminal, I can do (as a regular, non-privileged user):
$ sudo ./script.py
and it runs perfectly well. But in AppleScript when you try to do:
do shell script "sudo ./script.py"
You of course get the "sudo: no tty present and no askpass program specified" error. But if you change it to:
do shell script "./script.py" with administrator privileges
AppleScript insists on presenting a popup window to ask for the password. I have also tried passing a null password to sudo with a pipe:
do shell script "echo '' | sudo -S ./script.py"
but that also does not work. (I think it tries to run sudo individually first and then pass the command through, which won't work because the user doesn't have sudo privileges!)
I need a solution where AppleScript will run the Python script with sudo. I would prefer the script stays unreadable and un-executable by average users for security reasons, and is only executed through the AppleScript. (I know that, hypothetically, the users could call sudo script.py and it would run, but that's assuming they even know about sudoers; I'm trying to keep it as secure as possible while still usable).
I'm still pretty new to AppleScript, so any help would be greatly appreciated! Thanks!
When I added ALL ALL=NOPASSWD: /Users/myusername/a to sudoers and ran echo $'#!/bin/bash\nsay $(ls ~root|head -n1)'>~/a;chmod +x ~/a, do shell script "sudo ~/a" ran the script as root without requiring a password.
I'm guessing the problem is that you specified the path like do shell script "sudo ./script.py". Try to use do shell script "sudo ~/script.py" instead. The default working directory is for do shell script is / and not ~/.

Changing to root user inside shell script

I have a shell script which needs non-root user account to run certain commands and then change the user to root to run the rest of the script. I am using SUSE11.
I have used expect to automate the password prompt. But when I use
spawn su -
and the command gets executed, the prompt comes back with root and the rest of the script does not execute.
Eg.
< non-root commands>
spawn su -
<root commands>
But after su - the prompt returns back with user as root.
How to execute the remaining of the script.
The sudo -S option does not help as it does not run sudo -S ifconfig command which I need to find the IP address of the machine.
I have already gone through these links but could not find a solution:
Change script directory to user's homedir in a shell script
Changing unix user in a shell script
sudo will work here but you need to change your script a little bit:
$ cat 1.sh
id
sudo -s <<EOF
echo Now i am root
id
echo "yes!"
EOF
$ bash 1.sh
uid=1000(igor) gid=1000(igor) groups=1000(igor),29(audio),44(video),124(fuse)
Now i am root
uid=0(root) gid=0(root) groups=0(root)
yes!
You need to run your command in <<EOF block and give the block to sudo.
If you want, you can use su, of course. But you need to run it using expect/pexpect that will enter password for you.
But even in case you could manage to enter the password automatically (or switch it off) this construction would not work:
user-command
su
root-command
In this case root-command will be executed with user, not with root privileges, because it will be executed after su will be finished (su opens a new shell, not changes uid of the current shell). You can use the same trick here of course:
su -c 'sh -s' <<EOF
# list of root commands
EOF
But now you have the same as with sudo.
There is an easy way to do it without a second script. Just put this at the start of your file:
if [ "$(whoami)" != "root" ]
then
sudo su -s "$0"
exit
fi
Then it will automatically run itself as root. Of course, this assumes that you can sudo su without having to provide a password - but that's out of scope of this answer; see one of the other questions about using sudo in shell scripts for how to do that.
Short version: create a block to enclose all commands to be run as root.
For example, I created a script to run a command from a root subdirectory, the segment goes like this:
sudo su - <<EOF
cd rootSubFolder/subfolder
./commandtoRun
EOF
Also, note that if you are changing to "root" user inside a shell script like below one, few Linux utilities like awk for data extraction or defining even a simple shell variable etc will behave weirdly.
To resolve this simply quote the whole document by using <<'EOF' in place of EOF.
sudo -i <<'EOF'
ls
echo "I am root now"
EOF
The easiest way to do that would be to create a least two scripts.
The first one should call the second one with root privileges. So every command you execute in the second script would be executed as root.
For example:
runasroot.sh
sudo su-c'./scriptname.sh'
scriptname.sh
apt-get install mysql-server-5.5
or whatever you need.

Running interactive shell script in name of other user

In my shell script (bash) I want to call other shell scripts. I run my script as user_A.
One of these scripts needs special handling:
It has to be run as different user
(user_B). Password needed here.
It is interactive, but not only asks
questions but runs another script in
name of another user (user_C) using
su. I have to enter a password here
as well.
I can use su calling this script but its questions have to be answered somehow. I can not enter anything because it prints for each questons "stty: : Not a typewriter"
I'm calling the special script this way
su user_B << ABC
...
special_script
...
ABC
#!/bin/bash
main_for_root(){
:
}
# ------------------------------------------------------------------------------
abs_path="$(readlink -f `dirname $0`)/$(basename $0)"
# if [ `id -u` != 0 ] ; then
if [ `whoami` != 'root' ] ; then
echo "[su -] run as root"
su -c"/bin/bash $abs_path $#"
exit 0
else
main_for_root $#
fi
It works for 1 user, so now add 'if ...' for second user
Another option for running scripts as other users is the 'sudo' command, think of it as 'superuser do:' for readability purposes. The -u parameter gives username information. So:
sudo -u user_B special_script
Will prompt for the password for user_B. I've never had a problem with running interactive programs using it. You can manage who can sudo to whom via the visudo command.
You can use sudo and create a sudoers file which allows user_A to run the script as user_B.
a line like:
user_A ALL = (user_B) NOPASSWD: /usr/share/stuff/ABC
would allow user_A to do something like
sudo -u user_B /usr/share/stuff/ABC
without asking for a password
su attempts to get a password from the terminal and needs a tty device so it can call ioctl to turn off key echoing. Since the standard input is coming from a "here document" (ABC), an attempt to call the ioctl on file descriptor 0 yields "not a tty".
If you must use a here document instead of a bona fide script, do:
cat > /tmp/myscript.$$ <<ABC
#!/bin/sh
...
ABC
chmod +x /tmp/myscript.$$
sudo -u user_B /tmp/myscript.$$
You may want to use expect. Its designed for scripted interaction.

Resources