一条命令可以在linuxZ中执行为甚么不能用java代码执行

一条命令可以在linuxZ中执行为甚么不能用java代码执行,第1张

linux内核,听说过吗,就是Linux有自己系统封装的Api。java 是通过Api构建代码,虚拟机内部没有对应的API封装,只是简单的编译成机器语言,需要导入对应的jar包才可以执行

首先确保Linux开启sshd服务,并支持远程SSH连接。java程序使用jsch框架登录Linux,执行命令

protected void creation() throws Exception {

JSch jsch = new JSch()

session = jsch.getSession(userName, host, port)

session.setPassword(password)

Properties config = new Properties()

config.put("StrictHostKeyChecking", "no")

session.setConfig(config)

session.setTimeout(CONNECT_TIMEOUT)

session.setConfig("PreferredAuthentications", "password,keyboard-interactive")

session.setServerAliveInterval(1000 * 60 * 2)

session.connect()

}

public String sendCommand(String command) throws Exception {

if(!isConnected())

throw new JSchException("Session is not connected, command exec faild.")

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

ByteArrayOutputStream out = new ByteArrayOutputStream()

exec.setCommand(command)

exec.setOutputStream(out)

exec.setExtOutputStream(out)

exec.connect()

final Thread thread = new Thread() {

public void run() {

while(!exec.isEOF()) {

try { Thread.sleep(500L)} catch(Exception e) {}

}

}

}

thread.setDaemon(true)

thread.start()

thread.join(EXEC_TIMEOUT)

thread.interrupt()

if(thread.isAlive()) {

throw new JSchException("Exec Time Out Error")

} else {

try {

exec.disconnect()

out.close()

} catch (Exception e) {

}

byte[] lens = out.toByteArray()

String result = new String(lens, charset)

if(result.startsWith("bash") &&result.indexOf("command not found") != -1)

return ""

return result

}

}


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

原文地址:https://54852.com/yw/8489626.html

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

发表评论

登录后才能评论

评论列表(0条)

    保存