简体   繁体   English

执行sudo和chmod命令的bash脚本无法正常工作

[英]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. 我正在尝试创建一个以执行sudo -s命令的用户开头的bash脚本。

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. 我不想输入密码30次。 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. 我在创建bash脚本方面非常陌生,需要一些认真的指导。

The idea you have there will never work as sudo(1) does not read passwords from standard input unless it's a terminal. 你在那里的想法永远不会起作用,因为sudo(1)不会从标准输入中读取密码,除非它是终端。 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. 如果你真的想要实现这一点(我建议不要这样做),你应该在目标机器上编辑/etc/sudoers让你运行sudo(1)而不需要密码就无需密码就需要完成的事情。 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. 为此,你不应该让自己在没有密码的情况下运行任何 chmod命令行,而是在目标机器中创建一个脚本(例如'/ usr / local / bin / do-my-promiscuous-chmod`)然后告诉sudo让你只需运行该脚本而无需输入密码。

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: 例如,将以下内容添加到/etc/sudoers将允许用户“foo”在没有密码且具有root权限的情况下运行/usr/local/sbin/do-unsafe

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

Agree with Sami, no hardcoding password in scripts. 同意Sami,脚本中没有硬编码密码。

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: 如果脚本不需要以root身份运行,并且可以由某个其他应用程序管理员帐户(如DBA)运行,则应该仅为该用户提名以限制权限,例如:

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

Secondly, don't give any files with 777 permissions, it is unsafe. 其次,不要给任何具有777权限的文件,这是不安全的。 Think some others way, such as ACL permission set. 想一些其他的方式,比如ACL权限集。

chmod 777 $FILE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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