java执行shell命令

本文介绍如何使用sshxcute库在Java中执行Linux服务器上的shell命令,包括库的引入、实例代码及控制台输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值