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

The following examples show how to use com.jcraft.jsch.ChannelSftp#put() . 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: SftpResourceUploader.java    From pushfish-android with BSD 2-Clause "Simplified" License 7 votes vote down vote up
public void upload(Factory<InputStream> sourceFactory, Long contentLength, URI destination) throws IOException {
    LockableSftpClient client = sftpClientFactory.createSftpClient(destination, credentials);

    try {
        ChannelSftp channel = client.getSftpClient();
        ensureParentDirectoryExists(channel, destination);
        InputStream sourceStream = sourceFactory.create();
        try {
            channel.put(sourceStream, destination.getPath());
        } finally {
            sourceStream.close();
        }
    } catch (com.jcraft.jsch.SftpException e) {
        throw new SftpException(String.format("Could not write to resource '%s'.", destination), e);
    } finally {
        sftpClientFactory.releaseSftpClient(client);
    }
}
 
Example 3
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 4
Source File: SFTPUtil.java    From bestconf with Apache License 2.0 6 votes vote down vote up
public static void upload(String directory, String uploadFile, ChannelSftp sftp) throws Exception{
	
	File file = new File(uploadFile);
	if(file.exists()){
		
		try {
			Vector content = sftp.ls(directory);
			if(content == null){
				sftp.mkdir(directory);
				System.out.println("mkdir:" + directory);
			}
		} catch (SftpException e) {
			sftp.mkdir(directory);
		}
		sftp.cd(directory);
		System.out.println("directory: " + directory);
		if(file.isFile()){
			InputStream ins = new FileInputStream(file);
			
			sftp.put(ins, new String(file.getName().getBytes(),"UTF-8"));
			
		}else{
			File[] files = file.listFiles();
			for (File file2 : files) {
				String dir = file2.getAbsolutePath();
				if(file2.isDirectory()){
					String str = dir.substring(dir.lastIndexOf(file2.separator));
					directory = directory + str;
				}
				System.out.println("directory is :" + directory);
				upload(directory,dir,sftp);
			}
		}
	}
}
 
Example 5
Source File: SFtpClientUtils.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
/**
 * 本地檔案放到遠端SFTP上
 * 	
 * @param user
 * @param password
 * @param addr
 * @param port
 * @param localFile
 * @param remoteFile
 * @throws JSchException
 * @throws SftpException
 * @throws Exception
 */
public static void put(String user, String password, String addr, int port,
		List<String> localFile, List<String> remoteFile) throws JSchException, SftpException, Exception {
	
	Session session = getSession(user, password, addr, port);	
	Channel channel = session.openChannel("sftp");
	channel.connect();
	ChannelSftp sftpChannel = (ChannelSftp) channel;		
	try {
		for (int i=0; i<localFile.size(); i++) {
			String rf=remoteFile.get(i);
			String lf=localFile.get(i);
			logger.info("put local file: " + lf + " write to " + addr + " :" + rf );
			sftpChannel.put(lf, rf);
			logger.info("success write to " + addr + " :" + rf);
		}
	} catch (Exception e) {
		e.printStackTrace();
		throw e;
	} finally {
		sftpChannel.exit();
		channel.disconnect();
		session.disconnect();				
	}		
}
 
Example 6
Source File: SftpResourceUploader.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void upload(Factory<InputStream> sourceFactory, Long contentLength, URI destination) throws IOException {
    LockableSftpClient client = sftpClientFactory.createSftpClient(destination, credentials);

    try {
        ChannelSftp channel = client.getSftpClient();
        ensureParentDirectoryExists(channel, destination);
        InputStream sourceStream = sourceFactory.create();
        try {
            channel.put(sourceStream, destination.getPath());
        } finally {
            sourceStream.close();
        }
    } catch (com.jcraft.jsch.SftpException e) {
        throw new SftpException(String.format("Could not write to resource '%s'.", destination), e);
    } finally {
        sftpClientFactory.releaseSftpClient(client);
    }
}
 
