java程序执行linux命令

java程序执行linux命令,第1张

首先确保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

}

}

ssh是什么呢?

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

原文地址: http://outofmemory.cn/yw/7471342.html

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

发表评论

登录后才能评论

评论列表(0条)

保存