java如何执行远程服务器上的.sh文件

Python012

java如何执行远程服务器上的.sh文件,第1张

你可以使用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等操作

}

可以用Process 去调用shell脚本,demo如下

 String shellpath="/home/test/aa.sh"

 Process ps = Runtime.getRuntime().exec(shellpath)