项目场景: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自动配置
grep 'uwsgi ALL=(ALL) NOPASSWD:/usr/sbin/nginx' /etc/sudoers > /dev/null 2>&1 || add_sudoer
或者
[root@bogon NetworkRange]# visudo
#加上nginx的执行权限
uwsgi ALL=(ALL) NOPASSWD: /usr/sbin/nginx