gpt4 book ai didi

linux - 在脚本(.sh 文件)中以没有密码的 sudo 用户身份运行命令

转载 作者:太空宇宙 更新时间:2023-11-04 12:14:04 25 4
gpt4 key购买 nike

我正在尝试创建一个脚本,用于从 DJango/Python 项目中删除 *.pyc 文件。

这些文件看起来如下:

./backend/libmstr/vendors/migrations/__pycache__/__init__.cpython-36.pyc
./backend/libmstr/vendors/__pycache__/__init__.cpython-36.pyc
./backend/libmstr/vendors/__pycache__/models.cpython-36.pyc
./backend/libmstr/vendors/__pycache__/admin.cpython-36.pyc

权限如下:

ls -lart ./backend/libmstr/vendors/migrations/__pycache__/__init__.cpython-36.pyc
-rw-r--r-- 1 root root 143 Dec 21 15:55 ./backend/libmstr/vendors/migrations/__pycache__/__init__.cpython-36.pyc

如您所见,该文件的组和用户是root

鉴于我没有以 root 身份运行任何东西,我不确定它们来自哪里。

所以,我选择使用函数删除它们。为了让函数没有问题地运行,它必须在“sudo”下运行

我创建了文件:/home/dockerdj/remove_pyc_files.sh

#!/bin/bash
sudo find . -name "*.pyc" -exec rm -f {} \; -print

文件(以上)是在用户帐户上创建的:dockerdj 我还给了用户 sudo 权限。我还在 .bashrc 文件中添加了以下内容

export PATH=$PATH:/home/dockcclubdjango

我还在 /etc/sudoers 中添加了以下内容:

https://www.digitalocean.com/community/tutorials/how-to-edit-the-sudoers-file-on-ubuntu-and-centos

dockerdj ALL=(ALL) NOPASSWD: /home/dockerdj/remove_pyc_files.sh

即使在完成上述操作后,在运行 remove_pyc_files.sh 时,仍然要求我输入密码。

我做错了什么?

最佳答案

是的,系统要求您输入用户密码以确认这是用户是强制性的,您可以这样做:

#!/bin/bash

PASSWORD='password or something';
echo -n -e '${PASSWORD}' | sudo -S find . -name "*.pyc" -exec rm -f {} \; -print

This way the script will not ask you for the password, another thing you can do is have the password in hexadecimal and make a join with '\\x'

关于linux - 在脚本(.sh 文件)中以没有密码的 sudo 用户身份运行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47929355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com