Java 执行命令重启ubuntu系统

一、在ubuntu里编辑sudoers文件

编辑/etc/sudoers文件,为特定用户添加无需密码即可执行特定命令的权限。例如,如果你希望用户ids能够无需密码重启系统,

sudo vi /etc/sudoers

可以添加如下行:

ids ALL=(ALL) NOPASSWD: /sbin/reboot

以上用户ids需要替换成你自己的用户名

操作截图

二、Java程序执行重启命令

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class AgentMachineServiceImpl implements AgentMachineService {

    @Override
    public void reboot() {
        try {
            String command = "sudo /sbin/reboot";
            Process process = Runtime.getRuntime().exec(command);
            int exitCode = process.waitFor();
            log.info("AgentMachineServiceImpl.reboot exitCode={}", exitCode);
            if (exitCode == 0) {
                log.info("系统重启命令已成功发送");
            } else {
                log.info("执行命令失败,退出码,exitCode={}", exitCode);
            }
        } catch (Exception e) {
            log.error("AgentMachineServiceImpl.reboot error={}", e.getMessage());
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容