java 执行shell语句 shell 执行oracle语句

java 执行shell语句 shell 执行oracle语句,第1张

怎样在java代码中调用执行shell脚本

// 用法:Runtime.getRuntime.exec("命令")

String shpath="/test/test.sh"   //程序路径

Process process =null

String mand1 = “chmod 777 ” + shpath

try {

Runtime.getRuntime.exec(mand1 ).waitFor

} catch (IOException e1) {

e1.printStackTrace

}catch (InterruptedException e) {

e.printStackTrace

}

String var="201102"  /参数

String mand2 = “/bin/sh ” + shpath + ” ” + var

Runtime.getRuntime.exec(mand2).waitFor

如何在java中执行shell脚本

// 用法:Runtime.getRuntime.exec("命令")

String shpath="/test/test.sh"//程序路径

Process process =null

String mand1 = “chmod 777 ” + shpath

try {

Runtime.getRuntime.exec(mand1 ).waitFor

} catch (IOException e1) {

e1.printStackTrace

}catch (InterruptedException e) {

e.printStackTrace

}

String var="201102"/参数

String mand2 = “/bin/sh ” + shpath + ” ” + var

Runtime.getRuntime.exec(mand2).waitFor

java怎么调用shell脚本

String cmdstring = "chmod a+x test.sh"

Process proc = Runtime.getRuntime.exec(cmdstring)

proc.waitFor //阻塞,直到上述命令执行完

cmdstring = "bash test.sh" //这里也可以是ksh等

proc = Runtime.getRuntime.exec(cmdstring)

// 注意下面的 *** 作

string ls_1

BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(proc.getInputStream)

while 祥配铅( (ls_1=bufferedReader.readLine) != null)

bufferedReader.close

proc.waitFor

为什谨好么要有上面那段 *** 作呢?

原因是:可执行程序的输出可能会比较多,而运行窗口的输出缓冲区有限,会造成waitFor一直阻塞。解决的办法是,利用Java提供的Process类提供的getInputStream,getErrorStream方法让Java虚拟机截获被调用程序的标准输出、错误输出,在waitfor命令之前读掉输出缓冲区中的内容。

如何在java中执行shell脚本

在java中执行shell脚本 用卖碧法:Runtime.getRuntime.exec("命令")

String shpath="/test/test.sh"//程序路径

Process process =null

String mand1 = “chmod 777 ” + shpath

try {

Runtime.getRuntime.exec(mand1 ).waitFor

} catch (IOException e1) {

e1.printStackTrace

}catch (InterruptedException e) {

e.printStackTrace

}

String var="201102"/参数

String mand2 = “/bin/sh ” + shpath + ” ” + var

Runtime.getRuntime.exec(mand2).waitFor

标签:作文经典 上一篇:一个人带头的成语 一个猪头带头的成语 下一篇:描写长城的语句 描写长城美景的语句

怎么通过java去调用并执行shell脚本以及问题总结

以下是我在公司项目中实际应用到的:

/**

* 执行系统命令

* @time 2016/10/17$ 17:05$

*/

public final class SystemmandExecutor {

protected static Logger logger = LoggerFactory.getLogger(ShareDiskFileUtils.class)

public static final boolean isWindow

public static final boolean isLinux

static {

String osname = System.getProperty("os.name").toLowerCase

isWindow = osname.contains("win")

isLinux = osname.contains("linux")

logger.info("系统环境: " + (isLinux ? "Linux" : "Window"))

}

/**

* 执行命令

*/

public static Process executemand(String mand) throws IOException, InterruptedException {

logger.info("执行系统命令: " + mand)

Process process = Runtime.getRuntime.exec(getCmdArray(mand))

new StreamPrinter(process.getInputStream, logger).start

new StreamPrinter(process.getErrorStream, logger).start

process.waitFor

return process

}

/**

* 这个非常重要, 如果你直接执行mand,会出现一些问题,如果参数中包含一些空格,", ' 之类的特殊字符,将会执行失败,

*/

private static String[] getCmdArray(String mand) {

if (isWindow) {

return new String[]{"cmd", "/c", mand}

}

if (isLinux) {

return new String[]{"/bin/sh", "-c", mand}

}

return new String[]{"cmd", "/c", mand}

}

}

怎么通过java去调用并执行shell脚本以及问题总结

// 用法:Runtime.getRuntime.exec("命令")

String shpath="/test/test.sh"//程序路径

Process process =null

String mand1 = “chmod 777 ” + shpath

try {

Runtime.getRuntime.exec(mand1 ).waitFor

} catch (IOException e1) {

e1.printStackTrace

}catch (InterruptedException e) {

e.printStackTrace

}

String var="201102"/参数

String mand2 = “/bin/sh ” + shpath + ” ” + var

Runtime.getRuntime.exec(mand2).waitFor

java怎么执行shell脚本

如果shell脚本和java程序运行在不同的服务器上,可以使用远程执行Linux命令执行包,使用ssh2协议连接远程服务器,并发送执行命令就行了,ganymed.ssh2相关mave配置如下,你可以自己百度搜索相关资料。

如果shell脚本和java程序在同一台服务器上,

