java 远程操作shell

  1. 添加相关远程mvan的jsch依赖包
    <dependency>
    			<groupId>com.jcraft</groupId>
    			<artifactId>jsch</artifactId>
    			<version>0.1.55</version>
    		</dependency>
  2. jsch的单命令执行
        /**
         * 只能单指令执行
         * @param ip
         * @param port
         * @param username
         * @param password
         * @param command
         *
         */
        public static void remoteExec(String ip, Integer port, String username, String password, String command) {
            JSch jsch = new JSch();
            Session session = null;
            Channel channel = null;
            ChannelExec channelExec = null;
            try {
                jsch.getSession(username, ip, port);
                session = jsch.getSession(username, ip, port);
                session.setPassword(password);
                Properties sshConfig = new Properties();
                sshConfig.put("StrictHostKeyChecking", "no");
                session.setConfig(sshConfig);
                session.connect(60 * 1000);
                logger.info("Session connected!");
                // 打开执行shell指令的通道
                logger.info("执行远程Shell命令 command - > {}", command);
                    channel = session.openChannel("exec");//只能执行一条指令(也可执行符合指令)
                    channelExec = (ChannelExec) channel;
                    channelExec.setCommand(command);
                    channel.setInputStream(null);
                    channelExec.setErrStream(System.err);
                    channel.connect();
                    InputStream in = channelExec.getInputStream();
                    InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                    BufferedReader reader = new BufferedReader(isr,1024);
                    reader.lines().forEach(logger::info);
                    isr.close();
                    in.close();
            } catch (JSchException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (channelExec != null && channelExec.isConnected()) {
                    channelExec.disconnect();
                }
                if (channel != null && channel.isConnected()) {
                    channel.disconnect();
                }
                if (session != null && session.isConnected()) {
                    session.disconnect();
                }
            }
    
        }

     

  3. jsch的多命令执行
     /**
         * 多指令执行shell
         * @param ip
         * @param port
         * @param username
         * @param password
         * @param cmdList
         */
        public static void remoteShell(String ip, Integer port, String username, String password, List<String> cmdList) {
            JSch jsch = new JSch();
            Session session = null;
            Channel channel = null;
            ChannelExec channelExec = null;
            try {
                jsch.getSession(username, ip, port);
                session = jsch.getSession(username, ip, port);
                session.setPassword(password);
                Properties sshConfig = new Properties();
                sshConfig.put("StrictHostKeyChecking", "no");
                session.setConfig(sshConfig);
                session.connect(60 * 1000);
                logger.info("Session connected!");
                // 打开执行shell指令的通道
                ChannelShell channelShell = (ChannelShell) session.openChannel("shell");
                InputStream inputStream = channelShell.getInputStream();//从远端到达的数据  都能从这个流读取到
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"),1024);
                channelShell.setPty(true);
                channelShell.connect();
                OutputStream outputStream = channelShell.getOutputStream();//写入该流的数据  都将发送到远程端
                //使用PrintWriter 就是为了使用println 这个方法
                //好处就是不需要每次手动给字符加\n
                PrintWriter printWriter = new PrintWriter(outputStream);
                cmdList.forEach(cmd->printWriter.println(cmd));
                printWriter.println("exit");//为了结束本次交互
                printWriter.flush();//把缓冲区的数据强行输出
                bufferedReader.lines().forEach(logger::info);
                bufferedReader.close();
                outputStream.close();
                inputStream.close();
                channelShell.disconnect();
                session.disconnect();
                System.out.println("DONE");
            } catch (JSchException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (channelExec != null && channelExec.isConnected()) {
                    channelExec.disconnect();
                }
                if (channel != null && channel.isConnected()) {
                    channel.disconnect();
                }
                if (session != null && session.isConnected()) {
                    session.disconnect();
                }
            }
    
        }

     

  4. 如果是非远程,本地使用java的RunTime执行命令
    public class ShellCommandUtils { 
        public static void localExec(String cmd, String threadName) {
            logger.info("开始执行runtime的脚本start");
            Process ps = null;
            try {
                ps = Runtime.getRuntime().exec(cmd);
                //处理InputStream的线程,获取进程的标准输入流
                Thread t = new Thread(new InputStreamThread(ps.getInputStream()), threadName.concat("_suc"));
                t.start();
                Thread t1 = new Thread(new InputStreamThread(ps.getErrorStream()), threadName.concat("_err"));
                t1.start();
                //等待shell脚本结果
                int execStatus = ps.waitFor();
                logger.info("执行runtime的脚本end");
                logger.info("shell脚本执行结果--execStatus =" + execStatus);
                logger.info("返回值为result=" + execStatus);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
        }
    }
    class InputStreamThread implements Runnable{
        private final static Logger logger = LoggerFactory.getLogger(InputStreamThread.class);
        private InputStream inputStream = null;
        public InputStreamThread(InputStream inputStream){
              this.inputStream = inputStream;
        }
        @Override
        public void run() {
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            try {
                String line = null;
                while ((line = br.readLine()) != null) {
                    if (line != null){
                        logger.info("hadoop执行结果输出:"+line);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            finally{
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

     

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值