通过Java代码执行Shell命令
-
需求
在实际工作中,总会有些时候需要我们通过java代码通过远程连接去linux服务器上面执行一些shell命令,包括一些集群的状态管理,执行任务,集群的可视化界面操作等等,所以我们可以通过java代码来执行linux服务器的shell命令
为了解决上述问题,google公司给提出了对应的解决方案,开源出来了一个jar包叫做 sshxcute,通过这个jar包我们可以通过java代码,非常便捷的操作我们的linux服务器
项目下载地址:https://code.google.com/archive/p/sshxcute/
使用说明:https://www.ibm.com/developerworks/cn/opensource/os-sshxcute/
-
创建maven的java工程并导入jar包
先将sshxcute导入
在pom.xml中插入<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.2</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*/RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
-
开发测试用例
package cn.itcate.sshxcute; import com.jcraft.jsch.JSchException;
import net.neoremind.sshxcute.core.ConnBean;
import net.neoremind.sshxcute.core.SSHExec;
import net.neoremind.sshxcute.exception.TaskExecFailException;
import net.neoremind.sshxcute.task.impl.ExecCommand; public class XcuteExcute {
public static void main(String[] args) throws TaskExecFailException, JSchException {
ConnBean connBean = new ConnBean("192.168.0.30", "root", "zz140412.");
// 获取SSHExec用于执行Shell命令
SSHExec sshExec = SSHExec.getInstance(connBean);
// 连接linux服务器
sshExec.connect(); /*
CustomTask是一个抽象类
获取抽象类的两种方式:
一种是找子类
另一种是找抽象类有没有提供方法返回其本身
*/
ExecCommand execCommand = new ExecCommand("echo 'shut up' >> /export/servers/helloworld.txt"); // 执行linux命令
sshExec.exec(execCommand); //断开连接
sshExec.disconnect();
}
}