Accessing variables from another user scope in Bash - linux

I'm having trouble with the following bash script:
#!/bin/bash
myPassword="foobar"
su - postgres <<-'EOF'
echo $myPassword # nil
EOF
echo $myPassword # foobar
How can I access or pipe the contents of $myPassword from within the postgres user session?
Tried it with and without export with not luck.

You're using 'EOF' for the heredoc marker. So no substitution happens. Remove the quotes around that if you want variable substitution inside the block. See Heredocs And Herestrings.
You could also keep what you have, but use the -p (or -m or --preserve-environment) option of su which might work better for you.
(I'm sure there's no need to remind you that keeping passwords in scripts is unsafe. And a process's environment can be inspected with sufficient privileges, so it's not a great place for passwords either.)

you probably need to escape \$mypassword so that it doesn't get resolved in the original script before calling su
also, you can pass -c to su in order to pass something from the environment to the spawned shell:
user1:~$ X=foo su -c "bash -c \"whoami && echo \$X\"" user2
Password:
user2
foo

This su command should work:
myPassword="foobar"
su postgress -c "echo $myPassword"

Related

'su' by using 'script' in Docker returns different results compared to the standard environment

I need to request certain commands via su including password in one line.
I found a solution and it is working in a standard environment (Ubuntu) (more about solution here):
{ sleep 1; echo password; } | script -qc 'su -l user -c id' /dev/null | tail -n +2
But I am faced with the problem that this solution is not suitable in a Docker container environment
Script terminates the command without waiting for echo and as a result i get:
su: Authentication failure
Any help is much appreciated.
Passing the password for su via stdin is problematic for various reasons: the biggest one is probably that your password will end up in the history.
You could instead:
Call the entire script as the specific user and thus enter the password manually
Use sudo with the appropriate NOPASSWD sudoers configuration
In your case you are using docker, so you could just set the USER in your Dockerfile

Hide plaintext password from showing in bash script?

I have the following bash script to restart the network manager in Debian. The script works as is it should, but not as I would like it to. When the script asks for the sudo password I am able to pass it along using echo, but it displays the password in terminal while the script executes, making it less asthetically pleasing than I would like. Is there anyway to have the script enter the password, but not display the password text while the script calls for the sudo password?
I have tried as many suggestions on Stack Overflow as i could find, well as Stack Exchange before submitting this question.
Script is as follows:
#!/bin/bash
clear
echo "Restarting service Network Manager"
echo""
sleep 1
echo -e "\033[0;31m......................................\033[0m"
echo -e "\033[0;31m......................................\033[0m"
sleep 1
echo""
sudo service network-manager restart
sleep 2
echo <Password>
sleep 2
echo "Service Network Manager Restarted"
sleep 1
echo ""
echo "Relinquishing control of terminal to user..."
sleep 7
clear
Remove the echo <Password> line? I am pretty sure it does nothing other than display the password, as sudo apparently (through an appropriate entry in /etc/sudoers) works without you having to give a password. (What you write to terminal with echo does not get passed to any other process.)
Generally speaking, you can use sudo -S to make sudo expect the password on stdin. But also generally speaking, if you have to hardcode a password in a script, you're doing it wrong in some way.
Is there anyway to have the script enter the password
Putting password in script is not a good idea. First, from security point of view, password may be recovered from script from anyone with access to script. Second, from maintenance view, once you change your password, scripts suddenly stop working and you have to update them all.
Fortunately, as you are already using sudo there is better solution. You can configure sudo to allow running certain command without password, by using NOPASSWD rule in /etc/sudoers.
myuser ALL=(ALL) NOPASSWD: service network-manager restart
See:
How do I run specific sudo commands without a password?
How to run a specific program as root without a password prompt?
Warning: Always edit /etc/sudoers with visudo, never directly. It prevents you from breaking /etc/sudoers. Once you break your /etc/sudoers, you won't be able to use sudo, including using sudo to fix /etc/sudoers.
try this /bin/echo -e "password\n" | sudo apt-get update
or see this Use sudo with password as parameter

