0
点赞
收藏
分享

微信扫一扫

如何在shell中传递sudo密码

简介

在Linux中普通用户执行某些系统命令时需要root权限,这时需要我们输入密码才能执行。当使用crond定时任务来执行shell脚本时,由于不会出现交互界面,执行到sudo需要输入密码时往往会执行出错,导致脚本无法正确运行。

解决方法

我们可以使用echo将密码作为输入传递给sudo -S命令,就可以很好的解决这个问题

简单示例:

#!/bin/bash
time=$(date +"%F %Y%m%d%H%M%S")
if systemctl status httpd >/dev/null 2>&1 ;then
        echo "${time}http已启动" >>success.txt
else
        echo "${time}http未启动" >>failed.txt
        sudo  systemctl start httpd
fi

上述脚本在创建的定时任务中执行时就会报错,导致最后一条命令无法执行。

报错提示告诉我们使用sudo -S 参数从标准输入中读取密码

如何在shell中传递sudo密码_普通用户

我们换个写法再次尝试

#!/bin/bash
time=$(date +"%F %Y%m%d%H%M%S")
passwd="123"
if systemctl status httpd >/dev/null 2>&1 ;then
        echo "${time}http已启动" >>success.txt
else
        echo "${time}http未启动" >>failed.txt
        echo "${passwd}"|sudo -S  systemctl start httpd
        echo "${time} http启动成功" >>httpd.txt
fi

查看运行效果,查看定时任务日志与httpd.txt文件

可以看到定时任务日志没有报错!脚本执行成功

如何在shell中传递sudo密码_sudo_02


如何在shell中传递sudo密码_定时任务_03

ps:当我们使用普通用户设置定时任务执行shell脚本时,如果也出现了上述错误,不妨可以试试~

举报

相关推荐

0 条评论