命令行 从脚本中请求 root 权限

分享于 

3分钟阅读

ubuntu

  繁體

问题

如何"嵌入"pkexec或sudo,以root权限运行整个脚本?


答案1

这将工作:


echo"$(whoami)"



["$UID" -eq 0 ] || exec sudo"$0""$@"



例如:


./test.sh 


blade


[sudo] password for blade: 


root




答案2

如果你想要一个漂亮的对话框,尝试如下代码


brand="My Software"



# Check that the script is running as root. If not, then prompt for the sudo


# password and re-execute this script with sudo.


if ["$(id -nu)" !="root" ]; then


 sudo -k


 pass=$(whiptail --backtitle"$brand Installer" --title"Authentication required" --passwordbox"Installing $brand requires administrative privilege. Please authenticate to begin the installation.nn[sudo] Password for user $USER:" 12 50 3>&2 2>&1 1>&3-)


 exec sudo -S -p ''"$0""$@" <<<"$pass"


 exit 1


fi



它使用whiptail,如果还没有,你可以安装它:


sudo apt-get install whiptail




答案3


#!/usr/bin/sudo bash


# ...




答案4


#!/bin/sh 


mem=$(free | awk '/Mem:/ {print $4}')


swap=$(free | awk '/Swap:/ {print $3}')



if [ $mem -lt $swap ]; then


 echo"ERROR: not enough RAM to write swap back, nothing done" >&2


 exit 1


fi



sudo swapoff -a && 


sudo swapon -a



此脚本可以作为sudo <scriptname><scriptname>运行。无论哪种情况,它都会要求输入密码。


答案5

如果脚本需要root权限,最好将它放在脚本中:


#!/bin/bash


["$UID" -eq 0 ] || { echo"This script must be run as root."; exit 1;}



# do privileged stuff, etc.




答案6

我这样做:


echo -n"Enter password for sudo rights:"


read -s pass



echo $pass | sudo -S [your command here]





COM  COMM  Comma  命令行  Request  roo