java远程登陆linux服务器,执行命令获取命令显示

来源:互联网 发布:python 列表推导式 编辑:程序博客网 时间:2024/04/26 05:52

项目需要用linux服务器A执行传输脚本(部署定时任务)到另一台linux服务器B,然后在B上执行该脚本实现拉取数据功能。然而蛋疼的是策略开放的服务器为C,C可以访问A,但是C不能直接访问B,所以,必须用C做中转,传文件到A,然后由A执行传输部署命令。

简单思路是A上用Runtime()获取本机linux运行环境,然后执行传输命令 scp……部署脚本传输到B后,再远程登录B,执行部署脚本。

简单执行代码如下,mark一下笔记。

远程登录服务器代码
public static void main(String[] args)    {    //服务器地址String hostname = "192.168.168.170";String username = "linux服务器_账户名";String password = "linux服务器_对应账户密码"; //连续命令用 && 连接 可以保证在同一目录下执行//String command=" cd admin  && cd paymentconfirm && ls  ";String command=" cd admin && ls";Connection conn=null;Session sess=null; try    {   conn = new Connection(hostname);  conn.connect();  boolean isAuthenticated = conn.authenticateWithPassword(username, password);    if (isAuthenticated == false)     throw new IOException("Authentication failed."); //调用一个方法执行命令execCommand(conn,sess,command);}         catch (IOException e)   {     e.printStackTrace(System.err); System.exit(2);    } finally{if(conn!=null){conn.close(); }}   }public static void execCommand(Connection conn,Session sess, String command) {BufferedReader br=null;InputStream stdout=null;try {sess = conn.openSession();sess.execCommand(command);System.out.println("Here is some information about the remote host:");   stdout = new StreamGobbler(sess.getStdout());  br = new BufferedReader(new InputStreamReader(stdout)); String line=null;while ((line=br.readLine())!=null){    //打印命令显示信息 此处为admin目录下执行ls的返回信息System.out.println(line);   }  System.out.println("ExitCode: " + sess.getExitStatus());  sess.close();    } catch (IOException e) {e.printStackTrace();}  finally{if(br!=null){try {br.close();} catch (IOException e) {e.printStackTrace();} }if(stdout!=null){try {stdout.close();} catch (IOException e) {e.printStackTrace();}}if(sess!=null){sess.close();}}       }
C上中转文件传输代码:

说明:前端使用ajax异步提交文件表单,(html5新性能),后台为SpringMVC,使用httpClient中转

 @RequestMapping("/接口名")    public void turnToSeven(HttpServletRequest request, HttpServletResponse response)    {        String url="A服务器上java项目接口名>>http://开头的全路径";        try{            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession()                    .getServletContext());            // 检查form中是否有enctype="multipart/form-data"            if (multipartResolver.isMultipart(request))            {                // 将request变成多部分request                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;                // 获取multiRequest 中所有的文件名                @SuppressWarnings("rawtypes")                Iterator iter = multiRequest.getFileNames();                // 如果目标路径文件夹不存在,则创建文件夹                List<MultipartFile> lsMults=new ArrayList<MultipartFile>();                while (iter.hasNext())                {                    logger.info("有文件");                   //一次解析文件值MultipartFile,然后挨个封装到post方法中                   MultipartFile file = multiRequest.getFile(iter.next().toString());                   lsMults.add(file);                }                if(null!=lsMults){                    logger.info("执行传输/反送回复");                    httpClientUploadFile(lsMults, url,response);                                    }            }        }catch(Exception e){            logger.error("上传文件bug:"+e);            e.printStackTrace();        }          }
    public  void httpClientUploadFile(List<MultipartFile> lsMults,String url,HttpServletResponse responseIn) {        CloseableHttpClient httpClient = HttpClients.createDefault();;        String result = "";                try {            logger.info("组建httpPost!");            HttpPost httpPost = new HttpPost(url);            logger.info("组建MultipartEntityBuilder!");            MultipartEntityBuilder builder = MultipartEntityBuilder.create();            //多文件上传            //去重标记,防止多文件参数名重复            Integer sign=0;            for (MultipartFile m : lsMults)            {                builder.addBinaryBody("file"+sign, m.getInputStream(), ContentType.MULTIPART_FORM_DATA, m.getOriginalFilename());// 文件流                builder.addTextBody("filename"+sign,m.getOriginalFilename());                sign++;            }            //类似浏览器表单提交,对应input的name和value            HttpEntity entity = builder.build();            logger.info("设置httppost的值,post请求的消息体!");            httpPost.setEntity(entity);            HttpResponse response = httpClient.execute(httpPost);// 执行提交             HttpEntity responseEntity = response.getEntity();            if (responseEntity != null) {                // 将响应内容转换为字符串                result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));            }        } catch (IOException e) {            logger.info("bug1:"+e);            e.printStackTrace();        } catch (Exception e) {            logger.info("bug2:"+e);            e.printStackTrace();        } finally {            try {                httpClient.close();            } catch (IOException e) {                logger.info("bug3:"+e);                 e.printStackTrace();            }        }        if(null!=result){            try            {                responseIn.getWriter().write(result);            } catch (IOException e)            {                logger.info("bug4:"+e);                e.printStackTrace();            }        }    }
RunTime获取本机linux运行环境,省略。




原创粉丝点击