Linux set date&time via bash script

I'm trying to set a fake date via bash script
I'm using the following commands:
#!/bin/bash
echo 'myPass' | sudo -s 'date -s "1 NOV 2011 09:00:00"'
But I'm getting command error.
What is the right way to do it ?
sudo does not read the password from standard input by default, but from the terminal itself, so you cannot pipe your password into sudo this way. You need to use the -S option to read from standard input.
echo "myPass" | sudo -S date -s "1 NOV 2011 09:00:00"
(note that you don't need to use the -s (lowercase) option; sudo can run date directly without starting an intervening shell).
Exposing your password like this, however, is a security risk. It would be better to configure sudo to allow you (or anyone who is intended to run this script) to run
this particular date command without a password.
For sudo, the first parameter without a dash is the command to execute, the following parameters are the arguments to give to that command. If you wrap the command and its arguments together in quotes (e.g. "echo foo"), then sudo tries to execute the command "echo foo" instead of the command "echo" with parameter "foo". Hence, you need to omit the outermost quotes:
sudo date -s "1 NOV 2011 09:00:00"

How to get standard output from subshell?

I have a script like this?
command='scp xxx 192.168.1.23:/tmp'
su - nobody -c "$command"
The main shell didn't print any info.
How can I get output from the sub command?
You can get all of its output by just redirecting the corresponding output channel:
command='scp ... '
su - nobody -c "$command" > file
or
var=$(su - nobody -c "$command")
But if you don't see anything, maybe the diagnostics output of scp is disabled?
Is there a "-q" option somewhere in your real command?
You aren't actually running the scp. When you use the
VAR=value cmd ...
syntax, the VAR=value setting goes into the environment of cmd but it's not available in the current shell. The command after your -c is empty, or the previous value of $command if there was one.

Using the passwd command from within a shell script

I'm writing a shell script to automatically add a new user and update their password. I don't know how to get passwd to read from the shell script instead of interactively prompting me for the new password. My code is below.
adduser $1
passwd $1
$2
$2
from "man 1 passwd":
--stdin
This option is used to indicate that passwd should read the new
password from standard input, which can be a pipe.
So in your case
adduser "$1"
echo "$2" | passwd "$1" --stdin
[Update] a few issues were brought up in the comments:
Your passwd command may not have a --stdin option: use the chpasswd
utility instead, as suggested by ashawley.
If you use a shell other than bash, "echo" might not be a builtin command,
and the shell will call /bin/echo. This is insecure because the password
will show up in the process table and can be seen with tools like ps.
In this case, you should use another scripting language. Here is an example in Perl:
#!/usr/bin/perl -w
open my $pipe, '|chpasswd' or die "can't open pipe: $!";
print {$pipe} "$username:$password";
close $pipe
The only solution works on Ubuntu 12.04:
echo -e "new_password\nnew_password" | (passwd user)
But the second option only works when I change from:
echo "password:name" | chpasswd
To:
echo "user:password" | chpasswd
See explanations in original post: Changing password via a script
Nowadays, you can use this command:
echo "user:pass" | chpasswd
Read the wise words from:
http://mywiki.wooledge.org/BashFAQ/078
I quote:
Nothing you can do in bash can possibly work. passwd(1) does not read from standard input. This is intentional. It is for your protection. Passwords were never intended to be put into programs, or generated by programs. They were intended to be entered only by the fingers of an actual human being, with a functional brain, and never, ever written down anywhere.
Nonetheless, we get hordes of users asking how they can circumvent 35 years of Unix security.
It goes on to explain how you can set your shadow(5) password properly, and shows you the GNU-I-only-care-about-security-if-it-doesn't-make-me-think-too-much-way of abusing passwd(1).
Lastly, if you ARE going to use the silly GNU passwd(1) extension --stdin, do not pass the password putting it on the command line.
echo $mypassword | passwd --stdin # Eternal Sin.
echo "$mypassword" | passwd --stdin # Eternal Sin, but at least you remembered to quote your PE.
passwd --stdin <<< "$mypassword" # A little less insecure, still pretty insecure, though.
passwd --stdin < "passwordfile" # With a password file that was created with a secure `umask(1)`, a little bit secure.
The last is the best you can do with GNU passwd. Though I still wouldn't recommend it.
Putting the password on the command line means anyone with even the remotest hint of access to the box can be monitoring ps or such and steal the password. Even if you think your box is safe; it's something you should really get in the habit of avoiding at all cost (yes, even the cost of doing a bit more trouble getting the job done).
Here-document works if your passwd doesn't support --stdin and you don't want to (or can't) use chpasswd for some reason.
Example:
#!/usr/bin/env bash
username="user"
password="pass"
passwd ${username} << EOD
${password}
${password}
EOD
Tested under Arch Linux. This passwd is an element of shadow-utils and installed from the core/filesystem package, which you usually have by default since the package is required by core/base.
You could use chpasswd
echo $1:$2 | chpasswd
For those who need to 'run as root' remotely through a script logging into a user account in the sudoers file, I found an evil horrible hack, that is no doubt very insecure:
sshpass -p 'userpass' ssh -T -p port user#server << EOSSH
sudo -S su - << RROOT
userpass
echo ""
echo "*** Got Root ***"
echo ""
#[root commands go here]
useradd -m newuser
echo "newuser:newpass" | chpasswd
RROOT
EOSSH
I stumbled upon the same problem and for some reason the --stdin option was not available on the version of passwd I was using (shipped in Ubuntu 14.04).
If any of you happen to experience the same issue, you can work it around as I did, by using the chpasswd command like this:
echo "<user>:<password>" | chpasswd
Tested this on a CentOS VMWare image that I keep around for this sort of thing. Note that you probably want to avoid putting passwords as command-line arguments, because anybody on the entire machine can read them out of 'ps -ef'.
That said, this will work:
user="$1"
password="$2"
adduser $user
echo $password | passwd --stdin $user
This is the definitive answer for a teradata node admin.
Go to your /etc/hosts file and create a list of IP's or node names in a text file.
SMP007-1
SMP007-2
SMP007-3
Put the following script in a file.
#set a password across all nodes
printf "User ID: "
read MYUSERID
printf "New Password: "
read MYPASS
while read -r i; do
echo changing password on "$i"
ssh root#"$i" sudo echo "$MYUSERID":"$MYPASS" | chpasswd
echo password changed on "$i"
done< /usr/bin/setpwd.srvrs
Okay I know I've broken a cardinal security rule with ssh and root
but I'll let you security folks deal with it.
Now put this in your /usr/bin subdir along with your setpwd.srvrs config file.
When you run the command it prompts you one time for the User ID
then one time for the password. Then the script traverses all nodes
in the setpwd.srvrs file and does a passwordless ssh to each node,
then sets the password without any user interaction or secondary
password validation.
For me on Raspbian it works only this way (old password added):
#!/usr/bin/env bash
username="pi"
password="Szevasz123"
new_ps="Szevasz1234"
passwd ${username} << EOD
${password}
${new_ps}
${new_ps}
EOD
Have you looked at the -p option of adduser (which AFAIK is just another name for useradd)? You may also want to look at the -P option of luseradd which takes a plaintext password, but I don't know if luseradd is a standard command (it may be part of SE Linux or perhaps just an oddity of Fedora).
Sometimes it is useful to set a password which nobody knows. This seems to work:
tr -dc A-Za-z0-9 < /dev/urandom | head -c44 | passwd --stdin $user
echo 'yourPassword' | sudo -S yourCommand
if -S doesnt work try with -kS
You can use the expect utility to drive all programs that read from a tty (as opposed to stdin, which is what passwd does). Expect comes with ready to run examples for all sorts of interactive problems, like passwd entry.

Resources