项目场景:
项目场景:Django项目运行中系统用户为uwsgi用户(非root),需要去执行sudo命令并且不使用密码,下面以nginx -s reload为例
问题描述
Django项目运行中系统用户为uwsgi,需要去执行sudo命令并且不使用密码。
# 重启nginx
restart_nginx_res = subprocess.run(['nginx -s reload'], shell=True, stdout=subprocess.PIPE)
debug("{}:return_code".format(restart_nginx_res.returncode))
原因分析:
问题分析:普通用户需要使用sudo的时候会需要输入密码,提示下列信息:
We trust you have received the usual lecture from the local System
Administrator. It usually boils down to these three things:
#1) Respect the privacy of others.
#2) Think before you type.
#3) With great power comes great responsibility.
sudo: no tty present and no askpass program specified
解决方案:
具体解决方案:修改Python代码并以root权限执行脚本或手动加上nginx执行权限
# 重启nginx
restart_nginx_res = subprocess.run(['sudo nginx -s reload'], shell=True, stdout=subprocess.PIPE)
debug("{}:return_code".format(restart_nginx_res.returncode))
以root用户执行shell脚本
#!/bin/bash
# 将visudo自动配置
echo 'uwsgi ALL=(ALL) NOPASSWD: /usr/sbin/nginx' >> /etc/sudoers
或者
[root@bogon NetworkRange]# visudo
#加上nginx的执行权限
uwsgi ALL=(ALL) NOPASSWD: /usr/sbin/nginx