How to run sudo command without a password on a Linux or Unix

发布时间: 更新时间: 总字数:458 阅读时间:1m 作者: 分享

I‘m a new Unix system user. How do I use sudo command without a password on a Linux or Unix-like systems? I log in as tom@my-cloud-server-ip and disabled root login for ssh. After login, I need to run some commands as root user. I am the only sysadmin using my server. How do I run or execute sudo command without a password for a user named Tom under Debian/Ubuntu/CentOS Linux cloud server?

Before

sudo (“superuser do”) is nothing but a tool for Linux or Unix-like systems to run commands/programs as another user. Typically as a root user or another user. You can delegate common tasks such as reboot the server or restart the Apache or make a backup using sudo for unprivileged users.

By default, sudo needs that a user authenticates using a password before running a command. Some times you may need to run a command with root privileges, but you do not want to type a password using sudo command. This is useful for scripting or any other purpose. This can be achieved by editing /etc/sudoers file and setting up correct entries. You need to consider any security consequence of allowing a sudo command execute without a password.

How to to run sudo command without a password

  1. Backup your /etc/sudoers file by typing the following command:

sudo cp /etc/sudoers /root/sudoers.bak
  1. Edit the /etc/sudoers file by typing the visudo command:

sudo visudo
  1. Append/edit the line as follows in the /etc/sudoers file for user named ‘vivek’ to run ‘/bin/kill’ and ‘systemctl’ commands:

vivek ALL = NOPASSWD: /bin/systemctl restart httpd.service, /bin/kill
  1. Save and exit the file.

How do I execute ALL sudo commands without password?

Type the following command as root user:

# visudo

Or

$ sudo visudo

Append the following entry to run ALL command without a password for a user named tom:

tom ALL=(ALL) NOPASSWD:ALL

Here is my sample config file:

Fig.01: How to execute sudo without password for tom user

Save and close the file. Now you can run any command as root user:

$ sudo /etc/init.d/nginx restart
$ sudo /sbin/reboot
$ sudo apt-get install htop
## get root shell ##
$ sudo -i

Please make sure only tom can login via ssh keys. https://www.cyberciti.biz/faq/how-to-set-up-ssh-keys-on-linux-unix/

How do I test it?

Simply run /bin/kill to kill any process without a password:

[vivek@server ]$ sudo /bin/kill pid-here

OR

[vivek@server ]$ sudo /bin/systemctl restart httpd.service

For more info read man pages: sudoers(5),visudo(8)

创建

cat >> /etc/sudoers.d/xiexianbin << EOF
xiexianbin ALL = (root) NOPASSWD:ALL
EOF

完毕。

Home Archives Categories Tags Docs