Java Code Examples for com.jcraft.jsch.session#openChannel()
The following examples show how to use
com.jcraft.jsch.session#openChannel() .
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: JobEntrySFTPIT.java From pentaho-kettle with Apache License 2.0 | 6 votes |
private void uploadFile( String dir, String file ) throws Exception { Session session = server.createJschSession(); session.connect(); try { ChannelSftp sftp = (ChannelSftp) session.openChannel( "sftp" ); sftp.connect(); try { sftp.mkdir( dir ); sftp.cd( dir ); sftp.put( new ByteArrayInputStream( "data".getBytes() ), file ); } finally { sftp.disconnect(); } } finally { session.disconnect(); } }
Example 2
Source File: SSHServerTest.java From vertx-shell with Apache License 2.0 | 6 votes |
@Test public void testCloseHandler(TestContext context) throws Exception { Async async = context.async(); termHandler = term -> { term.closeHandler(v -> { async.complete(); }); }; startShell(); Session session = createSession("paulo", "secret", false); session.connect(); Channel channel = session.openChannel("shell"); channel.connect(); channel.disconnect(); session.disconnect(); }
Example 3
Source File: SSHServerTest.java From vertx-shell with Apache License 2.0 | 6 votes |
@Test public void testDifferentCharset(TestContext context) throws Exception { termHandler = term -> { term.write("\u20AC"); term.close(); }; startShell(new SSHTermOptions().setDefaultCharset("ISO_8859_1").setPort(5000).setHost("localhost").setKeyPairOptions( new JksOptions().setPath("src/test/resources/server-keystore.jks").setPassword("wibble")). setAuthOptions(new JsonObject() .put("provider", "shiro") .put("type", "PROPERTIES") .put("config", new JsonObject().put("properties_path", "classpath:test-auth.properties")))); Session session = createSession("paulo", "secret", false); session.connect(); Channel channel = session.openChannel("shell"); channel.connect(); InputStream in = channel.getInputStream(); int b = in.read(); context.assertEquals(63, b); }
Example 4
Source File: DeploymentEngine.java From if1007 with MIT License | 6 votes |
private boolean executeSSH(){ //get deployment descriptor, instead of this hard coded. // or execute a script on the target machine which download artifact from nexus String command ="nohup java -jar -Dserver.port=8091 ./work/codebox/chapter6/chapter6.search/target/search-1.0.jar &"; try{ System.out.println("Executing "+ command); java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); JSch jsch = new JSch(); Session session=jsch.getSession("rajeshrv", "localhost", 22); session.setPassword("rajeshrv"); session.setConfig(config); session.connect(); System.out.println("Connected"); ChannelExec channelExec = (ChannelExec)session.openChannel("exec"); InputStream in = channelExec.getInputStream(); channelExec.setCommand(command); channelExec.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line; int index = 0; while ((line = reader.readLine()) != null) { System.out.println(++index + " : " + line); } channelExec.disconnect(); session.disconnect(); System.out.println("Done!"); }catch(Exception e){ e.printStackTrace(); return false; } return true; }
Example 5
Source File: SshdShellAutoConfigurationWithPublicKeyAndBannerImageTest.java From sshd-shell-spring-boot with Apache License 2.0 | 6 votes |
@Test public void testTestCommand() throws JSchException, IOException { JSch jsch = new JSch(); Session session = jsch.getSession("admin", "localhost", properties.getShell().getPort()); jsch.addIdentity("src/test/resources/id_rsa"); Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); ChannelShell channel = (ChannelShell) session.openChannel("shell"); try (PipedInputStream pis = new PipedInputStream(); PipedOutputStream pos = new PipedOutputStream()) { channel.setInputStream(new PipedInputStream(pos)); channel.setOutputStream(new PipedOutputStream(pis)); channel.connect(); pos.write("test run bob\r".getBytes(StandardCharsets.UTF_8)); pos.flush(); verifyResponseContains(pis, "test run bob"); } channel.disconnect(); session.disconnect(); }
Example 6
Source File: SFtpUInfoTask.java From Aria with Apache License 2.0 | 5 votes |
@Override protected void getFileInfo(Session session) throws JSchException, UnsupportedEncodingException, SftpException { SFtpTaskOption option = (SFtpTaskOption) getWrapper().getTaskOption(); ChannelSftp channel = (ChannelSftp) session.openChannel("sftp"); channel.connect(1000); String remotePath = option.getUrlEntity().remotePath; String temp = CommonUtil.convertSFtpChar(getOption().getCharSet(), remotePath) + "/" + getWrapper().getEntity().getFileName(); SftpATTRS attr = null; try { attr = channel.stat(temp); } catch (Exception e) { ALog.d(TAG, String.format("文件不存在,remotePath:%s", remotePath)); } boolean isComplete = false; UploadEntity entity = getWrapper().getEntity(); if (attr != null && attr.getSize() == entity.getFileSize()) { isComplete = true; } CompleteInfo info = new CompleteInfo(); info.code = isComplete ? ISCOMPLETE : 200; info.obj = attr; channel.disconnect(); callback.onSucceed(getWrapper().getKey(), info); }
Example 7
Source File: RemoteCredentialsSupport.java From kork with Apache License 2.0 | 5 votes |
static RemoteCredentials getRemoteCredentials( String command, String user, String host, int port) { RemoteCredentials remoteCredentials = new RemoteCredentials(); try { Session session = jsch.getSession(user, host, port); Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); config.put("PreferredAuthentications", "publickey"); config.put("HashKnownHosts", "yes"); session.setConfig(config); session.setPassword(""); session.connect(); ChannelExec channel = (ChannelExec) session.openChannel("exec"); InputStream is = channel.getInputStream(); channel.setCommand(command); channel.connect(); String output = IOUtils.toString(is); log.debug("Remote credentials: {}", output); channel.disconnect(); session.disconnect(); output = output.replace("\n", ""); remoteCredentials = objectMapper.readValue(output, RemoteCredentials.class); } catch (Exception e) { log.error("Remote SSH execution failed.", e); } return remoteCredentials; }
Example 8
Source File: SFtpClientUtils.java From bamboobsc with Apache License 2.0 | 5 votes |
/** * 抓遠端檔案然後存到本機 , 單筆 * * @param user * @param password * @param addr * @param port * @param remoteFile * @param localFile * @throws JSchException * @throws SftpException * @throws Exception */ public static void get(String user, String password, String addr, int port, String remoteFile, String localFile) throws JSchException, SftpException, Exception { Session session = getSession(user, password, addr, port); Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp sftpChannel = (ChannelSftp) channel; logger.info("get remote file: " + remoteFile + " write to:" + localFile ); try { sftpChannel.get(remoteFile, localFile); } catch (Exception e) { e.printStackTrace(); throw e; } finally { sftpChannel.exit(); channel.disconnect(); session.disconnect(); } File f=new File(localFile); if (!f.exists()) { f=null; logger.error("get remote file:"+remoteFile + " fail!"); throw new Exception("get remote file:"+remoteFile + " fail!"); } f=null; logger.info("success write:" + localFile); }
Example 9
Source File: SshLocalhostExample.java From ExpectIt with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws JSchException, IOException { JSch jSch = new JSch(); Session session = jSch.getSession(System.getenv("USER"), "localhost"); Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); jSch.addIdentity(System.getProperty("user.home") + "/.ssh/id_rsa"); session.setConfig(config); session.connect(); Channel channel = session.openChannel("shell"); channel.connect(); Expect expect = new ExpectBuilder() .withOutput(channel.getOutputStream()) .withInputs(channel.getInputStream(), channel.getExtInputStream()) .build(); try { expect.expect(contains("$")); expect.sendLine("pwd"); System.out.println( "pwd1:" + expect.expect(times(2, contains("\n"))) .getResults() .get(1) .getBefore()); expect.sendLine("pwd"); // a regexp which captures the output of pwd System.out.println("pwd2:" + expect.expect(regexp("(?m)\\n([^\\n]*)\\n")).group(1)); expect.expect(contains("$")); expect.sendLine("ls -l"); // skipping the echo command expect.expect(times(2, contains("\n"))); // getting the output of ls System.out.println(expect.expect(regexp(".*\\$")).getBefore().trim()); expect.sendLine("exit"); } finally { expect.close(); channel.disconnect(); session.disconnect(); } }
Example 10
Source File: SshdSftpEnabledTest.java From sshd-shell-spring-boot with Apache License 2.0 | 5 votes |
@DirtiesContext @Test public void testSftp2() throws Exception { Session session = openSession(props.getShell().getUsername(), props.getShell().getPassword()); ChannelSftp sftp = (ChannelSftp) session.openChannel("sftp"); sftp.connect(); sftp.disconnect(); session.disconnect(); assertTrue(new File("target/sftp/admin").exists()); }
Example 11
Source File: SshdSftpEnabledTest.java From sshd-shell-spring-boot with Apache License 2.0 | 5 votes |
@DirtiesContext @Test public void testSftp() throws Exception { Session session = openSession(props.getShell().getUsername(), props.getShell().getPassword()); ChannelSftp sftp = (ChannelSftp) session.openChannel("sftp"); sftp.connect(); sftp.disconnect(); session.disconnect(); assertTrue(new File("target/sftp/admin").exists()); }
Example 12
Source File: KeyedPooledJschChannelFactory.java From jwala with Apache License 2.0 | 5 votes |
@Override public Channel create(final ChannelSessionKey key) throws Exception { Session session; synchronized (sessionMap) { session = sessionMap.get(key); if (session == null || !session.isConnected()) { session = prepareSession(key.remoteSystemConnection); session.connect(); sessionMap.put(key, session); LOGGER.debug("session {} created and connected!", key); } } return session.openChannel(key.channelType.getChannelType()); }
Example 13
Source File: JschUtil.java From jumbune with GNU Lesser General Public License v3.0 | 5 votes |
/** * Gets the channel. * * @param session * the session * @param command * the command * @return the channel * @throws JSchException * the j sch exception * @throws IOException * Signals that an I/O exception has occurred. */ public static Channel getChannel(Session session, String command) throws JSchException, IOException { session.connect(); Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); channel.setInputStream(null); InputStream in = channel.getInputStream(); channel.connect(); ((ChannelExec) channel).setErrStream(System.err); byte[] tmp = new byte[RemotingConstants.ONE_ZERO_TWO_FOUR]; while (true) { while (in.available() > 0) { int i = in.read(tmp, 0, RemotingConstants.ONE_ZERO_TWO_FOUR); if (i < 0){ break; } } if (channel.isClosed()) { break; } } return channel; }
Example 14
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 15
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 16
Source File: SshExample.java From ExpectIt with Apache License 2.0 | 4 votes |
public static void main(String[] args) throws JSchException, IOException { JSch jSch = new JSch(); Session session = jSch.getSession("new", "sdf.org"); Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); Channel channel = session.openChannel("shell"); channel.connect(); Expect expect = new ExpectBuilder() .withOutput(channel.getOutputStream()) .withInputs(channel.getInputStream(), channel.getExtInputStream()) .withEchoInput(System.out) .withEchoOutput(System.err) .withInputFilters(removeColors(), removeNonPrintable()) .withExceptionOnFailure() .build(); try { expect.expect(contains("[RETURN]")); expect.sendLine(); String ipAddress = expect.expect(regexp("Trying (.*)\\.\\.\\.")).group(1); System.out.println("Captured IP: " + ipAddress); expect.expect(contains("login:")); expect.sendLine("new"); expect.expect(contains("(Y/N)")); expect.send("N"); expect.expect(regexp(": $")); expect.send("\b"); expect.expect(regexp("\\(y\\/n\\)")); expect.sendLine("y"); expect.expect(contains("Would you like to sign the guestbook?")); expect.send("n"); expect.expect(contains("[RETURN]")); expect.sendLine(); } finally { expect.close(); channel.disconnect(); session.disconnect(); } }
Example 17
Source File: SSHShellUtil.java From mcg-helper with Apache License 2.0 | 4 votes |
public static String execute(String ip, int port, String userName, String password, String secretKey, String shell) throws JSchException, IOException { String response = null; JSch.setLogger(new ShellLogger()); JSch jsch = new JSch(); Session session = jsch.getSession(userName, ip, port); UserInfo ui = null; if(StringUtils.isEmpty(secretKey)) { ui = new SSHUserInfo(password); } else { ui = new SSHGoogleAuthUserInfo(secretKey, password); } session.setUserInfo(ui); session.connect(6000); Channel channel = session.openChannel("shell"); PipedInputStream pipedInputStream = new PipedInputStream(); PipedOutputStream pipedOutputStream = new PipedOutputStream(); pipedOutputStream.connect(pipedInputStream); Thread thread = new Thread(new MonitorShellUser(channel, shell, pipedOutputStream)); thread.start(); channel.setInputStream(pipedInputStream); PipedOutputStream shellPipedOutputStream = new PipedOutputStream(); PipedInputStream receiveStream = new PipedInputStream(); shellPipedOutputStream.connect(receiveStream); channel.setOutputStream(shellPipedOutputStream); ((ChannelShell)channel).setPtyType("vt100", 160, 24, 1000, 480); // dumb //((ChannelShell)channel).setTerminalMode("binary".getBytes(Constants.CHARSET)); // ((ChannelShell)channel).setEnv("LANG", "zh_CN.UTF-8"); try { channel.connect(); response = IOUtils.toString(receiveStream, "UTF-8"); }finally { // if(channel.isClosed()) { pipedOutputStream.close(); pipedInputStream.close(); shellPipedOutputStream.close(); receiveStream.close(); channel.disconnect(); session.disconnect(); } // } return response; }
Example 18
Source File: JobConfigUtil.java From jumbune with GNU Lesser General Public License v3.0 | 4 votes |
private static ChannelSftp getChannel(Session session) throws JSchException { Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp sftp = (ChannelSftp) channel; return sftp; }
Example 19
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(); } }
Example 20
Source File: ProfilerJMXDump.java From jumbune with GNU Lesser General Public License v3.0 | 3 votes |
/** * <<<<<<< Updated upstream Opens a new channel,sets the command,input and error streams and return it. ======= Opens a new channel,sets the * command,input and error streams and return it. >>>>>>> Stashed changes * * @param session * the session * @param command * the command * @return the channel * @throws JSchException * the j sch exception * @throws IOException * Signals that an I/O exception has occurred. */ private Channel getChannel(Session session, String command) throws JSchException, IOException { Channel channel = session.openChannel(EXECUTION_MODE); ((ChannelExec) channel).setCommand(command); channel.setInputStream(null); ((ChannelExec) channel).setErrStream(System.err); channel.connect(); return channel; }