Java Code Examples for com.jcraft.jsch.ChannelSftp#connect()

The following examples show how to use com.jcraft.jsch.ChannelSftp#connect() . 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: SSHShell.java    From azure-libraries-for-java with MIT License 7 votes vote down vote up
/**
 * Creates a new file on the remote host using the input content.
 *
 * @param from the byte array content to be uploaded
 * @param fileName the name of the file for which the content will be saved into
 * @param toPath the path of the file for which the content will be saved into
 * @param isUserHomeBased true if the path of the file is relative to the user's home directory
 * @param filePerm file permissions to be set
 * @throws Exception exception thrown
 */
public void upload(InputStream from, String fileName, String toPath, boolean isUserHomeBased, String filePerm) throws Exception {
    ChannelSftp channel = (ChannelSftp) this.session.openChannel("sftp");
    channel.connect();
    String absolutePath = isUserHomeBased ? channel.getHome() + "/" + toPath : toPath;

    String path = "";
    for (String dir : absolutePath.split("/")) {
        path = path + "/" + dir;
        try {
            channel.mkdir(path);
        } catch (Exception ee) {
        }
    }
    channel.cd(absolutePath);
    channel.put(from, fileName);
    if (filePerm != null) {
        channel.chmod(Integer.parseInt(filePerm), absolutePath + "/" + fileName);
    }

    channel.disconnect();
}
 
Example 2
Source File: SSHShell.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * Downloads the content of a file from the remote host as a String.
 *
 * @param fileName the name of the file for which the content will be downloaded
 * @param fromPath the path of the file for which the content will be downloaded
 * @param isUserHomeBased true if the path of the file is relative to the user's home directory
 * @return the content of the file
 * @throws Exception exception thrown
 */
public String download(String fileName, String fromPath, boolean isUserHomeBased) throws Exception {
    ChannelSftp channel = (ChannelSftp) this.session.openChannel("sftp");
    channel.connect();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    BufferedOutputStream buff = new BufferedOutputStream(outputStream);
    String absolutePath = isUserHomeBased ? channel.getHome() + "/" + fromPath : fromPath;
    channel.cd(absolutePath);
    channel.get(fileName, buff);

    channel.disconnect();

    return outputStream.toString();
}
 
Example 3
Source File: JSchSshSession.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/**
 * Opens a new SFTP channel over this SSH session.
 *
 * @throws JSchException
 * @throws SftpException
 * @see JSchSftpChannel
 */
public JSchSftpChannel openSftpChannel() throws JSchException, SftpException {
  ChannelSftp chan = (ChannelSftp) session.openChannel("sftp");
  chan.connect(timeout);
  if (url.getPath().isPresent()) {
    String dir = url.getPath().get();
    try {
      chan.cd(dir);
    } catch (SftpException e) {
      logger.atWarning().withCause(e).log("Could not open SFTP channel.");
      mkdirs(chan, dir);
      chan.cd(dir);
    }
  }
  return new JSchSftpChannel(chan);
}
 
Example 4
Source File: SftpFsHelper.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Create new channel every time a command needs to be executed. This is required to support execution of multiple
 * commands in parallel. All created channels are cleaned up when the session is closed.
 *
 *
 * @return a new {@link ChannelSftp}
 * @throws SftpException
 */
public ChannelSftp getSftpChannel() throws SftpException {

  try {
    ChannelSftp channelSftp = (ChannelSftp) this.session.openChannel("sftp");

    // In millsec
    int connTimeout = state.getPropAsInt(SFTP_CONNECTION_TIMEOUT_KEY, DEFAULT_SFTP_CONNECTION_TIMEOUT);
    channelSftp.connect(connTimeout);
    return channelSftp;
  } catch (JSchException e) {
    throw new SftpException(0, "Cannot open a channel to SFTP server", e);
  }
}
 
Example 5
Source File: JobEntrySFTPIT.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
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 6
Source File: SftpExecutor.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Override
protected SftpOutput executeCommand(ServerConfiguration serverConfiguration, Commands commands, ChannelSftp channel)
        throws JSchException, IOException
{
    channel.setAgentForwarding(serverConfiguration.isAgentForwarding());
    channel.connect();
    SftpOutput executionOutput = new SftpOutput();
    StringBuilder output = new StringBuilder();
    try
    {
        for (SingleCommand<SftpCommand> command : commands.getSingleCommands(SftpCommand::fromString))
        {
            String commandOutput = command.getCommand().execute(channel, command.getParameters());
            if (commandOutput != null)
            {
                if (output.length() > 0)
                {
                    output.append(System.lineSeparator());
                }
                output.append(commandOutput);
            }
        }
    }
    catch (SftpException e)
    {
        softAssert.recordFailedAssertion("SFTP command error", e);
    }
    executionOutput.setResult(output.toString());
    return executionOutput;
}
 
