java操作linux

1、加入maven依赖

        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.53</version>
        </dependency> 

 

2、封装执行命令方法

public static String exeCommand(String host, int port, String user, String password, String command) throws JSchException, IOException {
        JSch jsch = new JSch();
        Session session = jsch.getSession(user, host, port);
        session.setConfig("StrictHostKeyChecking", "no");

        session.setPassword(password);
        session.connect();

        ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
        InputStream in = channelExec.getInputStream();
        channelExec.setCommand(command);
        channelExec.setErrStream(System.err);
        channelExec.connect();
        String out = IOUtils.toString(in, "UTF-8");

        channelExec.disconnect();
        session.disconnect();
        return out;
    }

 

3、测试

        String host = "10.100.26.81";
        int port = 22;
        String user = "root";
        String password = "xxx";
        String command = "curl -k -v -s -L 'https://hids.xxx.com/agent/download?k=xxx&group=xxx&protocol=0' | bash";
        String res = exeCommand(host,port,user,password,command);
        System.out.println(res);    

 

posted @ 2021-03-17 16:24  mabiao008  阅读(180)  评论(0编辑  收藏  举报