java执行shell命令

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工程并导入jar包

由于这个jar包没有maven坐标,所以需要我们手动导入并添加到工程的build path当中去

下载地址:https://code.google.com/archive/p/sshxcute/downloads

第二步:编写实例

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 test {
    public static void main(String[] args) throws TaskExecFailException {
        ConnBean connBean = new ConnBean("192.168.52.100", "root", "123456");
        SSHExec instance = SSHExec.getInstance(connBean);
        instance.connect();
        ExecCommand execCommand = new ExecCommand("echo 'hello world'");
        instance.exec(execCommand);
        instance.disconnect();
    }
}

控制台输出:

SSHExec initializing ...
Session initialized and associated with user credential 123456
SSHExec initialized successfully
SSHExec trying to connect root@192.168.52.100
SSH connection established
Command is echo 'hello world'
Connection channel established succesfully
Start to run command
hello world

Connection channel closed
Check if exec success or not ... 
Execute successfully for command: echo 'hello world'
Connection channel disconnect
SSH connection shutdown

Process finished with exit code 0

你可能感兴趣的:(shell)