JAVA执行Shell命令

    基于JAVA执行shell指令,通常的代码范例为:

Process process = Runtime.getRuntime().exec("jps -v");
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
while (true) {
    String line = reader.readLine();
    if(line == null) {
        break;
    }
    System.out.println(line);
}
process.destroy();
reader.close();

 

    这么执行并没有太大的问题,但是如果希望它执行“多个指令”,上述方式总是获取不到信息,无信息输出,比如执行“jps -v | grep AppMain | awk ${print $2}”。

    徘徊了很久,后来通过使用:

process.getErrorStream();

 

    发现打印出来一些信息,提示的内容大概是指令的参数集不合法。归因于我们使用的方式不对,因为runtime.exec()方法不能执行多个指令。所以我们需要换一种比较标准的方式:

String[] command = {"ssh","127.0.0.1","ps","-ef","|","grep","java"};
ProcessBuilder pb = new ProcessBuilder();
pb.command(command);
//very important,if error,message will output too.
pb.redirectErrorStream(true);
Process process = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
while (true) {
    String line = reader.readLine();
    if(line == null) {
        break;
    }
    System.out.println(line);
}
process.destroy();
reader.close();

 

JAVA执行shell命令小工具 NULL 博文链接:https://qindongliang.iteye.com/blog/2072760 立即下载

相关推荐

CentOS7.9 安装 ImageMagick,图片转换为HEIC图像格式

由于ImageMagick7以下不支持heic等图片格式,所以重新安装了ImageMagick7.1版本支持heic格式,在网上找了很多资料,归纳总结并写此文章记录一下。在Linux(CentOS7.9)上安装ImageMagick7.1.1-38。

shmily_i的博客 1940

Java执行shell命令

java执行shell命令 1.导入依赖 <dependency> <groupId>ch.ethz.ganymed</groupId> <artifactId>ganymed-ssh2</artifactId> <version>build210</version> </dependency>

sunrj_niu的博客 7177

Matlab实现POD本征正交分解数据降维模型

近年来,随着大数据时代的到来,各种复杂的工程问题产生了海量的高维数据,如何有效降维、提取数据中的关键信息成为了众多领域中的重要问题。在传统的数据降维方法中,PCTFA(主成分分析)是一种典型的统计方法,然而对于流体动力学等非线性问题,PCTFA在处理时可能失去部分物理意义,难以捕捉到系统的复杂性。在降维过程中,POD提取的主要特征通常是一组复杂的正交基函数,如何将这些结果有效地转化为直观且易于理解的物理意义,特别是在实际应用中,对该特征的理解和分析,依然是一个重要的课题。本项目的扩展性也得到了有效体现。

优质创作者: 人工智能技术领域 对于有一定基础的 MATLAB和Python带具体需求都可以详谈 MATLAB和Python可以提供代码调试服务加油 谢谢 你的鼓励是我前行的动力 谢谢支持 加油 谢谢 1216

使用 Java 执行本地 Shell 命令的工具类:RuntimeUtil

RuntimeUtil 工具类提供了在 Java 中执行本地 Shell 命令的便捷方法。如果你在开发中需要频繁地执行本地命令,这个工具类将会是一个非常有用的辅助工具。

分享关于Java编程、数据库管理和信息安全方面的最佳实践 1647

SRRC型号核准的模块豁免规则解析——如何利用完整型模块简化设备认证流程

本文详细解析了SRRC型号核准中模块豁免规则的应用,重点介绍了完整型模块的技术定义、豁免条件及实际应用场景。通过合理利用完整型模块,企业可显著简化设备认证流程,缩短上市周期并降低成本。文章还提供了模块选型指南和常见问题解决方案,帮助工程师高效应对SRRC认证挑战。

weixin_29306011的博客 933

flink新版本无bat启动文件的解决办法

flink

6 4932

java连接linux服务器执行shell命令(框架分析+推荐)

java连接linux服务器执行shell命令(框架分析+推荐) 一、分类+连接方式 程序打成jar包,在本地服务器上执行shell命令。这种使用MyRuntimeUtil工具类 java程序远程linux服务器有两个框架分别是:jsch与ganymed-ssh2框架**。**推荐使用jsch框架因为ganymed-ssh2框架不支持麒麟服务器的连接原因是openssl版本过高,ganymed-ssh框架不维护了所以不支持。 二、执行本地的shell命令 <dependency>

飞奔的屎壳郎 1万+

图像算法中的 Blob 分析

在计算机视觉中,Blob 可以理解为在图像中具有相似性质(如颜色、亮度等)的像素群体。Blob 通常用作基本单元,在图像分析和处理任务中能够提取出有意义的特征。

m0_44975814的博客 2483

如何从Java执行Shell命令

在Java中,我们可以使用ProcessBuilder或Runtime.getRuntime().exec来执行外部shell命令: 1. ProcessBuilder ProcessBuilder processBuilder = new ProcessBuilder(); // -- Linux -- // Run a shell command processB...

一名可爱的技术搬运工 7955

别让 Claude Code 一直问你“能不能执行“:权限配置完全指南

Claude Code 提供了一套精细的权限配置机制,配置好权限设置,可以提速不少。这个小技巧需要掌握一下。

沐风 3840

注意力机制与经典 CV 网络:PyTorch 实现与实战