Example 7
Source File: JschFactory.java    From setupmaker with Apache License 2.0 6 votes vote down vote up
/**
 * Send a file to server path via SFTP
 * @param src
 * @param path
 * @throws SftpException
 */
public void put(final File src, String path) throws SftpException
{
    if (!path.endsWith("/")) path = path.concat("/");
    if (path.startsWith("/")) path = path.substring(1);
    
    ChannelSftp sftp = (ChannelSftp) channel;
    SftpProgressMonitor progress = new SftpProgressMonitor() {
        
        @Override public void init(int arg0, String arg1, String arg2, long arg3)
        {
            System.out.println("File transfer begin..");
        }
        
        @Override public void end()
        {
            Out.print(LOG_LEVEL.INFO, "Upload of file "+ src.getName() +" succeeded.");
            ready = true;
        }
        
        @Override public boolean count(long i) { return false; }
    };
    sftp.put(src.getAbsolutePath(), initRemDir+path+src.getName(), progress);
}
 
Example 8
Source File: SFTPRepository.java    From ant-ivy with Apache License 2.0 6 votes vote down vote up
public void put(File source, String destination, boolean overwrite) throws IOException {
    fireTransferInitiated(getResource(destination), TransferEvent.REQUEST_PUT);
    ChannelSftp c = getSftpChannel(destination);
    try {
        String path = getPath(destination);
        if (!overwrite && checkExistence(path, c)) {
            throw new IOException("destination file exists and overwrite == false");
        }
        if (path.indexOf('/') != -1) {
            mkdirs(path.substring(0, path.lastIndexOf('/')), c);
        }
        c.put(source.getAbsolutePath(), path, new MyProgressMonitor());
    } catch (SftpException | URISyntaxException e) {
        throw new IOException(e.getMessage(), e);
    }
}
 
Example 9
Source File: JobConfigUtil.java    From jumbune with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void sendJars(JumbuneRequest jumbuneRequest, String[] jarsPath) throws Exception {
	JobConfig jobConfig = jumbuneRequest.getJobConfig();
	Cluster cluster = jumbuneRequest.getCluster();

	String privateKeyPath = null;
	String password;
	String username;
	username = cluster.getAgents().getUser();
	password = cluster.getAgents().getPassword();
	if ((password != null) && (!password.trim().isEmpty())) {
		password = StringUtil.getPlain(cluster.getAgents().getPassword());
	} else {
		privateKeyPath = cluster.getAgents().getSshAuthKeysFile();
	}
	Session session = getSession(cluster.getNameNode(), username, password, privateKeyPath);
	ChannelSftp sftp = getChannel(session);

	String remoteDir = jumbuneRequest.getJobConfig().getTempDirectory() + jobConfig.getJumbuneJobName() + "/lib/";
	createPathInRemote(sftp, new File(remoteDir));
	for (String localJarPath : jarsPath) {
		String remoteFilePath = remoteDir + "/" + localJarPath.substring(localJarPath.lastIndexOf("/") + 1);
		sftp.put(new FileInputStream(localJarPath), remoteFilePath, 0);
	}
	sftp.disconnect();
	session.disconnect();
}
 
Example 10
Source File: SftpSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void put(ChannelSftp cftp) throws SftpIOException {
    // the below is just the replacement for one code line:
    // cftp.put(srcFileName, dstFileName);
    // (connected with #184068 -  Instable remote unit tests failure)
    int attempt = 0;
    while (true) {
        attempt++;
        try {
            cftp.put(parameters.srcFile.getAbsolutePath(), parameters.dstFileName);
            if (attempt > 1) {
                if (LOG.isLoggable(Level.FINE)) {
                    LOG.log(Level.FINE, "Success on attempt {0} to copy {1} to {2}:{3} :\n",
                            new Object[] {attempt, parameters.srcFile.getAbsolutePath(), execEnv, parameters.dstFileName});
                }
            }
            return;
        } catch (SftpException e) {
            if (attempt > PUT_RETRY_COUNT) {
                throw decorateSftpException(e, parameters.dstFileName);
            } else {
                if (LOG.isLoggable(Level.FINE) || attempt == 2) {
                    String message = String.format("Error on attempt %d to copy %s to %s:%s :\n", // NOI18N
                            attempt, parameters.srcFile.getAbsolutePath(), execEnv, parameters.dstFileName);
                    LOG.log(Level.FINE, message, e);
                    if (attempt == 2) {
                        Logger.fullThreadDump(message);
                    }
                }
                e.printStackTrace(System.err);
            }
        }
    }
}
 
