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

Python05

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等操作

}

//创建一个ftpclient对象

FTPClient fc=new FTPClient()

//创建连接

fc.connect("ip地址", 端口号)

//登录

fc.login("用户名","密码")

//校验登陆

reply = fc.getReplyCode()

if (!FTPReply.isPositiveCompletion(reply)) {

fc.disconnect()

}           

//切换到指定地址

fc.changeWorkingDirectory("地址")

//获取该目录下的所有文件

FTPFile[] fs=fc.listFiles()

for(FTPFile ff:fs){

  System.out.println(ff.getName())

}

//注销退出

fc.logout()