注意力机制(SE/空间/CBAM/Non-Local)通过权重重标定让模型聚焦关键特征,经典 CNN(ResNet/DenseNet/FPN)提供了深层网络、特征复用和多尺度融合的基础骨架。建议先在 ResNet 上插入 SE 模块(通道注意力)做基线实验,再根据任务类型引入空间注意力(分割任务)或非局部注意力(视频任务)。CIFAR-10 数据集适合快速验证注意力模块的有效性,迁移到更大数据集时保持相同的结构设计思路即可。

FJN110的博客 62

java 执行shell命令

import java.io.BufferedReader; import java.io.InputStreamReader; public class shell { public static String executeCommand(String command) { StringBuffer output = new StringBuffer();

duhaomin的专栏 1447

YOLOv8-COCO指标转换

本文介绍了将YOLO格式数据集转换为COCO格式并评估模型性能的完整流程。首先需将YOLO格式的标注数据转换为COCO格式,通过修改classes、image_path等参数适配不同数据集。然后使用YOLO模型对验证集进行预测并保存结果为JSON格式。最后通过比较预测结果和转换后的COCO标注文件,使用COCO官方评估指标和TIDE工具进行性能分析,生成包含AP、AR等指标的报告及错误分析图表。整个过程实现了从数据准备到模型评估的完整闭环,为计算机视觉任务提供标准化的性能评估方案。

FJN110的博客 402

Android 用java语言执行Shell命令

最近项目中需要用到java语言来执行shell命令,在网上查了资料, 把自己在项目里用到的命令整理成了工具类开放给大家,希望对大家有用。功能不全,后期我会慢慢添加整合。                    public class ShellUtils { public static final String COMMAND_SU = "su"; public static f

ss8860524的博客 9713

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

Java执行本地Shell命令以及远程Shell命令

我们可以使用Java来执行本地Shell命令甚至是远程主机上的Shell命令,并获取其标准输出、异常输出、执行结果码。 首先,访问远程主机需要加入一下maven支持: <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.55</version> </dependency>

hushukang的博客 914

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

Java远程执行Shell命令

Java远程执行Shell命令 Jar包:ganymed-ssh2-build210.jar 下载地址:Ganymed SSH-2 for Java package cn.liusd; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.Inpu...

白日梦的博客 814

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

java执行shell命令

java 执行shell命令 /** * 运行shell脚本 * @param shell 需要运行的shell脚本 */ public static void execShell(String shell){ try { Runtime.getRuntime().exec(shell); } catch (Exception e) { e.printStackTrace(); .

weixin_38011805的博客 2765

Java JSch 远程执行 Shell 命令

背景 项目需求,需要远程 ssh 登录到某个节点执行 shell 命令来完成任务。对于这种需求,如果不用 java 程序,直接 linux 的 ssh 命令就可以完成,但是在编码到程序中时需要相关的程序包来完成,本文主要介绍在 java 中如何使用 JSch 包实现 ssh 远程连接并执行命令。 JSch 简介 JSch 是Java Secure Channel的缩写。JSch是一个SSH2的纯Java实现。它允许你连接到一个SSH服务器,并且可以使用端口转发,X11转发,文件传输等,当然你也可以集成它的功

qhh0205 1万+

利用shell命令执行Java_Java代码执行shell命令的实现

本文描述两种方式使用java代码执行shell命令,首先使用Runtime类调用exce方法,其次使用ProcessBuilder实例实现更灵活的方式。1. 环境准备执行shell命令之前,我们需要获取jvm底层操作系统,同时定义通用消费流的类。1.1. 操作系统依赖在创建进场执行shell命令之前,我们需要获取jvm运行在具体哪个操作系统之上。因为Windows执行shell命令是cmd.exe...

weixin_35832025的博客 1680

java调用shell命令并返回执行结果

Java调用shell脚本或命令时,可使用下面的两种方式: 1、Runtime.getRuntime().exec(); 2、通过ProcessBuilder进行调度。 第一种方式比较直接,具体使用方式见https://blog.youkuaiyun.com/arkblue/article/details/7897396 由于在使用过程中,涉及到shell命令的字符串和数组形式,以及权限问题、同时调用多条shell命令等,这时候第二种方式就比较好用了,具体使用方式和代码如下: import java.io.B

YoungLittleT的博客 5264

Java代码执行shell命令

Java代码执行shell命令 本文描述两种方式使用java代码执行shell命令,首先使用Runtime类调用exce方法,其次使用ProcessBuilder实例实现更灵活的方式。 1. 环境准备 执行shell命令之前,我们需要获取jvm底层操作系统,同时定义通用消费流的类。 1.1. 操作系统依赖 在创建进场执行shell命令之前,我们需要获取jvm运行在具体哪个操作系统之上。因为Wind...

neweastsun的专栏 5260

java执行shell命令返回值为空

shell命令相关学习资料:https://edu.51cto.com/video/3832.htmlJava执行Shell命令并返回空值的实现指南 作为一名经验丰富的开发者,我经常被问到如何使用Java执行Shell命令并获取返回值。对于刚入行的小白来说,这可能是一个相对复杂的问题。但是不用担心,我会一步步教你如何实现...

weixin_36364044的博客 203

java shell 异步执行_Java代码实现执行shell命令

publicclassShellUtil {publicString run(String cmd) {Runtime runtime=Runtime.getRuntime();StringBuffer b=newStringBuffer();BufferedReader br= null;String sys= System.getProperties().getProperty("os.na...

weixin_29959549的博客 643
上一篇: logback日志与MDC机制
下一篇: nginx/tomcat日志格式规范
iteye_19607
博客等级 码龄8年 34粉丝 198原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值