美文网首页
工具1:Java远程、本地(免密/非免密)环境执行linux的命

工具1:Java远程、本地(免密/非免密)环境执行linux的命

作者: 一到家就变乖 | 来源:发表于2019-03-29 11:12 被阅读0次

    一、非免密环境

    Java的runtime机制实现远程(本地)linux命令或者shell脚本调用,并以字符串返回执行结果。具体代码如下:

        import java.io.BufferedReader;  
        import java.io.IOException;  
        import java.io.InputStream;  
        import java.io.InputStreamReader;  
        import java.io.UnsupportedEncodingException;  
        import org.apache.commons.lang.StringUtils;  
        import ch.ethz.ssh2.Connection;  
        import ch.ethz.ssh2.Session;  
        import ch.ethz.ssh2.StreamGobbler;  
          
        /** 
         * 远程(本地)执行linux的命令或者shell 
         * @author damocle 
         */  
        public class ExecuteRuntimeCommand2 {  
            //字符编码默认是utf-8  
            private static String  DEFAULTCHART="UTF-8";  
            private Connection conn;  
            private String ip;  
            private String userName;  
            private String userPwd;  
              
            public ExecuteRuntimeCommand2(String ip, String userName, String userPwd) {  
                this.ip = ip;  
                this.userName = userName;  
                this.userPwd = userPwd;  
            }  
              
            public ExecuteRuntimeCommand2() {  
                  
            }  
              
            /** 
             * 远程登录linux的主机 
             * @author damocle
             * @since  V0.1 
             * @return 
             *      登录成功返回true,否则返回false 
             */  
            public Boolean login(){  
                boolean flg=false;  
                try {  
                    conn = new Connection(ip);  
                    conn.connect();//连接  
                    flg=conn.authenticateWithPassword(userName, userPwd);//认证  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
                return flg;  
            }  
            /** 
             * @author damocle 
             * 远程执行shll脚本或者命令 
             * @param cmd 
             *      即将执行的命令 
             * @return 
             *      命令执行完后返回的结果值 
             * @since V0.1 
             */  
            public String execute(String cmd){  
                String result="";  
                try {  
                    if(login()){  
                        Session session= conn.openSession();//打开一个会话  
                        session.execCommand(cmd);//执行命令  
                        result=processStdout(session.getStdout(),DEFAULTCHART);  
                        //如果为得到标准输出为空,说明脚本执行出错了  
                        if(StringUtils.isBlank(result)){  
                            result=processStdout(session.getStderr(),DEFAULTCHART);  
                        }  
                        conn.close();  
                        session.close();  
                    }  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
                return result;  
            }  
            
            /**
             * 调用本地linux
             * @param cmd
             * @return
             */
            public String executeLocal(String command){  
                String result = null;
                try {
                    String[] cmd = new String[]{"/bin/sh", "-c",command};
                    Process ps = Runtime.getRuntime().exec(cmd);
         
                    BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
                    StringBuffer sb = new StringBuffer();
                    String line;
                    while ((line = br.readLine()) != null) {
                        //执行结果加上回车
                        sb.append(line).append("\n");
                    }
                    result = sb.toString();
                } catch (Exception e) {
                    e.printStackTrace();
                }
         
                return result;
            }
              
              
            /** 
             * @author damocle 
             * 远程执行shll脚本或者命令 
             * @param cmd 
             *      即将执行的命令 
             * @return 
             *      命令执行成功后返回的结果值,如果命令执行失败,返回空字符串,不是null 
             * @since V0.1 
             */  
            public String executeSuccess(String cmd){  
                String result="";  
                try {  
                    if(login()){  
                        Session session= conn.openSession();//打开一个会话  
                        session.execCommand(cmd);//执行命令  
                        result=processStdout(session.getStdout(),DEFAULTCHART);  
                        conn.close();  
                        session.close();  
                    }  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
                return result;  
            }  
              
           /** 
            * 解析脚本执行返回的结果集 
            * @author damocle 
            * @param in 输入流对象 
            * @param charset 编码 
            * @since V0.1 
            * @return 
            *       以纯文本的格式返回 
            */  
            private String processStdout(InputStream in, String charset){  
                InputStream  stdout = new StreamGobbler(in);  
                StringBuffer buffer = new StringBuffer();;  
                try {  
                    BufferedReader br = new BufferedReader(new InputStreamReader(stdout,charset));  
                    String line=null;  
                    while((line=br.readLine()) != null){  
                        buffer.append(line+"\n");  
                    }  
                } catch (UnsupportedEncodingException e) {  
                    e.printStackTrace();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
                return buffer.toString();  
            }  
              
            public static void setCharset(String charset) {  
                DEFAULTCHART = charset;  
            }  
            public Connection getConn() {  
                return conn;  
            }  
            public void setConn(Connection conn) {  
                this.conn = conn;  
            }  
            public String getIp() {  
                return ip;  
            }  
            public void setIp(String ip) {  
                this.ip = ip;  
            }  
            public String getUserName() {  
                return userName;  
            }  
            public void setUserName(String userName) {  
                this.userName = userName;  
            }  
            public String getUserPwd() {  
                return userPwd;  
            }  
            public void setUserPwd(String userPwd) {  
                this.userPwd = userPwd;  
            }  
        }
    

    二、免密环境

    1、添加Jar包依赖
    <dependency>
        <groupId>com.jcraft</groupId>
        <artifactId>jsch</artifactId>
        <version>0.1.54</version>
    </dependency>
    
    2、代码实例
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import com.jcraft.jsch.Channel;
    import com.jcraft.jsch.ChannelExec;
    import com.jcraft.jsch.JSch;
    import com.jcraft.jsch.JSchException;
    import com.jcraft.jsch.Session;
    
    public class ConnectionSSH {
        public static void main(String[] args) throws JSchException, IOException {
        JSch jsch = new JSch();
        String pubKeyPath = "C:\\Users\\yutao\\.ssh\\id_rsa";
        jsch.addIdentity(pubKeyPath);
    
        String username = "yutao";
        String host = "192.168.116.131";
        Session session=jsch.getSession(username, host, 22);//为了连接做准备
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();
        String command = "./test.sh";
    //      Channel channel=session.openChannel("shell");
        ChannelExec channel=(ChannelExec)session.openChannel("exec");
        channel.setCommand(command);
    
    //      channel.setInputStream(System.in);
    //      channel.setOutputStream(System.out);
    //      InputStream in=channel.getInputStream();
    
        BufferedReader in = new BufferedReader(new InputStreamReader(channel.getInputStream()));
        channel.connect();
        String msg;
        while((msg = in.readLine()) != null){
            System.out.println(msg);
        }
        channel.disconnect();
        session.disconnect();
    }
    

    Linux服务器免密登录生成的id_rsa我拷贝一份到了windows,所以路径为"C:\\Users\\yutao\\.ssh\\id_rsa",如果代码执行在Linux环境,可以直接设置id_rsa路径/root/.ssh/id_rsa。测试通过,完事!

    相关文章

      网友评论

          本文标题:工具1:Java远程、本地(免密/非免密)环境执行linux的命

          本文链接:https://www.haomeiwen.com/subject/dbakbqtx.html