java 远程调用shell脚本demo
来源:互联网 发布:python 调用 go 编辑:程序博客网 时间:2024/06/05 13:34
首先在远程服务器上编写一个测试脚本test.sh,并赋予可执行权限:chmod +x test.sh
#!/bin/bashecho 'test22'echo $1
$1是脚本传进来的第一个参数,我们控制台打印一下这个参数
新建maven项目,添加依赖:
<dependency><groupId>org.jvnet.hudson</groupId><artifactId>ganymed-ssh2</artifactId><version>build210-hudson-1</version></dependency>
编写一个工具类:
package com.xj.runshell;import java.io.IOException;import java.io.InputStream;import java.nio.charset.Charset;import ch.ethz.ssh2.Connection;import ch.ethz.ssh2.Session;public class RemoteShellTool {private Connection conn;private String ipAddr;private String charset = Charset.defaultCharset().toString();private String userName;private String password;public RemoteShellTool(String ipAddr, String userName, String password,String charset) {this.ipAddr = ipAddr;this.userName = userName;this.password = password;if (charset != null) {this.charset = charset;}}public boolean login() throws IOException {conn = new Connection(ipAddr);conn.connect(); // 连接return conn.authenticateWithPassword(userName, password); // 认证}public String exec(String cmds) {InputStream in = null;String result = "";try {if (this.login()) {Session session = conn.openSession(); // 打开一个会话session.execCommand(cmds);in = session.getStdout();result = this.processStdout(in, this.charset);session.close();conn.close();}} catch (IOException e1) {e1.printStackTrace();}return result;}public String processStdout(InputStream in, String charset) {byte[] buf = new byte[1024];StringBuffer sb = new StringBuffer();try {while (in.read(buf) != -1) {sb.append(new String(buf, charset));}} catch (IOException e) {e.printStackTrace();}return sb.toString();}/** * @param args */public static void main(String[] args) {RemoteShellTool tool = new RemoteShellTool("192.168.27.41", "hadoop","hadoop", "utf-8");String result = tool.exec("./test.sh xiaojun");System.out.print(result);}}
main函数中执行了./test.sh xiaojun这个命令,控制台打印出:
test22
xiaojun
这个简单的远程调用shell demo就算完了。
1 0
- java 远程调用shell脚本demo
- Java调用远程Shell脚本
- Java调用远程Shell脚本
- java 远程调用shell脚本
- java远程调用shell脚本
- java远程调用shell脚本
- ZZ Java远程调用shell脚本
- Java调用远程Shell脚本(待验证)
- windows下java远程调用shell脚本
- Java程序调用远程Shell脚本
- java怎么调用远程服务器中的Shell脚本 一
- java怎么调用远程服务器上的shell脚本 二参数调用远程
- java调用Shell脚本
- java调用Shell脚本
- JAVA 调用shell脚本
- Java 调用Shell脚本
- shell脚本调用java
- Java调用shell脚本
- Spring jdbcTemplat 写入BLOB数据为空
- 设计模式之工厂模式
- jQuery -> 使用andSelf()来包含之前的选择集
- 解决ant打包时有依赖工程(library)的方法
- 广州让同行望尘莫及的PHP培训机构
- java 远程调用shell脚本demo
- 【js设计模式笔记---组合模式】
- 新浪微博的demo
- 位域结构体的定义示例及其与联合体的定义使用
- 数组和链表
- 对日外包,如何提升自身技术水平?
- 2048电脑版
- 互联网报告:众多路由器存泄密后门
- WPF—— ListBox的使用