简体   繁体   中英

bash script executing sudo and chmod command not working properly

I am trying to create a bash script that starts with the user executing a sudo -s command.

This is my script:

#!/bin/bash
SSH_USER=testuser
SUDO_PASSWD=secretpassword
FILE=/www/a/logs/service.log

MACHINES=( 'machine1' );
for HOST in ${MACHINES[@]}; do
    ssh -t -l "$SSH_USER" "$HOST" "echo '$SUDO_PASSWD' | sudo -Ss chmod 777 $FILE"
done

I feel like this script should not prompt me for the password but it does. I do not want to have to input the password 30 different times. I have tried multiple versions where I hard code the password into the script but I still get prompted to enter in a password. HELP ME PLEASE. I'm VERY new at creating bash scripts and need some serious guidance.

The idea you have there will never work as sudo(1) does not read passwords from standard input unless it's a terminal. Hardcoding passwords into a script is also very bad idea, as pointed out repeatedly in comments.

If you really want to make this happen (I recommend against it), you should do edit /etc/sudoers in your target machine to let you run sudo(1) without it asking a password for things you need to be done without a password. For that you should not let yourself run any chmod command lines without a password, but instead create a script in target machine (for example ´/usr/local/bin/do-my-promiscuous-chmod`) then tell sudo to let you run just that script without asking a password.

For example adding the following to /etc/sudoers will let user "foo" run /usr/local/sbin/do-unsafe without a password and with root privileges:

foo ALL = (root) NOPASSWD: /usr/local/sbin/do-unsafe

Agree with Sami, no hardcoding password in scripts.

more suggestions.

If the script needn't run as root, and can be run by some other application admin account, such as DBA, you should nominate to that user only to limit the permissions, such as:

foo ALL = (dba) NOPASSWD: /usr/local/sbin/do-unsafe

Secondly, don't give any files with 777 permissions, it is unsafe. Think some others way, such as ACL permission set.

chmod 777 $FILE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM