简体   繁体   中英

Using sudo inside a bash script: permission denied

This is my first real bash script, called makevhost, and I'm running into a permissions error when trying to use sudo to execute commands in the script. A site name is supplied as an argument to the script call in the CLI. The file is executable and the bin directory in which it lives is added to $PATH.

The concept is simple: It creates the directories and sample templates for a web site on my apache development server (Debian 11 VM on a Windows host), then creates the virtual host file and restarts the server. I've tried all the suggestionshere , most of which I found repeated on numerous sites and forums.

When I run the script it seems to run fine until line 31, where I get a "Permission Denied" error. I get another error on line 43, but the permissions error is what I'm working on now.

Here's my code:

#!/bin/bash

if mkdir -p /var/www/"$1"/public_html; then
    echo "Creating site directories ..."
    cd /var/www/"$1"/public_html
    mkdir style images js
    chown -R $USER:$USER /var/www/"$1"
else
    echo "Could not create site directories"
    exit
fi

echo "Creating index.html and style.css"
cat <<- EOF > index.html
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="style/style.css"></link>
</head>
<body>

</body>
</html>
EOF

touch style/style.css
echo "Site files created"

sudo cat <<- EOF > /etc/apache2/sites-available/"$1".com.conf
<VirtualHost *:8080>
    ServerAdmin eric@sabresong.com
    ServerName sabresong.local
    ServerAlias "$1"
    DocumentRoot /var/www/"$1"/public_html
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
EOF
echo "Virtual Host File created."

if [ sudo a2ensite "$1".com.conf ]; then
    echo "$1 enabled"
    sudo a2dissite 000-default.conf
    echo "Restarting Apache"
    sudo systemctl restart apache2
    echo "Finished!"
else
    echo 'WARNING! Could not enable new site "$1"'
fi

My /etc/sudoers.d/eric has only one line: eric ALL=(root) NOPASSWD: /home/eric/bin/

In visudo, I have added this: eric ALL=(ALL:ALL) NOPASSWD: /home/eric/bin/ I also tried that same line with ALL=(ALL)

I know that using NOPASSWD isn't best practice, but I'm the only person with access to ths machine, and I haven't yet worked out how to use the sudo password for specific lines in the script but not for others, so I'm going this route, mostly for the learning experience.

I think you actually have to run the script with the sudo command. so:

sudo ./makevhost

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