Java Code Examples for com.jcraft.jsch.Channel#getOutputStream()
The following examples show how to use
com.jcraft.jsch.Channel#getOutputStream() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JavaStatusChecker.java From embeddedlinux-jvmdebugger-intellij with Apache License 2.0 | 6 votes |
/** * Stops java application that needs to, this should be called when the user wants to manually stop the application * so that it kills the remote java process * * @param session * @param isRunningAsRoot * @param mainClass * @throws JSchException * @throws IOException */ public void forceStopJavaApplication(@Nullable Session session, @NotNull boolean isRunningAsRoot, @NotNull String mainClass) throws JSchException, IOException { if (session == null) { return; } String javaKillCmd = String.format("%s kill -9 $(ps -efww | grep \"%s\"| grep -v grep | tr -s \" \"| cut -d\" \" -f2)", isRunningAsRoot ? "sudo" : "", mainClass); Channel channel = session.openChannel("shell"); OutputStream inputstream_for_the_channel = channel.getOutputStream(); PrintStream commander = new PrintStream(inputstream_for_the_channel, true); channel.connect(); commander.println(javaKillCmd); commander.close(); channel.disconnect(); session.disconnect(); }
Example 2
Source File: SSHServerTest.java From vertx-shell with Apache License 2.0 | 6 votes |
@Test public void testRead(TestContext context) throws Exception { Async async = context.async(); termHandler = term -> { term.stdinHandler(s -> { context.assertEquals("hello", s); async.complete(); }); }; startShell(); Session session = createSession("paulo", "secret", false); session.connect(); Channel channel = session.openChannel("shell"); channel.connect(); OutputStream out = channel.getOutputStream(); out.write("hello".getBytes()); out.flush(); channel.disconnect(); session.disconnect(); }
Example 3
Source File: WebSSHServiceImpl.java From mcg-helper with Apache License 2.0 | 5 votes |
private void transToSSH(Channel channel, String command) throws IOException { if (channel != null) { OutputStream outputStream = channel.getOutputStream(); outputStream.write(command.getBytes()); outputStream.flush(); } }
Example 4
Source File: JschServiceImpl.java From jwala with Apache License 2.0 | 5 votes |
@Override public RemoteCommandReturnInfo runShellCommand(RemoteSystemConnection remoteSystemConnection, String command, long timeout) { final ChannelSessionKey channelSessionKey = new ChannelSessionKey(remoteSystemConnection, ChannelType.SHELL); LOGGER.debug("channel session key = {}", channelSessionKey); Channel channel = null; try { channel = getChannelShell(channelSessionKey); final InputStream in = channel.getInputStream(); final OutputStream out = channel.getOutputStream(); LOGGER.debug("Executing command \"{}\"", command); out.write(command.getBytes(StandardCharsets.UTF_8)); out.write(CRLF.getBytes(StandardCharsets.UTF_8)); out.write("echo 'EXIT_CODE='$?***".getBytes(StandardCharsets.UTF_8)); out.write(CRLF.getBytes(StandardCharsets.UTF_8)); out.write("echo -n -e '\\xff'".getBytes(StandardCharsets.UTF_8)); out.write(CRLF.getBytes(StandardCharsets.UTF_8)); out.flush(); return getShellRemoteCommandReturnInfo(command, in, timeout); } catch (final Exception e) { final String errMsg = MessageFormat.format("Failed to run the following command: {0}", command); LOGGER.error(errMsg, e); throw new JschServiceException(errMsg, e); } finally { if (channel != null) { channelPool.returnObject(channelSessionKey, channel); LOGGER.debug("channel {} returned", channel.getId()); } } }
Example 5
Source File: JschUtil.java From jumbune with GNU Lesser General Public License v3.0 | 5 votes |
public static String getDaemonProcessId(Session session, String daemon) throws JSchException, IOException { String command = PID_COMMAND_PREFIX + daemon + PID_COMMAND_SUFFIX; session.connect(); Channel channel = session.openChannel("shell"); channel.connect(); OutputStream os = channel.getOutputStream(); InputStream is = channel.getInputStream(); PrintStream ps = new PrintStream(os, true); String pid = ""; try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) { ps.println(command); for (String line = br.readLine(); line != null; line = br.readLine()) { if (line.contains(daemon) && !line.contains("awk ")) { pid = line.split("\\s+")[1]; } } } LOGGER.debug(" exit status - " + channel.getExitStatus() + ", daemon = " + daemon + ", PID = " + pid); if (channel != null && channel.isConnected()) { channel.disconnect(); } if (session != null && session.isConnected()) { session.disconnect(); } return pid; }
Example 6
Source File: SshUtilities.java From hortonmachine with GNU General Public License v3.0 | 5 votes |
/** * Upload a file to the remote host via scp. * * @param session the session to use. * @param localFile the local file path. * @param remoteFile the remote file path to copy into. * @throws Exception */ public static void uploadFile( Session session, String localFile, String remoteFile ) throws Exception { boolean ptimestamp = true; // exec 'scp -t rfile' remotely String command = "scp " + (ptimestamp ? "-p" : "") + " -t " + remoteFile; 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) { throw new RuntimeException(); } 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()); out.flush(); if (checkAck(in) != 0) { throw new RuntimeException(); } } // 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 { command += localFile; } command += "\n"; out.write(command.getBytes()); out.flush(); if (checkAck(in) != 0) { throw new RuntimeException(); } // send a content of lfile FileInputStream fis = new FileInputStream(localFile); byte[] buf = new byte[1024]; while( true ) { int len = fis.read(buf, 0, buf.length); if (len <= 0) break; out.write(buf, 0, len); // out.flush(); } fis.close(); fis = null; // send '\0' buf[0] = 0; out.write(buf, 0, 1); out.flush(); if (checkAck(in) != 0) { throw new RuntimeException(); } out.close(); channel.disconnect(); }
Example 7
Source File: Scanner.java From ciscorouter with MIT License | 5 votes |
/** * Connects to the device and retrieves the configuration file from the * device. * @return A ArrayList containing the output from the GET_ALL_CONFIG * command */ private ArrayList<String> getConfigFile() throws Exception{ JSch jsch = new JSch(); InputStream in = null; Session session = jsch.getSession( host.getUser(), host.toString(), SSH_PORT); session.setPassword(host.getPass()); //If this line isn't present, every host must be in known_hosts session.setConfig("StrictHostKeyChecking", "no"); session.connect(); Channel channel = session.openChannel("shell"); in = channel.getInputStream(); OutputStream outputStream = channel.getOutputStream(); Expect expect = new ExpectBuilder() .withOutput(outputStream) .withInputs(channel.getInputStream(), channel.getExtInputStream()) //.withEchoOutput(System.out) //.withEchoInput(System.out) .build(); channel.connect(); if (host.usesEnable()) { expect.expect(contains(">")); expect.sendLine(ENABLE_SUPERUSER); expect.expect(contains(PASSWORD_PROMPT)); expect.sendLine(host.getEnablePass()); } expect.expect(contains("#")); //# expect.sendLine(DISABLE_OUTPUT_BUFFERING); //terminal length 0 expect.expect(contains("#")); //# expect.sendLine(GET_ALL_CONFIG); //show running-config full String result = expect.expect(contains("#")).getBefore(); //# channel.disconnect(); session.disconnect(); expect.close(); String[] arrLines = result.split("\n"); ArrayList<String> lines = new ArrayList<>(Arrays.asList(arrLines)); return lines; }
Example 8
Source File: SshHandler.java From Jpom with MIT License | 4 votes |
@Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { SshModel sshItem = (SshModel) session.getAttributes().get("sshItem"); Map<String, String[]> parameterMap = (Map<String, String[]>) session.getAttributes().get("parameterMap"); String[] fileDirAlls = null; //判断url是何操作请求 if (parameterMap.containsKey("tail")) { fileDirAlls = parameterMap.get("tail"); } else if (parameterMap.containsKey("gz")) { fileDirAlls = parameterMap.get("gz"); } else { fileDirAlls = parameterMap.get("zip"); } //检查文件路径 String fileDirAll = null; if (fileDirAlls != null && fileDirAlls.length > 0 && !StrUtil.isEmptyOrUndefined(fileDirAlls[0])) { fileDirAll = fileDirAlls[0]; List<String> fileDirs = sshItem.getFileDirs(); if (fileDirs == null) { sendBinary(session, "没有配置路径"); return; } File file = FileUtil.file(fileDirAll); boolean find = false; for (String fileDir : fileDirs) { if (FileUtil.isSub(FileUtil.file(fileDir), file)) { find = true; break; } } if (!find) { sendBinary(session, "非法路径"); return; } } Session openSession = SshService.getSession(sshItem); //JschUtil.openSession(sshItem.getHost(), sshItem.getPort(), sshItem.getUser(), sshItem.getPassword()); Channel channel = JschUtil.createChannel(openSession, ChannelType.SHELL); InputStream inputStream = channel.getInputStream(); OutputStream outputStream = channel.getOutputStream(); // Charset charset = sshItem.getCharsetT(); HandlerItem handlerItem = new HandlerItem(session, inputStream, outputStream, openSession, channel, charset); handlerItem.startRead(); HANDLER_ITEM_CONCURRENT_HASH_MAP.put(session.getId(), handlerItem); // Thread.sleep(1000); //截取当前操作文件父路径 String fileLocalPath = null; if (fileDirAll != null && fileDirAll.lastIndexOf("/") > -1) { fileLocalPath = fileDirAll.substring(0, fileDirAll.lastIndexOf("/")); } if (fileDirAll == null) { this.call(session, StrUtil.CR); } else if (parameterMap.containsKey("tail")) { // 查看文件 fileDirAll = FileUtil.normalize(fileDirAll); this.call(session, StrUtil.format("tail -f {}", fileDirAll)); this.call(session, StrUtil.CR); } else if (parameterMap.containsKey("zip")) { //解压zip fileDirAll = FileUtil.normalize(fileDirAll); this.call(session, StrUtil.format("unzip -o {} -d " + "{}", fileDirAll, fileLocalPath)); this.call(session, StrUtil.CR); } else { //解压 tar和tar.gz fileDirAll = FileUtil.normalize(fileDirAll); this.call(session, StrUtil.format("tar -xzvf {} -C " + "{}", fileDirAll, fileLocalPath)); this.call(session, StrUtil.CR); } }
Example 9
Source File: RmtShellExecutor.java From LuckyFrameClient with GNU Affero General Public License v3.0 | 4 votes |
/** * ����JSch��ʵ��Զ������SHELL����ִ�� * * @param ip ����IP * @param user ������½�û��� * @param psw ������½���� * @param port ����ssh2��½�˿ڣ����ȡĬ��ֵ����-1 * @param command Shell���� cd /home/pospsettle/tomcat-7.0-7080/bin&&./restart.sh */ public static String sshShell(String ip, String user, String psw , int port, String command) { Session session = null; Channel channel = null; String result = "Status:true" + " ��������ִ�гɹ���"; try { JSch jsch = new JSch(); LogUtil.APP.info("���뵽����TOMCAT����..."); if (port <= 0) { //���ӷ�����������Ĭ�϶˿� LogUtil.APP.info("��������TOMCAT������IP��Ĭ�϶˿�..."); session = jsch.getSession(user, ip); } else { //����ָ���Ķ˿����ӷ����� LogUtil.APP.info("��������TOMCAT������IP���˿�..."); session = jsch.getSession(user, ip, port); LogUtil.APP.info("��������TOMCAT������IP���˿����!"); } //������������Ӳ��ϣ����׳��쳣 if (session == null) { LogUtil.APP.warn("����TOMCAT�����У����ӷ�����session is null"); throw new Exception("session is null"); } //���õ�½���������� session.setPassword(psw); //���õ�һ�ε�½��ʱ����ʾ����ѡֵ��(ask | yes | no) session.setConfig("StrictHostKeyChecking", "no"); //���õ�½��ʱʱ�� session.connect(30000); //����sftpͨ��ͨ�� channel = session.openChannel("shell"); channel.connect(1000); //��ȡ������������� InputStream instream = channel.getInputStream(); OutputStream outstream = channel.getOutputStream(); //������Ҫִ�е�SHELL�����Ҫ��\n��β����ʾ�س� LogUtil.APP.info("��������TOMCAT��������������!"); String shellCommand = command + " \n"; outstream.write(shellCommand.getBytes()); outstream.flush(); Thread.sleep(10000); //��ȡ����ִ�еĽ�� if (instream.available() > 0) { byte[] data = new byte[instream.available()]; int nLen = instream.read(data); if (nLen < 0) { LogUtil.APP.warn("����TOMCAT�����У���ȡ����ִ�н�������쳣��"); } //ת������������ӡ���� String temp = new String(data, 0, nLen, "iso8859-1"); LogUtil.APP.info("��ʼ��ӡ����TOMCAT����ִ�н��...{}", temp); } outstream.close(); instream.close(); } catch (Exception e) { result = "����TOMCAT�����У������쳣��"; LogUtil.APP.error("����TOMCAT�����У������쳣��", e); return result; } finally { if (null != session) { session.disconnect(); } if (null != channel) { channel.disconnect(); } } return result; }
Example 10
Source File: Scp.java From ant-ivy with Apache License 2.0 | 4 votes |
private void sendFile(Channel channel, String localFile, String remoteName, String mode) throws IOException, RemoteScpException { byte[] buffer = new byte[BUFFER_SIZE]; OutputStream os = new BufferedOutputStream(channel.getOutputStream(), SEND_FILE_BUFFER_LENGTH); InputStream is = new BufferedInputStream(channel.getInputStream(), SEND_BYTES_BUFFER_LENGTH); try { if (channel.isConnected()) { channel.start(); } else { channel.connect(); } } catch (JSchException jsche) { throw new IOException("Channel connection problems", jsche); } readResponse(is); File f = new File(localFile); long remain = f.length(); String cMode = mode; if (cMode == null) { cMode = "0600"; } String cline = "C" + cMode + " " + remain + " " + remoteName + "\n"; os.write(cline.getBytes()); os.flush(); readResponse(is); try (FileInputStream fis = new FileInputStream(f)) { while (remain > 0) { int trans; if (remain > buffer.length) { trans = buffer.length; } else { trans = (int) remain; } if (fis.read(buffer, 0, trans) != trans) { throw new IOException("Cannot read enough from local file " + localFile); } os.write(buffer, 0, trans); remain -= trans; } } os.write(0); os.flush(); readResponse(is); os.write("E\n".getBytes()); os.flush(); }
Example 11
Source File: Scp.java From ant-ivy with Apache License 2.0 | 4 votes |
/** * Receive a file via scp and store it in a stream * * @param channel * ssh channel to use * @param file * to receive from remote * @param targetStream * to store file into (if null, get only file info) * @return file information of the file we received * @throws IOException * in case of network or protocol trouble * @throws RemoteScpException * in case of problems on the target system (connection is fine) */ private FileInfo receiveStream(Channel channel, String file, OutputStream targetStream) throws IOException, RemoteScpException { byte[] buffer = new byte[BUFFER_SIZE]; OutputStream os = channel.getOutputStream(); InputStream is = channel.getInputStream(); try { if (channel.isConnected()) { channel.start(); } else { channel.connect(); } } catch (JSchException jsche) { throw new IOException("Channel connection problems", jsche); } os.write(0x0); os.flush(); FileInfo fileInfo = new FileInfo(); while (true) { int c = is.read(); if (c < 0) { throw new RemoteScpException("Remote scp terminated unexpectedly."); } String line = receiveLine(is); if (c == 'T') { parseTLine(line, fileInfo); os.write(0x0); os.flush(); continue; } if (c == 1 || c == 2) { throw new RemoteScpException("Remote SCP error: " + line); } if (c == 'C') { parseCLine(line, fileInfo); break; } throw new RemoteScpException("Remote SCP error: " + ((char) c) + line); } if (targetStream != null) { os.write(0x0); os.flush(); try { long remain = fileInfo.getLength(); while (remain > 0) { int trans; if (remain > buffer.length) { trans = buffer.length; } else { trans = (int) remain; } int thisTimeReceived = is.read(buffer, 0, trans); if (thisTimeReceived < 0) { throw new IOException("Remote scp terminated connection unexpectedly"); } targetStream.write(buffer, 0, thisTimeReceived); remain -= thisTimeReceived; } targetStream.close(); } catch (IOException e) { if (targetStream != null) { targetStream.close(); } throw (e); } readResponse(is); os.write(0x0); os.flush(); } return fileInfo; }
Example 12
Source File: CommandDelegatorMethods.java From jumbune with GNU Lesser General Public License v3.0 | 4 votes |
/** * Called from class:HadoopLogParser(method:checkAndgetCurrentLogFilePathForYarn),class: ClusterProfilingHelper (method: getJobDetails),Class CopyThread(run method) * @param command * @throws JSchException * @throws IOException */ public void executeRemoteCommandAsSudo(Command command) throws JSchException, IOException { Session session = null; Channel channel = null; String host = RemotingConstants.LOCALHOST; SwitchedIdentity switchedIdentity = command.getSwitchedIdentity(); CommandType commandType = command.getCommandType(); try { session = createSession(switchedIdentity, host, commandType); channel = session.openChannel("exec"); String sudoCommand = "sudo -E su - " + switchedIdentity.getWorkingUser(); ((ChannelExec) channel).setCommand(sudoCommand); ((ChannelExec) channel).setPty(true); channel.connect(); InputStream inputStream = channel.getInputStream(); OutputStream out = channel.getOutputStream(); ((ChannelExec) channel).setErrStream(System.err); if(switchedIdentity.getPrivatePath() == null || switchedIdentity.getPrivatePath().isEmpty()){ out.write((StringUtil.getPlain(switchedIdentity.getPasswd()) + "\n").getBytes()); } out.flush(); Thread.sleep(100); LOGGER.debug("Now Sending Command ["+command.getCommandString()+"]"); out.write((command.getCommandString() + "\n").getBytes()); out.flush(); Thread.sleep(100 * 100); out.write(("logout" + "\n").getBytes()); out.flush(); Thread.sleep(100); out.write(("exit" + "\n").getBytes()); /* if(channel.getExitStatus()!=0){ String errorDebug = logJsch(channel, inputStream); LOGGER.error("Detailed Debug log for Errored command [" + command.getCommandString() +"]\n ----- \n"+errorDebug+"\n-----"); } */ out.flush(); out.close(); } catch (Exception e) { LOGGER.error(e.getCause()); } finally { if(session!=null){ session.disconnect(); } if(channel!=null){ channel.disconnect(); } } }
Example 13
Source File: SshUtilities.java From hortonmachine with GNU General Public License v3.0 | 4 votes |
/** * Download a remote file via scp. * * @param session the session to use. * @param remoteFilePath the remote file path. * @param localFilePath the local file path to copy into. * @throws Exception */ public static void downloadFile( Session session, String remoteFilePath, String localFilePath ) throws Exception { // exec 'scp -f rfile' remotely String command = "scp -f " + remoteFilePath; 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(); byte[] buf = new byte[1024]; // send '\0' buf[0] = 0; out.write(buf, 0, 1); out.flush(); while( true ) { int c = checkAck(in); if (c != 'C') { break; } // read '0644 ' in.read(buf, 0, 5); long filesize = 0L; while( true ) { if (in.read(buf, 0, 1) < 0) { // error break; } if (buf[0] == ' ') break; filesize = filesize * 10L + (long) (buf[0] - '0'); } String file = null; for( int i = 0;; i++ ) { in.read(buf, i, 1); if (buf[i] == (byte) 0x0a) { file = new String(buf, 0, i); break; } } System.out.println("filesize=" + filesize + ", file=" + file); // send '\0' buf[0] = 0; out.write(buf, 0, 1); out.flush(); // read a content of lfile FileOutputStream fos = new FileOutputStream(localFilePath); int foo; while( true ) { if (buf.length < filesize) foo = buf.length; else foo = (int) filesize; foo = in.read(buf, 0, foo); if (foo < 0) { // error break; } fos.write(buf, 0, foo); filesize -= foo; if (filesize == 0L) break; } fos.close(); if (checkAck(in) != 0) { throw new RuntimeException(); } // send '\0' buf[0] = 0; out.write(buf, 0, 1); out.flush(); } }