java(jsp)执行ssh命令,在远程执行shell命令

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将Linux虚拟机中shell执行命令的结果放到JSP上,您可以使用Java中的SSH库来连接远程Linux虚拟机并执行命令。其中,比较常用的SSH库有JSch和Apache Commons Net等。 以下是一个使用JSch库实现的示例代码片段: ```java <%@ page import="com.jcraft.jsch.*" %> <% String host = "your_host_name"; // Linux虚拟机的主机名或IP地址 String user = "your_user_name"; // 登录Linux虚拟机的用户名 String password = "your_password"; // 登录Linux虚拟机的密码 String command = "ls -l"; // 要执行命令 JSch jsch = new JSch(); Session session = jsch.getSession(user, host, 22); session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); ChannelExec channelExec = (ChannelExec) session.openChannel("exec"); channelExec.setCommand(command); channelExec.connect(); InputStream inputStream = channelExec.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; StringBuilder output = new StringBuilder(); while ((line = reader.readLine()) != null) { output.append(line + "\n"); } String result = output.toString(); channelExec.disconnect(); session.disconnect(); request.setAttribute("output", result); // 将输出结果存储在request对象中 %> <html> <head> <title>SSH Command Result</title> </head> <body> <pre><%= request.getAttribute("output") %></pre> // 在JSP页面上显示输出结果 </body> </html> ``` 请注意,上述示例中使用了`<pre>`标签来保留输出结果中的换行符和空格。另外,为了避免SSH连接时的安全校验问题,我们将`StrictHostKeyChecking`配置为`no`。在实际使用中,您应该进行更加严格的安全设置。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值