Ubuntu制作系统服务时服务程序需要root权限

Ubuntu制作系统服务时服务程序需要root权限

1、简单service

start_service.service

[Unit]
Description=MonitorIP
After=network-online.target
Wants=network-online.target

[Service]
WorkingDirectory=/home/up/docker-compose-test/test_demo/service_test
ExecStart=/home/up/docker-compose-test/test_demo/service_test/start.sh
Type=simple
Restart=always
TimeoutSec=infinity
User=root

[Install]
WantedBy=multi-user.target

2、服务程序需要root权限

方案一(推荐)

  • 设置service文件中Userroot

方案二(不推荐)

  • 设置service文件中User当前用户(非root)

    [Unit]
    Description=MonitorIP
    After=network-online.target
    Wants=network-online.target
    
    [Service]
    WorkingDirectory=/home/up/docker-compose-test/test_demo/service_test
    ExecStart=/home/up/docker-compose-test/test_demo/service_test/start.sh
    Type=simple
    Restart=always
    TimeoutSec=infinity
    User=up
    
    [Install]
    WantedBy=multi-user.target
    
  • 修改sudo时不需要输入密码

    • sudo vim /etc/sudoers

      sudo下一行添加your_username ALL = (ALL) NOPASSWORD: ALL

      #
      # This file MUST be edited with the 'visudo' command as root.
      #
      # Please consider adding local content in /etc/sudoers.d/ instead of
      # directly modifying this file.
      #
      # See the man page for details on how to write a sudoers file.
      #
      Defaults        env_reset
      Defaults        mail_badpass
      Defaults        secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin"
      
      # Host alias specification
      
      # User alias specification
      
      # Cmnd alias specification
      
      # User privilege specification
      root    ALL=(ALL:ALL) ALL
      
      # Members of the admin group may gain root privileges
      %admin ALL=(ALL) ALL
      
      # Allow members of group sudo to execute any command
      %sudo   ALL=(ALL:ALL) ALL
      up ALL=(ALL) NOPASSWD: ALL    # 例如这里添加up用户不输入密码
      # See sudoers(5) for more information on "#include" directives:
      
      #includedir /etc/sudoers.d
      
原文地址:https://www.cnblogs.com/linagcheng/p/14272945.html