温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在java中执行sudo 命令

发布时间:2021-07-01 11:55:57 来源:亿速云 阅读:290 作者:chen 栏目:大数据

本篇内容介绍了“怎么在java中执行sudo 命令”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

 *    1. 修改/etc/sudoers文件,在其中添加一行:
 *          username  ALL=(ALL) NOPASSWD:ALL
 *       其中,"username"是需要运行这个程序的用户名。
 /bin/bash -c echo password |sudo -S command

Shell(JSCH)工具类:

package cn.bywin.cbvsp.common.utils;

import cn.bywin.cbvsp.DAL.BO.po.MyUserInfo;
import com.jcraft.jsch.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

/**
 * @author linbin
 * @create 2019-03-19 10:06
 */
public class Shell {

    //远程主机的ip地址
    private String ip;
    //远程主机登录用户名
    private String username;
    //远程主机的登录密码
    private String password;
    //设置ssh连接的远程端口
    public static final int DEFAULT_SSH_PORT = 22;
    //保存输出内容的容器
    private ArrayList<String> stdout;

    public Shell() {
    }

    /**
     * 初始化登录信息
     *
     * @param ip
     * @param username
     * @param password
     */
    public Shell(final String ip, final String username, final String password) {
        this.ip = ip;
        this.username = username;
        this.password = password;
        stdout = new ArrayList<String>();
    }



    /**
     * 执行shell命令
     *
     * @param command
     * @return
     */
    //原本是 execute(final String command)
    public int execute(String command) {
        int returnCode = 0;
        JSch jsch = new JSch();
        MyUserInfo userInfo = new MyUserInfo();

        try {
            //创建session并且打开连接,因为创建session之后要主动打开连接
            Session session = jsch.getSession(username, ip, DEFAULT_SSH_PORT);
            session.setPassword(password);
            session.setUserInfo(userInfo);
            session.connect();

            //打开通道,设置通道类型,和执行的命令
            Channel channel = session.openChannel("exec");
            ChannelExec channelExec = (ChannelExec) channel;
            channelExec.setCommand(command);

            channelExec.setInputStream(null);
            BufferedReader input = new BufferedReader(new InputStreamReader
                    (channelExec.getInputStream()));

            channelExec.connect();
            System.out.println("The remote command is :" + command);

            //接收远程服务器执行命令的结果
            String line;
            while ((line = input.readLine()) != null) {
                stdout.add(line);
            }
            input.close();

            // 得到returnCode
            if (channelExec.isClosed()) {
                returnCode = channelExec.getExitStatus();
                // 关闭通道
                channelExec.disconnect();
                //关闭session
                session.disconnect();
            }



        } catch (JSchException e) {

            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnCode;
    }

    public static ChannelExec getCommandResult(Session session, String command) throws JSchException, IOException {
        ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
        channelExec.setCommand(command);
        channelExec.setInputStream(null);
        channelExec.setErrStream(System.err);
        channelExec.connect();


        /*if (null != session) {
            session.disconnect();
        }*/
        return channelExec;
    }

    /**
     * get stdout
     *
     * @return
     */
    public ArrayList<String> getStandardOutput() {
        return stdout;
    }
}

执行代码:

    public static void main(String[] args) {
        Shell shell = new Shell("192.168.161.152","root","linbinbhs7");
        shell.execute("/bin/bash -c echo linbinbhs7 |sudo -S ls");
        ArrayList<String> graphicsCardNames = shell.getStandardOutput();
        graphicsCardNames.forEach(e->{
            System.out.println(e);
        });
    }

删除指定时间的文件

public class TestShell {
    public static void main(String[] args) {
        Shell shell = new Shell("192.168.96.136","developer","de183!!!");
        shell.execute("/bin/bash -c echo de183!!! |sudo -S find /home/developer/temp -type f -mmin +1 -exec rm -rfv {} \\; > /home/developer/temp/nohup.out;");
        ArrayList<String> graphicsCardNames = shell.getStandardOutput();
        graphicsCardNames.forEach(System.out::println);
    }
}

“怎么在java中执行sudo 命令”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI