如何在脚本中运行'sudo'命令?

分享于 

5分钟阅读

ubuntu

  繁體

问题

我要手动对程序打补丁,必须键入以下命令


sudo ./playback_delete_data_patch.sh 09_delete_old_data_p.sql 



在09之前有一个空格:


sudo ./playback_delete_data_patch.sh [space] 09_delete_old_data_p.sql



如何运行这个内部脚本?


答案1

使用sudo的脚本,通常不是个好办法,从脚本中删除sudo,并使用sudo运行脚本本身更合适:

 
sudo myscript.sh



这样,脚本中的所有命令都将以root权限运行,在启动脚本时只需要给密码一次,


sudo -u username command 




答案2

你可以修改sudoers文件。

运行sudo visudo

为你的用户名和脚本添加一个条目,你希望在不要求密码的情况下运行。


username ALL=(ALL) NOPASSWD: /path/to/script




答案3

你可以尝试以下操作:


echo"PASSWORD" | sudo -S ./playback_delete_data_patch.sh 09_delete_old_data_p.sql



这不太安全,因为你正在写一个纯文本的sudoer密码,为了使它更安全,可以创建一个变量,并将sudo密码读入该变量,然后你可以执行命令:


echo $PASSWORD | sudo -S ./playback_delete_data_patch.sh 09_delete_old_data_p.sql



另外,如果你不介意所有的命令都作为root执行,你可以使用sudo简单执行你的脚本,如前面所建议的。

 
sudo ./myscript




答案4

这是一个示例脚本,说明如何实现该功能:


#!/bin/bash



# ref: https://askubuntu.com/a/30157/8698


if ! [ $(id -u) = 0 ]; then


 echo"The script need to be run as root." >&2


 exit 1


fi



if [ $SUDO_USER ]; then


 real_user=$SUDO_USER


else


 real_user=$(whoami)


fi



# Commands that you don't want run with root would be invoked


# with: sudo -u $real_user


# So they will be ran as the user who invoked the sudo command


# Keep in mind, if the user is using a root shell (they're logged in as root),


# then $real_user is actually root


# sudo -u $real_user non-root-command



# Commands that need to be ran with root would be invoked without sudo


# root-command




答案5


#!/bin/bash


# this declares that current user is a sudoer


sudo tee /etc/sudoers.d/$USER <<END


END



# write the content of your script here


sudo npm install hexo-cli -g


mkdir Untitled


sudo apt-get install python



# then to remove the sudo access from the current user


sudo /bin/rm /etc/sudoers.d/$USER


sudo -k




答案6

实际上有一种更简单的方法,

在启动脚本时,输入sudo密码作为参数,提示输入sudo密码的命令回显它。


#!/bin/bash



PW=$1


echo $PW | ./playback_delete_data_patch.sh 09_delete_old_data_p.sql 


./command_wo_sudo.sh <param>


echo $PW | ./other_command_requires_sudo.sh <param>



你可以在脚本启动后添加提示,如下所示:


echo"enter the sudo password, please"


read PW



这也适用于运行需要"yes"才能继续的命令/脚本:


echo $PW | yes | ./install.sh




答案7

你可以尝试将运行脚本的用户添加到sudoers文件:


#give permissions to the file


sudo chmod 700 /etc/sudoers.d/useradm



sudo visudo /etc/sudoers.d/useradm



#add the following text, changing"user" but your desired user


user ALL=(ALL)NOPASSWD:ALL



#return the right permissions to the file


sudo chmod 440 /etc/sudoers.d/useradm





COM  COMM  Comma  
相关文章