java shell文件_JAVA生成Shell文件并执行

本文介绍了一种使用JAVA程序生成Shell脚本的方法,并演示了如何执行该脚本。具体实现了通过JAVA代码创建Shell文件,包括设置文件权限,以及执行创建后的Shell脚本。

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

JAVA生成Shell文件并执行

最近有个奇怪的需求,创建RabbitMq用户,但是不能通过Rabbitmq的管理页面进行添加用户。Rabbitmq的管理页面对外的接口也没有发现添加用户的功能。只能出此下策。

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileWriter;

import java.io.InputStreamReader;

public class ShellUtil {

//创建shell

public static void createShell(String path, String... strs) throws Exception {

if (strs == null) {

System.out.println("strs is null");

return;

}

File sh = new File(path);

if (sh.exists()) {

sh.delete();

}

sh.createNewFile();

sh.setExecutable(true);

FileWriter fw = new FileWriter(sh);

BufferedWriter bf = new BufferedWriter(fw);

for (int i = 0; i < strs.length; i++) {

bf.write(strs[i]);

if (i < strs.length - 1) {

bf.newLine();

}

}

bf.flush();

bf.close();

}

//执行shell

public static String runShell(String shpath) throws Exception {

if (shpath == null || shpath.equals("")) {

return "shpath is empty";

}

Process ps = Runtime.getRuntime().exec(shpath);

ps.waitFor();

BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));

StringBuffer sb = new StringBuffer();

String line;

while ((line = br.readLine()) != null) {

sb.append(line).append("\n");

}

String result = sb.toString();

return result;

}

//测试效果

public static void main(String[] args) {

//文件存放路径

String path = "/home/xxx/java.sh";

//执行的脚本,一个字符串就是一行。

String[] strs = { "cp aaa.sh aaa2.sh" };

try {

ShellUtil.createShell(path, strs);

String result = ShellUtil.runShell(path);

System.out.println(result);

} catch (Exception e) {

e.printStackTrace();

}

}

}

自测可用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值