use of com.jcraft.jsch.ChannelExec in project Jpom by dromara.
the class CommandService method execute.
/**
* 执行命令
*
* @param commandModel 命令模版
* @param commandExecLogModel 执行记录
* @param sshModel ssh
* @param commandParamsLine 参数
* @throws IOException io
*/
private void execute(CommandModel commandModel, CommandExecLogModel commandExecLogModel, SshModel sshModel, String commandParamsLine) throws IOException {
File file = commandExecLogModel.logFile();
try (BufferedOutputStream outputStream = FileUtil.getOutputStream(file)) {
if (sshModel == null) {
this.appendLine(outputStream, "ssh 不存在");
return;
}
String command = commandModel.getCommand();
String[] commands = StrUtil.splitToArray(command, StrUtil.LF);
//
workspaceEnvVarService.formatCommand(commandModel.getWorkspaceId(), commands);
//
Charset charset = sshModel.getCharsetT();
sshService.exec(sshModel, (s, session) -> {
final ChannelExec channel = (ChannelExec) JschUtil.createChannel(session, ChannelType.EXEC);
channel.setCommand(StrUtil.bytes(s + StrUtil.SPACE + commandParamsLine, charset));
channel.setInputStream(null);
channel.setErrStream(outputStream, true);
InputStream in = null;
try {
channel.connect();
in = channel.getInputStream();
IoUtil.readLines(in, charset, (LineHandler) line -> this.appendLine(outputStream, line));
// 更新状态
this.updateStatus(commandExecLogModel.getId(), CommandExecLogModel.Status.DONE);
} catch (Exception e) {
DefaultSystemLog.getLog().error("执行命令错误", e);
// 更新状态
this.updateStatus(commandExecLogModel.getId(), CommandExecLogModel.Status.ERROR);
// 记录错误日志
String stacktraceToString = ExceptionUtil.stacktraceToString(e);
this.appendLine(outputStream, stacktraceToString);
} finally {
IoUtil.close(in);
JschUtil.close(channel);
}
return null;
}, commands);
}
}
use of com.jcraft.jsch.ChannelExec in project Jpom by dromara.
the class TestJschExec method test2.
@Test
public void test2() throws IOException, JSchException {
Charset charset = CharsetUtil.CHARSET_UTF_8;
Session session = JschUtil.createSession("192.168.1.8", 22, "root", "123456+");
ChannelExec channel = (ChannelExec) JschUtil.createChannel(session, ChannelType.EXEC);
// 添加环境变量
channel.setCommand(cmd);
channel.setErrStream(System.err);
channel.setInputStream(System.in);
InputStream inputStream = channel.getInputStream();
InputStream errStream = channel.getErrStream();
channel.connect((int) TimeUnit.SECONDS.toMillis(5));
//
String error = null;
String result = null;
try {
result = IoUtil.read(inputStream, charset);
} catch (Exception e) {
e.printStackTrace();
if (!StrUtil.contains(e.getMessage(), "Pipe closed")) {
DefaultSystemLog.getLog().error("读取 exec 流发生异常", e);
result = "读取 exec 流发生异常" + e.getMessage();
}
}
try {
error = IoUtil.read(errStream, charset);
} catch (Exception e) {
e.printStackTrace();
if (!StrUtil.contains(e.getMessage(), "Pipe closed")) {
DefaultSystemLog.getLog().error("读取 exec err 流发生异常", e);
error = "读取 exec err 流发生异常" + e.getMessage();
}
}
System.out.println("结束 " + result + " " + error);
}
use of com.jcraft.jsch.ChannelExec in project commons-vfs by apache.
the class SftpFileSystem method executeCommand.
/**
* Executes a command and returns the (standard) output through a StringBuilder.
*
* @param command The command
* @param output The output
* @return The exit code of the command
* @throws JSchException if a JSch error is detected.
* @throws FileSystemException if a session cannot be created.
* @throws IOException if an I/O error is detected.
*/
private int executeCommand(final String command, final StringBuilder output) throws JSchException, IOException {
final ChannelExec channel = (ChannelExec) getSession().openChannel("exec");
try {
channel.setCommand(command);
channel.setInputStream(null);
try (InputStreamReader stream = new InputStreamReader(channel.getInputStream(), StandardCharsets.UTF_8)) {
channel.setErrStream(System.err, true);
channel.connect(DurationUtils.toMillisInt(connectTimeout));
// Read the stream
final char[] buffer = new char[EXEC_BUFFER_SIZE];
int read;
while ((read = stream.read(buffer, 0, buffer.length)) >= 0) {
output.append(buffer, 0, read);
}
}
// Wait until the command finishes (should not be long since we read the output stream)
while (!channel.isClosed()) {
try {
Thread.sleep(SLEEP_MILLIS);
} catch (InterruptedException e) {
// Someone asked us to stop.
break;
}
}
} finally {
channel.disconnect();
}
return channel.getExitStatus();
}
use of com.jcraft.jsch.ChannelExec in project hopsworks by logicalclocks.
the class RemoteCommandExecutor method executeInternal.
private RemoteCommandResult executeInternal(RemoteCommand command) throws ServiceException {
Channel channel = null;
Session session = null;
try {
LOGGER.log(Level.FINE, "Executing remote command: " + command);
JSch jsch = new JSch();
jsch.addIdentity(command.getIdentity().toString());
session = jsch.getSession(command.getUser(), command.getHost(), command.getPort());
session.setConfig(command.getSSHConfig());
session.setConfig("StrictHostKeyChecking", "no");
session.connect(command.getConnectTimeout());
channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command.getCommand());
String stdout = waitForCommandToFinish(channel, command);
int exitCode = channel.getExitStatus();
return new RemoteCommandResult(stdout, exitCode);
} catch (JSchException | IOException ex) {
LOGGER.log(Level.WARNING, "Error executing remote command " + command, ex);
throw new ServiceException(RESTCodes.ServiceErrorCode.ERROR_EXECUTING_REMOTE_COMMAND, Level.WARNING, "Error while executing remote command", "Error executing remote command: " + command, ex);
} catch (RemoteCommandTimeoutException ex) {
return new RemoteCommandResult("Command time-out: " + ex.getMessage(), 20);
} finally {
if (channel != null) {
channel.disconnect();
}
if (session != null) {
session.disconnect();
}
}
}
use of com.jcraft.jsch.ChannelExec in project kylin by apache.
the class SSHClient method scpFileToRemote.
public void scpFileToRemote(String localFile, String remoteTargetDirectory) throws Exception {
FileInputStream fis = null;
try {
logger.info("SCP file " + localFile + " to " + remoteTargetDirectory);
Session session = newJSchSession();
session.connect();
boolean ptimestamp = false;
// exec 'scp -t rfile' remotely
String command = "scp " + (ptimestamp ? "-p" : "") + " -t " + remoteTargetDirectory;
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
// get I/O streams for remote scp
OutputStream out = channel.getOutputStream();
InputStream in = channel.getInputStream();
channel.connect();
if (checkAck(in) != 0) {
System.exit(0);
}
File _lfile = new File(localFile);
if (ptimestamp) {
command = "T " + (_lfile.lastModified() / 1000) + " 0";
// The access time should be sent here,
// but it is not accessible with JavaAPI ;-<
command += (" " + (_lfile.lastModified() / 1000) + " 0\n");
out.write(command.getBytes(StandardCharsets.UTF_8));
out.flush();
if (checkAck(in) != 0) {
throw new Exception(ERROR_IN_CHECK_ACK);
}
}
// send "C0644 filesize filename", where filename should not include '/'
long filesize = _lfile.length();
command = "C0644 " + filesize + " ";
if (localFile.lastIndexOf("/") > 0) {
command += localFile.substring(localFile.lastIndexOf("/") + 1);
} else if (localFile.lastIndexOf(File.separator) > 0) {
command += localFile.substring(localFile.lastIndexOf(File.separator) + 1);
} else {
command += localFile;
}
command += "\n";
out.write(command.getBytes(StandardCharsets.UTF_8));
out.flush();
if (checkAck(in) != 0) {
throw new Exception(ERROR_IN_CHECK_ACK);
}
// send a content of lfile
fis = new FileInputStream(localFile);
byte[] buf = new byte[1024];
while (true) {
int len = fis.read(buf, 0, buf.length);
if (len <= 0)
break;
// out.flush();
out.write(buf, 0, len);
}
fis.close();
fis = null;
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
if (checkAck(in) != 0) {
throw new Exception(ERROR_IN_CHECK_ACK);
}
out.close();
channel.disconnect();
session.disconnect();
} catch (Exception e) {
throw e;
} finally {
IOUtils.closeQuietly(fis);
}
}
Aggregations