Example 11
Source File: SftpUtils.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
public static void landFile(File fileToLand, UploadProperties properties) throws Exception {
    JSch jsch = new JSch();
    
    String host = properties.getSftpServer();
    String user = properties.getUser();
    String password = properties.getPassword();
    int port = properties.getPort();
    
    Session session = jsch.getSession(user, host, port);
    session.setOutputStream(System.out);
    
    session.setPassword(password);
    
    session.setConfig("StrictHostKeyChecking", "no");
    session.connect(TIMEOUT);
    
    Channel channel = session.openChannel("sftp");
    channel.connect();
    ChannelSftp c = (ChannelSftp) channel;
    
    // delete any existing file with the target filename, so that rename will work
    @SuppressWarnings("unchecked")
    Vector<LsEntry> files = c.ls(".");
    for (LsEntry file : files) {
        if (FINAL_REMOTE_FILENAME.equals(file.getFilename())) {
            c.rm(FINAL_REMOTE_FILENAME);
        }
    }
    
    // transmit file, using temp remote name, so ingestion won't process file until complete
    c.put(new FileInputStream(fileToLand), TEMP_REMOTE_FILENAME, ChannelSftp.OVERWRITE);
    
    // rename remote file so ingestion can begin
    c.rename(TEMP_REMOTE_FILENAME, FINAL_REMOTE_FILENAME);
    
    c.disconnect();
    channel.disconnect();
    session.disconnect();
}
 
Example 12
Source File: SftpFileObject.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an output stream to write the file content to.
 */
@Override
protected OutputStream doGetOutputStream(final boolean bAppend) throws Exception {
    // TODO - Don't write the entire file into memory. Use the stream-based
    // methods on ChannelSftp once the work properly
    /*
     * final ChannelSftp channel = getAbstractFileSystem().getChannel(); return new SftpOutputStream(channel);
     */

    final ChannelSftp channel = getAbstractFileSystem().getChannel();
    return new SftpOutputStream(channel, channel.put(relPath, bAppend ? ChannelSftp.APPEND : ChannelSftp.OVERWRITE));
}
 
Example 13
Source File: Scar.java    From scar with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
void upload (ChannelSftp channel) throws Exception {
	BufferedInputStream input = new BufferedInputStream(new FileInputStream(file));
	try {
		channel.put(input, file.getName(), sftpMonitor, fileCount == 0 ? ChannelSftp.OVERWRITE : ChannelSftp.RESUME);
	} finally {
		try {
			input.close();
		} catch (Exception ignored) {
		}
	}
}
 
Example 14
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 15
Source File: SFTPUtils.java    From axelor-open-suite with GNU Affero General Public License v3.0 4 votes vote down vote up
/** Sends given {@code file} to given {@code absoluteFilePath} in remote server. */
public static void put(ChannelSftp channel, InputStream file, String absoluteFilePath)
    throws SftpException {
  channel.put(file, absoluteFilePath);
}
 
Example 16
Source File: PooledSFTPOperationHandler.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void createFile(ChannelSftp ftp, String path) throws SftpException {
	ftp.put(new ByteArrayInputStream(new byte[0]), path);
}
 
Example 17
Source File: SFTPOperationHandler.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void createFile(ChannelSftp ftp, String path) throws SftpException {
	ftp.put(new ByteArrayInputStream(new byte[0]), path);
}
 
Example 18
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);
    }
}