Java执行Dos-Shell脚本
Java执行Dos-Shell脚本
相关参考内容原文地址:
1、介绍
在Linux中运行Java程序时,需要调用一些Shell命令和脚本。而Runtime.getRuntime().exec()方法给我们提供了这个功能,而且Runtime.getRuntime()给我们提供了以下几种exec()方法:
Process exec(String command)
在单独的进程中执行指定的字符串命令。
Process exec(String[] cmdarray)
在单独的进程中执行指定命令和变量。
Process exec(String[] cmdarray, String[] envp)
在指定环境的独立进程中执行指定命令和变量。
Process exec(String[] cmdarray, String[] envp, File dir)
在指定环境和工作目录的独立进程中执行指定的命令和变量。
Process exec(String command, String[] envp)
在指定环境的单独进程中执行指定的字符串命令。
Process exec(String command, String[] envp, File dir)
在有指定环境和工作目录的独立进程中执行指定的字符串命令。
如果参数中如果没有envp参数或设为null,表示调用命令将在当前程序执行的环境中执行;如果没有dir参数或设为null,表示调用命令将在当前程序执行的目录中执行,因此调用到其他目录中的文件和脚本最好使用绝对路径。
各个参数的含义:
- cmdarray: 包含所调用命令及其参数的数组。
- command: 一条指定的系统命令。
- envp: 字符串数组,其中每个元素的环境变量的设置格式为name=value;如果子进程应该继承当前进程的环境,则该参数为 null。
- dir: 子进程的工作目录;如果子进程应该继承当前进程的工作目录,则该参数为 null。
通过调用Process类的以下方法,得知调用操作是否正确执行:
abstract int waitFor()
导致当前线程等待,如有必要,一直要等到由该 Process 对象表示的进程已经终止。
2、调用shell脚本
2.1 获取键盘输入
BufferedReader reader = null;
try{
reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入IP:");
String ip = reader.readLine();
上述指令基本很常见:
- 创建读入器:BufferReader
- 将数据流载入BufferReader,即InputStreamReader
- 将系统输入载入InputStreamReader中
- 然后利用reader获取数据。
2.2 构建指令
shell运行脚本指令为 sh **.sh args。
#!/bin/sh
#根据进程名杀死进程
echo "This is a $call"
if [ $# -lt 2 ]
then echo "缺少参数:procedure_name和ip" exit 1
fi
echo "Kill the $1 process"
PROCESS=`ps -ef|grep $1|grep $2|grep -v grep|grep -v PPID|awk '{ print $2}'`
for i in $PROCESS
do echo "Kill the $1 process [ $i ]"
done
注意事项:
- shell脚本必须有执行权限,比如部署后chmod -R 777 /webapps
- shell文件,必须是UNIX格式,ANSI编码格式,否则容易出问题(可以用notepad++,编辑->文档格式转换,格式->转为ANSI格式(UNIX格式)
2.3 Java代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TestBash {
public static void main(String [] args){
BufferedReader reader = null;
try{
reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入IP:");
String ip = reader.readLine();
String bashCommand = "sh "+ "/usr/local/java/jdk1.8.0_121/lib/stopffmpeg.sh" + " ffmpeg " + ip;
// String bashCommand = "chmod 777 " + "/usr/local/java/jdk1.8.0_121/lib/stopffmpeg.sh" ;
// String bashCommand = "kill -9" + ip;
System.out.println(bashCommand);
Runtime runtime = Runtime.getRuntime();
Process pro = runtime.exec(bashCommand);
int status = pro.waitFor();
if (status != 0)
{
System.out.println("Failed to call shell's command ");
}
BufferedReader br = new BufferedReader(new InputStreamReader(pro.getInputStream()));
StringBuffer strbr = new StringBuffer();
String line;
while ((line = br.readLine())!= null)
{
strbr.append(line).append("\n");
}
String result = strbr.toString();
System.out.println(result);
}
catch (IOException ec)
{
ec.printStackTrace();
}
catch (InterruptedException ex){
ex.printStackTrace();
}
}
}
3、Java调用Shell并传入参数
public static void invokeShell(){
//方法1 执行字符串命令(各个参数1234之间需要有空格)
String path="sh /root/zpy/zpy.sh 1 2 3 4";
//方法2 在单独的进程中执行指定命令和变量。
//第一个变量是sh命令,第二个变量是需要执行的脚本路径,从第三个变量开始是我们要传到脚本里的参数。
String[] path=new String[]{"sh","/root/zpy/zpy.sh","1","2","3","4"};
try{
Runtime runtime = Runtime.getRuntime();
Process pro = runtime.exec(path);
int status = pro.waitFor();
if (status != 0)
{
System.out.println("Failed to call shell's command");
}
BufferedReader br = new BufferedReader(new InputStreamReader(pro.getInputStream()));
StringBuffer strbr = new StringBuffer();
String line;
while ((line = br.readLine())!= null)
{
strbr.append(line).append("\n");
}
String result = strbr.toString();
System.out.println(result);
}
catch (IOException ec)
{
ec.printStackTrace();
}
catch (InterruptedException ex){
ex.printStackTrace();
}
}
4、Java调用远程的Shell脚本
<!--调用远程服务器上的shell-->
<dependency>
<groupId>org.jvnet.hudson</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210-hudson-1</version>
</dependency>
/**
* 执行远程服务器上的shell脚本
* @param ip 服务器IP地址
* @param port 端口号
* @param name 登录用户名
* @param pwd 密码
* @param cmds shell命令
*/
public static void RemoteInvokeShell(String ip,int port,String name,String pwd,String cmds) {
Connection conn=null;
try {
conn = new Connection(ip,port);
conn.connect();
if (conn.authenticateWithPassword(name, pwd)) {
// Open a new {@link Session} on this connection
Session session = conn.openSession();
// Execute a command on the remote machine.
session.execCommand(cmds);
BufferedReader br = new BufferedReader(new InputStreamReader(session.getStdout()));
BufferedReader brErr = new BufferedReader(new InputStreamReader(session.getStderr()));
String line;
while ((line = br.readLine()) != null) {
logger.info("br={}", line);
}
while ((line = brErr.readLine()) != null) {
logger.info("brErr={}", line);
}
if (null != br) {
br.close();
}
if(null != brErr){
brErr.close();
}
session.waitForCondition(ChannelCondition.EXIT_STATUS, 0);
int ret = session.getExitStatus();
logger.info("getExitStatus:"+ ret);
} else {
logger.info("登录远程机器失败" + ip);
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.close();
}
}
}
public static void main(String[] args){
RemoteInvokeShell("192.168.11.xx",22,"xx","xx","sh /root/zpy/zpy.sh \"jj|aa|bb\"")//带有特殊符号的参数需要加上双引号
}
Java执行Dos-Shell脚本的更多相关文章
- java 调用bash shell脚本阻塞的小问题的解决
java 调用bash shell脚本阻塞的小问题的解决 背景 使用java实现的web端,web端相应用户的界面操作,使用java调用bash实现的shell脚本进行实际的操作,操作完成返回执行结 ...
- Java代码调用Shell脚本并传入参数实现DB2数据库表导出到文件
本文通过Java代码调用Shell脚本并传入参数实现DB2数据库表导出到文件,代码如下: import java.io.File; import java.io.IOException; import ...
- top 自动执行的shell脚本中,使用top -n 1 > log.txt, 上电自动执行,文件无输出
. 自动执行的shell脚本中,使用top -n > log.txt, 上电自动执行,文件无输出,使用一下命令解决: //usr/bin/top -d -n -b > log.txt 如果 ...
- 用java代码调用shell脚本执行sqoop将hive表中数据导出到mysql
1:创建shell脚本 touch sqoop_options.sh chmod 777 sqoop_options.sh 编辑文件 特地将执行map的个数设置为变量 测试 可以java代码传参数 ...
- Azkaban实战,Command类型单一job示例,任务中执行外部shell脚本,Command类型多job工作flow,HDFS操作任务,MapReduce任务,HIVE任务
本文转载自:https://blog.csdn.net/tototuzuoquan/article/details/73251616 1.Azkaban实战 Azkaba内置的任务类型支持comman ...
- Java如何调用shell脚本的
有些时候会碰到这样的场景:java的功能里面要嵌入一个功能点,这个功能是通过是shell脚本实现的.这种时候就需要Java对脚本调用的支持了. 测试环境 Ubuntu16.04 i3-6100,12G ...
- Linux centos开机执行JAR Shell脚本
Linux centos开机执行shell脚本 Linux centos开机执行 java jar 1.编写jar执行脚本 vim start.sh 加入如下内容(根据自己真实路径与数据进行编写) ...
- 批量复制及执行命令shell脚本
平时在处理一个或几个机器运行环境时,一个机器一个机器处理也能接受,但是如果是一批机器,几十或几百台,要是一台一台去安装环境,光是输入同一的命令,估计你自己都想吐,所有聪明的人会想一些偷懒的办法,确实可 ...
- 每秒执行一个shell脚本(转载)
上周迁移了一台服务器,发现其中一个项目的数据没有更新,查询原服务器的数据,数据有更新,并找到了rsync服务,从其他服务器传输数据,那么如何找到这台服务器?因为是从远程传输到本地,而且不是很频繁, ...
- [转]如何取得当前正在执行的shell脚本的绝对路径?
来源:http://sexywp.com/bash-how-to-get-the-basepath-of-current-running-script.htm 如题,一般我们写Shell脚本的时候,都 ...
随机推荐
- Java Tree 树 数据结构
说到树结构就不得不回顾 链表结构 https://www.cnblogs.com/easyidea/p/13371863.html 如果链表结构中再多一个指针会是什么情况? 是不是像树根一样,这就是 ...
- JVM个人总结一
看了深入理解JAVA虚拟机已经有一段时间了 发现很多东西如果不总结 脑子里总是没有一条线贯穿起来,也比较模糊混乱,所以还是有必要利用逻辑思维图总结下. JVM看了下 大致比较重要的分内存区域划分 ...
- CyclicBarrier(栅栏)的用法详解及与countDownLatch用法区别
CyclicBarrier适用于这样的情况:你希望创建一组任务,它们并行的执行工作,然后在进行下一步步骤之前等待,直至所有任务都完成,它使得所有的并行任务都将在删栏出列队,因此可以一致的向前移动. 当 ...
- 【linux】系统编程-5-线程
目录 前言 7. 线程 7.1 概念 7.2 创建线程 7.2.1 pthread_create() 7.3 设置线程属性 7.3.1 pthread_attr_init() 7.3.2 销毁一个线程 ...
- openbmc编译错误汇总,持续更新,建议收藏
本文汇总自己在编译openbmc时遇到的一些问题及解决思路,希望对有兴趣研究openbmc的同学有一些帮助. 项目地址:https://github.com/openbmc/openbmc 编译步骤: ...
- 杭电OJ2005---第几天?(c++)
Problem Description 给定一个日期,输出这个日期是该年的第几天. Input 输入数据有多组,每组占一行,数据格式为YYYY/MM/DD组成,具体参见sample input ,另外 ...
- 八:架构,搭建,WAF
WAF防护分析 什么是WAF应用 如何快速识别WAF 识别WAF对于安全测试的意义 CMS识别技术 源码获取技术 架构信息获取 站点搭建分析 搭建习惯-目录型站点 sti.blcu-bbs 目录型站点 ...
- Java 基于 mysql-connector-java 编写一个 JDBC 工具类
用到的 jar 包 jar包地址: mysql-connector-java-5.1.47.jar junit-4.13.jar Maven: <!-- mysql驱动 --> <d ...
- 【Python】简单的脚本,轻松批量修改文件名称
使用python脚本,批量修改文件夹名称 先创建一些没用的案例文件 import os #创建新文件夹 dir = os.makedirs('D:\\SomeThing\\testfile') #将文 ...
- 【ORA】ORA-39002,ORA-39070,ORA-29283, ORA-06512,ORA-29283解决办法
今天使用IMPDP导入的时候报了一个错误 ORA-39002: invalid operation ORA-39070: Unable to open the log file. ORA-2928 ...