这里不得不提到java的process类了。

process这个类是一个抽象类,封装了一个进程(你在调用linux的命令或者shell脚本就是为了执行一个在linux下执行的程序,所以应该使用process类)。

process类提供了执行从进程输入,执行输出到进程,等待进程完成,检查进程的推出状态,以及shut down掉进程。

.ganymed.ssh2

ganymed-ssh2-build

210

本地执行命令代码如下:

String shpath="/test/test.sh"   //程序路径

Process process =null

String mand1 = “chmod 777 ” + shpath

process = Runtime.getRuntime.exec(mand1)

process.waitFor

如何在java中执行shell脚本

1、最常用的方法:

Process p = Runtime.getRuntime.exec(SHELL_FILE_DIR + RUNNING_SHELL_FILE +

" "+param1+" "+param2+" "+param3)

int runnngStatus = p.waitFor

2、通过ProcessBuilder进行调度,这种方法比较直观,而且参数的设置也比较方便:

ProcessBuilder pb = new ProcessBuilder("./" + RUNNING_SHELL_FILE, param1,

param2, param3)

pb.directory(new File(SHELL_FILE_DIR))

int runningStatus = 0

String s = null

try {

Process p = pb.start

try {

runningStatus = p.waitFor

} catch (InterruptedException e) {

e.printStackTrace

}

} catch (IOException e) {

e.printStackTrace

}

if (runningStatus != 0) {

}

return

参数说明:

RUNNING_SHELL_FILE:要运行的脚本

SHELL_FILE_DIR:要运行的脚本所在的目录; 当然你也可以把要运行的脚本写成全路径。

runningStatus:运行状态,0标识正常。 详细可以看java文档。

param1, param2, param3:可以在RUNNING_SHELL_FILE脚本中直接通过1,1,2,$3分别拿到的参数。

怎么通过java去调用并执行shell脚本以及问题总结

对于第一个问题:java抓取,并且把结果打包。那么比较直接的做法就是,java接收各种消息(db,metaq等等),然后借助于jstorm集群进行调度和抓取。

最后把抓取的结果保存到一个文件中,并且通过调用shell打包, 回传。 也许有同学会问,

为什么不直接把java调用odps直接保存文件,答案是,我们的集群不是hz集群,直接上传odps速度很有问题,因此先打包比较合适。(这里不纠结设计了,我们回到正题)

java调用shell的方法

通过ProcessBuilder进行调度

这种方法比较直观,而且参数的设置也比较方便, 比如我在实践中的代码(我隐藏了部分业务代码):

ProcessBuilderpb = new ProcessBuilder("./" + RUNNING_SHELL_FILE, param1,

param2, param3)

pb.directory(new File(SHELL_FILE_DIR))

int runningStatus = 0

String s = null

try {

Process p = pb.start

try {

runningStatus = p.waitFor

} catch (InterruptedException e) {

}

} catch (IOException e) {

}

if (runningStatus != 0) {

}

return

这里有必要解释一下几个参数:

RUNNING_SHELL_FILE:要运行的脚本

SHELL_FILE_DIR:要运行的脚本所在的目录; 当然你也可以把要运行的脚本写成全路径。

runningStatus:运行状态,0标识正常。 详细可以看java文档。

param1, param2, param3:可以在RUNNING_SHELL_FILE脚本中直接通过1,2,$3分别拿到的参数。

直接通过系统Runtime执行shell

这个方法比较暴力,也比较常用, 代码如下:

p = Runtime.getRuntime.exec(SHELL_FILE_DIR + RUNNING_SHELL_FILE + " "+param1+" "+param2+" "+param3)

p.waitFor

我们发现,通过Runtime的方式并没有builder那么方便,特别是参数方面,必须自己加空格分开,因为exec会把整个字符串作为shell运行。

可能存在的问题以及解决方法

如果你觉得通过上面就能满足你的需求,那么可能是要碰壁了。你会遇到以下情况。

没权限运行

这个情况我们团队的朱东方就遇到了, 在做DTS迁移的过程中,要执行包里面的shell脚本, 解压出来了之后,发现执行不了。 那么就按照上面的方法授权吧

java进行一直等待shell返回

这个问题估计更加经常遇到。 原因是, shell脚本中有echo或者print输出, 导致缓冲区被用完了! 为了避免这种情况, 一定要把缓冲区读一下, 好处就是,可以对shell的具体运行状态进行log出来。 比如上面我的例子中我会变成:

ProcessBuilderpb = new ProcessBuilder("./" + RUNNING_SHELL_FILE, keyword.trim,

taskId.toString, fileName)

pb.directory(new File(CASPERJS_FILE_DIR))

int runningStatus = 0

String s = null