Example 7
Source File: SFTPUtils.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
public static SFTPConnection connectSftp(final SFTPConfiguration conf) throws JSchException, SftpException, IOException {
    final JSch jsch = new JSch();
    final Session session = SFTPUtils.createSession(conf, jsch);
    final ChannelSftp sftp = (ChannelSftp) session.openChannel("sftp");
    sftp.connect();
    return new SFTPConnection(session, sftp);
}
 
Example 8
Source File: SshdSftpEnabledTest.java    From sshd-shell-spring-boot with Apache License 2.0 5 votes vote down vote up
@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 9
Source File: SshdSftpEnabledTest.java    From sshd-shell-spring-boot with Apache License 2.0 5 votes vote down vote up
@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 10
Source File: SFTPEnvironment.java    From sftp-fs with Apache License 2.0 5 votes vote down vote up
void connect(ChannelSftp channel) throws IOException {
    try {
        if (containsKey(CONNECT_TIMEOUT)) {
            int connectTimeout = FileSystemProviderSupport.getIntValue(this, CONNECT_TIMEOUT);
            channel.connect(connectTimeout);
        } else {
            channel.connect();
        }
    } catch (JSchException e) {
        throw asFileSystemException(e);
    }
}
 
Example 11
Source File: SFtpUInfoTask.java    From Aria with Apache License 2.0 5 votes vote down vote up
@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 12
Source File: SFtpDInfoTask.java    From Aria with Apache License 2.0 5 votes vote down vote up
@Override protected void getFileInfo(Session session) throws JSchException,
    UnsupportedEncodingException, SftpException {
  SFtpTaskOption option = (SFtpTaskOption) getWrapper().getTaskOption();
  ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
  channel.connect(1000);

  //channel.setFilenameEncoding(option.getCharSet());
  //channel.setFilenameEncoding("gbk");

  String remotePath = option.getUrlEntity().remotePath;
  String temp = CommonUtil.convertSFtpChar(option.getCharSet(), remotePath);
  SftpATTRS attr = null;
  try {
    attr = channel.stat(temp);
  } catch (Exception e) {
    ALog.e(TAG, String.format("文件不存在,remotePath:%s", remotePath));
  }

  if (attr != null) {
    getWrapper().getEntity().setFileSize(attr.getSize());
    CompleteInfo info = new CompleteInfo();
    info.code = 200;
    callback.onSucceed(getWrapper().getKey(), info);
  } else {
    callback.onFail(getWrapper().getEntity(),
        new AriaSFTPException(String.format("文件不存在,remotePath:%s", remotePath)), false);
  }
  channel.disconnect();
}
 
Example 13
Source File: SftpFileTransferLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenUploadFileUsingJsch_thenSuccess() throws JSchException, SftpException {
    ChannelSftp channelSftp = setupJsch();
    channelSftp.connect();
    channelSftp.put(localFile, remoteDir + "jschFile.txt");
    channelSftp.exit();
}
 
Example 14
Source File: SftpFileTransferLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenDownloadFileUsingJsch_thenSuccess() throws JSchException, SftpException {
    ChannelSftp channelSftp = setupJsch();
    channelSftp.connect();
    channelSftp.get(remoteFile, localDir + "jschFile.txt");
    channelSftp.exit();
}
 
Example 15
Source File: GitRepo.java    From warnings-ng-plugin with MIT License 4 votes vote down vote up
/**
 * Zip bare repository, copy to Docker container using sftp, then unzip. The repo is now accessible over
 * "ssh://git@ip:port/home/git/gitRepo.git"
 *
 * @param host
 *         IP of Docker container
 * @param port
 *         SSH port of Docker container
 */
public void transferToDockerContainer(String host, int port) {
    try {
        Path zipPath = Files.createTempFile("git", "zip");
        File zippedRepo = zipPath.toFile();
        String zippedFilename = zipPath.getFileName().toString();
        ZipUtil.pack(new File(dir.getPath()), zippedRepo);

        Properties props = new Properties();
        props.put("StrictHostKeyChecking", "no");

        JSch jSch = new JSch();
        jSch.addIdentity(privateKey.getAbsolutePath());

        Session session = jSch.getSession("git", host, port);
        session.setConfig(props);
        session.connect();

        ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
        channel.connect();
        channel.cd("/home/git");
        channel.put(new FileInputStream(zippedRepo), zippedFilename);

        ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
        InputStream in = channelExec.getInputStream();
        channelExec.setCommand("unzip " + zippedFilename + " -d " + REPO_NAME);
        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();
        channel.disconnect();
        session.disconnect();
        // Files.delete(zipPath);
    }
    catch (IOException | JSchException | SftpException e) {
        throw new AssertionError("Can't transfer git repository to docker container", e);
    }
}