sudo使用

一、免密执行sudo

1、创建账号

[root@bogon local]# passwd mysql
Changing password for user mysql.
New password:
BAD PASSWORD: The password is shorter than 8 characters
Retype new password:

2、修改/etc/sudoers

命令行输入 visudo回车即可进入/etc/sudoers下,或者vi /etc/sudoers  找到

## Allow root to run any commands anywhere
root ALL=(ALL) ALL 

root ALL=(ALL) NOPASSWD:ALL 

在这个下面添加如下,

xxx ALL=(ALL) ALL

sed -i '92a mysql ALL=(ALL) NOPASSWD:ALL ' /etc/sudoers 

3、把Defaults !visiblepw 改成 Defaults visiblepw

否则会出现 sudo: no tty present and no askpass program specified

grep -n "Defaults" /etc/sudoers

sed -i '55 s/!//g' /etc/sudoers 2>&1 >/dev/null

然后保存退出,再次切换到普通用户下,执行sudo命令就不用输入密码,

shell脚本创建用户并添加sudo

[root@oracledb ~]# cat user_add.sh
#!/bin/bash
name=jenkins
useradd $name
sed -i '92a $name ALL=(ALL) NOPASSWD:ALL ' /etc/sudoers;grep -n "Defaults" /etc/sudoers;sed -i '55 s/!//g' /etc/sudoers 

./user_add.sh 2>&1 >/dev/null

普通命令切换用户并执行命令

[root@bogon ~]# su mysql -c "sudo ls"

anaconda-ks.cfg a.py a.sh c.sh c.txt d.sh lnmp.py password.txt soft user_add.sh

二、非免密执行sudo

1、创建账号

[root@bogon local]# passwd oracle
Changing password for user oracle
New password: 
BAD PASSWORD: The password is shorter than 8 characters
Retype new password:

2、修改/etc/sudoers

命令行输入 visudo回车即可进入/etc/sudoers下,或者vi /etc/sudoers  找到

## Allow root to run any commands anywhere 
root ALL=(ALL) ALL 

root ALL=(ALL) NOPASSWD:ALL 

在这个下面添加如下,

xxx ALL=(ALL) ALL

sed -i '92a mysql ALL=(ALL) NOPASSWD:ALL ' /etc/sudoers 

下面的脚本是针对普通用户使用sudo需要输入密码写自动登录脚本

expect脚本自动切换su并且执行ls命令

[root@oracledb ~]# cat login.sh
#!/usr/bin/expect
set timeout 5
spawn su oracle -c "sudo ls"
expect "password for oracle:"
send "123 "
interact

[root@oracledb ~]# ./login.sh
spawn su oracle -c sudo ls
[sudo] password for oracle:
2.txt a.sh deplomet.yaml login.sh orcale.txt pdksh-5.2.14-37.el5.x86_64.rpm python3
3.txt c.sh d.sh orcale output.sh pip_output.sh Python-3.6.5.tgz
anaconda-ks.cfg cut_new.sh d.txt orcale_output.sh output.txt pip_output.txt user.txt
a.py cut.sh lnmp.sh orcale.sh –p pip.sh

三、连续执行sudo命令使用,

sudo systemctl stop firewalld && sudo systemctl start firewalld && sudo firewall-cmd --get-active-zones

报错:

[root@oracledb ~]# su oracle -c "ls"
ls: cannot open directory .: Permission denied

解决:
sed = /etc/sudoers | sed -i '92a oracle ALL=(ALL) NOPASSWD:ALL'


报错:
sudo: no tty present and no askpass program specified

解决:

http://blog.51cto.com/nosmoking/1595241

1. 注释Defaults requiretty
Defaults requiretty修改为 #Defaults requiretty, 表示不需要控制终端,没有就不用注释
否则会出现sudo: sorry, you must have a tty to run sudo

2. 增加行 Defaults visiblepw
否则会出现 sudo: no tty present and no askpass program specified

grep -n "Defaults" /etc/sudoers && sed -i '55 s/!//g' /etc/sudoers

原文地址:https://www.cnblogs.com/effortsing/p/9999500.html