try {

Process p = pb.start

BufferedReaderstdInput = new BufferedReader(new InputStreamReader(p.getInputStream))

BufferedReaderstdError = new BufferedReader(new InputStreamReader(p.getErrorStream))

while ((s = stdInput.readLine) != null) {

LOG.error(s)

}

while ((s = stdError.readLine) != null) {

LOG.error(s)

}

try {

runningStatus = p.waitFor

} catch (InterruptedException e) {

}

记得在start之后, waitFor()之前把缓冲区读出来打log, 就可以看到你的shell为什么会没有按照预期运行。 这个还有一个好处是,可以读shell里面输出的结果, 方便java代码进一步 *** 作。

也许你还会遇到这个问题,明明手工可以运行的命令,java调用的shell中某一些命令居然不能执行,报错:命令不存在!

比如我在使用casperjs的时候,手工去执行shell明明是可以执行的,但是java调用的时候,发现总是出错。

通过读取缓冲区就能发现错误日志了。 我发现即便自己把安装的casperjs的bin已经加入了path中(/etc/profile,

各种bashrc中)还不够。 比如:

exportNODE_HOME="/home/admin/node"

exportCASPERJS_HOME="/home/admin/casperjs"

exportPHANTOMJS_HOME="/home/admin/phantomjs"

exportPATH=$PATH:$JAVA_HOME/bin:/root/bin:$NODE_HOME/bin:$CASPERJS_HOME/bin:$PHANTOMJS_HOME/bin

原来是因为java在调用shell的时候,默认用的是系统的/bin/下的指令。特别是你用root权限运行的时候。 这时候,你要在/bin下加软链了。针对我上面的例子,就要在/bin下加软链:

ln -s /home/admin/casperjs/bin/casperjscasperjs

ln -s /home/admin/node/bin/nodenode

ln -s /home/admin/phantomjs/bin/phantomjsphantomjs

这样,问题就可以解决了。

如果是通过java调用shell进行打包,那么要注意路径的问题了

因为shell里面tar的压缩和解压可不能直接写:

tar -zcf /home/admin/data/result.tar.gz /home/admin/data/result

直接给你报错,因为tar的压缩源必须到路径下面, 因此可以写成

tar -zcf /home/admin/data/result.tar.gz -C /home/admin/data/ result

如果我的shell是在jar包中怎么办?

答案是:解压出来。再按照上面指示进行 *** 作。(1)找到路径

String jarPath = findClassJarPath(ClassLoaderUtil.class)

JarFiletopLevelJarFile = null

try {

topLevelJarFile = new JarFile(jarPath)

Enumeration entries = topLevelJarFile.entries

while (entries.hasMoreElements) {

JarEntryentry = entries.nextElement

if (!entry.isDirectory entry.getName.endsWith(".sh")) {

对你的shell文件进行处理

}

}

对文件处理的方法就简单了,直接touch一个临时文件,然后把数据流写入,代码:

FileUtils.touch(tempjline)

tempjline.deleteOnExit

FileOutputStreamfos = new FileOutputStream(tempjline)

IOUtils.copy(ClassLoaderUtil.class.getResourceAsStream(r), fos)

fos.close

如何在java中执行shell脚本

首先你可以百度搜一下 java Process 类的用法,很多博文都有讲解。

另外我补充一下我再使用过程中的一些点:

process = Runtime.getRuntime.exec(new String[]{"/bin/sh","-c",shellContext})

其中 shellContext 是shel脚本字符串

这句提交的时候,不少博文 exec中是直接提交shellContext。

但是对于一些场景不适用,取出来数据跟直接运行shell脚本有差异,可以改成我这种写法。

标签:作文经典 上一篇:一个人带头的成语 一个猪头带头的成语 下一篇:描写长城的语句 描写长城美景的语句

你可以使用JSch

JSch全称是“Java Secure Channel”

是SSH2的一个纯Java实现。它允许你连接到一个sshd 服务器,使用端口转发,X11转发,文件传输等等。同时也是支持执行命令;

以下是大概运行的代码,只是提供大致思路,可以去查官方API和demo

import com.jcraft.jsch.ChannelExec

import com.jcraft.jsch.ChannelSftp

import com.jcraft.jsch.ChannelSftp.LsEntry

import com.jcraft.jsch.JSch

import com.jcraft.jsch.JSchException

import com.jcraft.jsch.Session

import com.jcraft.jsch.SftpATTRS

import com.jcraft.jsch.SftpException

.......

try{

Session session = new 指培颤JSch().getSession(user, ip, port)

session.setPassword(pwd)

session.setConfig("StrictHostKeyChecking", "no")

session.setConfig("userauth.gssapi-with-mic", "no")

session.connect()

ChannelExec exec = (ChannelExec) session.openChannel("exec")

exec.setCommand("ifconfig")//这里是你要执唯败行的命令,部分命令中敏不支持,具体自己执行下

ByteArrayOutputStream bao = new ByteArrayOutputStream()

exec.setOutputStream(bao)

ByteArrayOutputStream baerr = new ByteArrayOutputStream()

exec.setErrStream(baerr)

exec.connect()

while (!exec.isEOF())

String errmsg = new String(baerr.toByteArray(), "utf-8")

if (StringUtils.notNull(errmsg)) {

throw new RuntimeException(errmsg)

} else {

System.out.println(new String(bao.toByteArray(), "utf-8"))

}

}catch(Exception e){

    e.printStackTrace()

}finally{

    //关闭session等 *** 作

}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/tougao/12246226.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-22
下一篇 2023-05-22

发表评论

登录后才能评论

评论列表(0条)

保存