java 代码执行linux命令

java 代码执行linux命令远程执行linux命令代码代码不是在服务器部署时,但是需要执行这个服务器的linux命令packagecom.demo.common.linux;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;……

java

远程执行linux命令代码

代码不是在服务器部署时,但是需要执行这个服务器的linux命令

maven库

<!-- https://mvnrepository.com/artifact/ch.ethz.ganymed/ganymed-ssh2 -->
<dependency>
    <groupId>ch.ethz.ganymed</groupId>
    <artifactId>ganymed-ssh2</artifactId>
    <version>262</version>
</dependency>
package com.demo.common.linux;

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

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

/** * @author zhaosongbin */
public class SshUtil { 
   

    private final static String host = "192.168.1.1";
    private final static int port = 22;
    private final static String username = "root";
    private final static String password = "root";
    private final static String directory = "/home/";
    private static SshUtil ftp = new SshUtil();
    private static Connection con = new Connection(host, port);

    /** * 执行传来的linux指令 * * @param command * @return */
    public static List<String> execCom(String command) { 
   
        Session session = ftp.session();
        BufferedReader br = null;
        List<String> msgList = new ArrayList<String>();
        try { 
   
            session.requestPTY("vt100", 80, 24, 640, 480, null);
            session.execCommand(command);
            InputStream stdout = new StreamGobbler(session.getStdout());
            br = new BufferedReader(new InputStreamReader(stdout));
            while (true) { 
   
                String line = br.readLine();
                if (line == null) { 
   
                    break;
                }
                msgList.add(line);
            }
        } catch (IOException e) { 
   
            e.printStackTrace();
        }
        try { 
   
            br.close();
        } catch (IOException e) { 
   
            e.printStackTrace();
        }
        session.close();
        con.close();
        return msgList;
    }

    public Session session() { 
   
        Session session = null;
        try { 
   
            con.connect();
            // 远程服务器的用户名密码
            con.authenticateWithPassword(username, password);
            session = con.openSession();
        } catch (IOException e) { 
   
            e.printStackTrace();
            return null;
        }
        return session;
    }


}

本地执行linux命令代码

代码在服务器部署,并且需要执行服务器linux命令

package com.demo.common.linux;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/** * @author zhaosongbin */
public class RunTimeUtil { 
   

    private final static Logger logger = LoggerFactory.getLogger(RunTimeUtil.class);

    private static List<String> msg=new ArrayList<String>();

    public static List<String> execCom(String cmd) { 
   
        List<String> msgList=new ArrayList<String>();
        try { 
   
            //执行命令
            Process process = Runtime.getRuntime().exec(new String[]{ 
   "/bin/sh", "-c", cmd});

            InputStreamReader ir = new InputStreamReader(process.getInputStream(),"utf-8");
            LineNumberReader input = new LineNumberReader(ir);

            String line;
            //输出结果
            while ((line = input.readLine()) != null) { 
   
                msgList.add(line);
            }
        } catch (IOException e) { 
   
            //捕捉异常
            logger.error("IOException " + e.getMessage());
        }
        return msgList;
    }

    public static List<String> execComs(String strings)  { 
   

        msg.clear();
        try { 
   
            //执行命令
            Process process = Runtime.getRuntime().exec(new String[]{ 
   "/bin/sh", "-c", strings});
            read(process.getInputStream(),"input");
            read(process.getErrorStream(),"error");
        } catch (IOException e) { 
   
            //捕捉异常
           logger.error("IOException " + e.getMessage());
        }
        return msg;
    }
    private static void read(InputStream inputStream, String str) { 
   
        try { 
   
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) { 
   
                if("input".equals(str)){ 
    msg.add(line);}
                else if("error".equals(str)){ 
    msg.add(line);}

            }
        } catch (IOException e) { 
   
            e.printStackTrace();
        } finally { 
   
            try { 
   
                inputStream.close();
            } catch (IOException e) { 
   
                e.printStackTrace();
            }
        }
    }
}

今天的文章java 代码执行linux命令分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/29744.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注