Shell script calls sudo; how do I suppress the password prompt

前端 未结 5 806
萌比男神i
萌比男神i 2020-12-28 22:39

I am writing a simple shell script which changes the mac address of the network hardware. One of the line is :

sudo ifconfig eth0 hw ether 00:99:99:00:00:00
         


        
相关标签:
5条回答
  • 2020-12-28 22:42

    A safer way to do it would be:

    sudo visudo -f sudoers
    

    then add

    myuser ALL=NOPASSWD:/sbin/ifconfig
    

    to the editor window that appeared. Once you are done, use :x to quit

    0 讨论(0)
  • 2020-12-28 22:51

    Most definitely, if you don't mind making that particular command 'free for use' for that particular user:

    See basically my other answer here: Shell script - Sudo-permissions lost over time

    The simplest thing that may work is

    myuser = NOPASSWD: /sbin/ifconfig
    

    Also, you could sudo an arbitrary command on the same terminal (tty/vty), and sudo will cache the authentication for a while (or until sudo -k), so you may start the script and it will 'remember' the credentials from your earlier sudo invocation. I sometimes do this when composing pipes with sudo (just preceded them with sudo true)

    0 讨论(0)
  • 2020-12-28 22:51
    echo "password" | sudo -S ifconfig eth0 hw ether 00:99:99:00:00:00
    
    0 讨论(0)
  • 2020-12-28 22:54

    Here is a Zenity dialog that does something similar to Tman's comment,
    though the password isn't stored in history... This may be a good alternative

    #!/bin/bash
    ENTRY=`zenity --password`
    case $? in
    0)
    pw=$(echo $ENTRY | cut -d'|' -f1)
    ;;
    1)
    echo "Stop login.";;
    -1)
    echo "An unexpected error has occurred.";;
    esac
    TMP=$(echo "${pw}" | sudo -Sv)
    TMP=0
    
    0 讨论(0)
  • 2020-12-28 23:07

    You need a sudo configuration line which allows for the command to be executed by the user without password prompt.

    You can disable the password prompt for a whole user (more dangerous, but perhaps ok if you are the only user on your desktop -- DONT do this on a server ):

    yourusername  ALL=(ALL) NOPASSWD: ALL
    

    or more restrictive, only allowing the ifconfig command:

    yourusername  ALL= NOPASSWD: /sbin/ifconfig
    

    See: man sudoers , man sudo

    http://ubuntuforums.org/showthread.php?t=1132821

    http://www.linuxhelp.net/guides/sudo/

    0 讨论(0)
提交回复
热议问题