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

The following examples show how to use com.jcraft.jsch.ChannelSftp#cd() . 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: FTPUtil.java    From seed with Apache License 2.0 8 votes vote down vote up
/**
 * 创建远程目录
 * @param remotePath 不含文件名的远程路径(格式为/a/b/c)
 */
private static void createRemoteFolderViaSFTP(ChannelSftp channelSftp, String remotePath){
    String[] folders = remotePath.split("/");
    String remoteTempPath = "";
    for(String folder : folders){
        if(StringUtils.isNotBlank(folder)){
            remoteTempPath += "/" + folder;
            boolean flag = true;
            try{
                channelSftp.cd(remoteTempPath);
            }catch(SftpException e){
                flag = false;
            }
            LogUtil.getLogger().info("change working directory : " + remoteTempPath + "-->" + (flag?"SUCCESS":"FAIL"));
            if(!flag){
                try{
                    channelSftp.mkdir(remoteTempPath);
                    flag = true;
                }catch(SftpException ignored){}
                LogUtil.getLogger().info("make directory : " + remoteTempPath + "-->" + (flag?"SUCCESS":"FAIL"));
            }
        }
    }
}
 
Example 2
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 3
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 4
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 5
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 6
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 7
Source File: SFTPEnvironment.java    From sftp-fs with Apache License 2.0 5 votes vote down vote up
void initializePostConnect(ChannelSftp channel) throws IOException {
    String defaultDir = FileSystemProviderSupport.getValue(this, DEFAULT_DIR, String.class, null);
    if (defaultDir != null) {
        try {
            channel.cd(defaultDir);
        } catch (SftpException e) {
            throw getExceptionFactory().createChangeWorkingDirectoryException(defaultDir, e);
        }
    }
}
 
Example 8
Source File: Scar.java    From scar with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
void cd (ChannelSftp channel, String path) throws Exception {
	try {
		channel.cd(path);
	} catch (SftpException ex) {
		if (ex.id != ChannelSftp.SSH_FX_NO_SUCH_FILE) throw new Exception("Error setting remote directory: " + path, ex);
		mkdirs(channel, path);
	}
}
 
Example 9
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);
    }
}