当前位置: 首页>>代码示例>>Java>>正文


Java ChannelSftp类代码示例

本文整理汇总了Java中com.jcraft.jsch.ChannelSftp的典型用法代码示例。如果您正苦于以下问题:Java ChannelSftp类的具体用法?Java ChannelSftp怎么用?Java ChannelSftp使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


ChannelSftp类属于com.jcraft.jsch包,在下文中一共展示了ChannelSftp类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: upload

import com.jcraft.jsch.ChannelSftp; //导入依赖的package包/类
private void upload(String filename) {
    try {
        JSch jsch = new JSch();
        Session session = jsch.getSession(login, server, port);
        session.setPassword(password);

        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();

        Channel channel = session.openChannel("sftp");
        channel.connect();
        ChannelSftp channelSftp = (ChannelSftp) channel;
        channelSftp.cd(workingDirectory);
        File f = new File(filename);

        channelSftp.put(new FileInputStream(f), f.getName());

        f.delete();

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
 
开发者ID:SKNZ,项目名称:LesPatternsDuSwag,代码行数:26,代码来源:SFTPUploader.java

示例2: fileFetch

import com.jcraft.jsch.ChannelSftp; //导入依赖的package包/类
public static void fileFetch(String host, String user, String keyLocation, String sourceDir, String destDir) {
    JSch jsch = new JSch();
    Session session = null;
    try {
        // set up session
        session = jsch.getSession(user,host);
        // use private key instead of username/password
        session.setConfig(
                "PreferredAuthentications",
                "publickey,gssapi-with-mic,keyboard-interactive,password");
        jsch.addIdentity(keyLocation);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();

        // copy remote log file to localhost.
        ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
        channelSftp.connect();
        channelSftp.get(sourceDir, destDir);
        channelSftp.exit();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        session.disconnect();
    }
}
 
开发者ID:thomas-young-2013,项目名称:wherehowsX,代码行数:29,代码来源:SshUtils.java

示例3: put

import com.jcraft.jsch.ChannelSftp; //导入依赖的package包/类
/**
 * 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);
}
 
开发者ID:DevComPack,项目名称:setupmaker,代码行数:30,代码来源:JschFactory.java

示例4: getDir

import com.jcraft.jsch.ChannelSftp; //导入依赖的package包/类
private void getDir(final ChannelSftp channel,
                    final String remoteFile,
                    final File localFile) throws IOException, SftpException {
    String pwd = remoteFile;
    if (remoteFile.lastIndexOf('/') != -1) {
        if (remoteFile.length() > 1) {
            pwd = remoteFile.substring(0, remoteFile.lastIndexOf('/'));
        }
    }
    channel.cd(pwd);
    if (!localFile.exists()) {
        localFile.mkdirs();
    }
    @SuppressWarnings("unchecked")
    final List<ChannelSftp.LsEntry> files = channel.ls(remoteFile);
    for (ChannelSftp.LsEntry le : files) {
        final String name = le.getFilename();
        if (le.getAttrs().isDir()) {
            if (".".equals(name) || "..".equals(name)) {
                continue;
            }
            getDir(channel,
                   channel.pwd() + "/" + name + "/",
                   new File(localFile, le.getFilename()));
        } else {
            getFile(channel, le, localFile);
        }
    }
    channel.cd("..");
}
 
开发者ID:apache,项目名称:ant,代码行数:31,代码来源:ScpFromMessageBySftp.java

示例5: getRemoteFileList

import com.jcraft.jsch.ChannelSftp; //导入依赖的package包/类
@SuppressWarnings("unchecked")
public static Vector<LsEntry> getRemoteFileList(String user, String password, String addr, int port, String cwd) throws JSchException, 
	SftpException, Exception {
	
	Session session = getSession(user, password, addr, port);	
	Vector<LsEntry> lsVec=null;
	Channel channel = session.openChannel("sftp");
	channel.connect();
	ChannelSftp sftpChannel = (ChannelSftp) channel;
	try {
		lsVec=(Vector<LsEntry>)sftpChannel.ls(cwd); //sftpChannel.lpwd()
	} catch (Exception e) {
		e.printStackTrace();
		throw e;
	} finally {
		sftpChannel.exit();
		channel.disconnect();
		session.disconnect();			
	}		
	return lsVec;		
}
 
开发者ID:billchen198318,项目名称:bamboobsc,代码行数:22,代码来源:SFtpClientUtils.java

示例6: listFiles

import com.jcraft.jsch.ChannelSftp; //导入依赖的package包/类
/**
 * Lists directory files on remote server.
 * @throws URISyntaxException 
 * @throws JSchException 
 * @throws SftpException 
 */
private void listFiles() throws URISyntaxException, JSchException, SftpException {
	
	JSch jsch = new JSch();
	JSch.setLogger(new JschLogger());
	setupSftpIdentity(jsch);

	URI uri = new URI(sftpUrl);
	Session session = jsch.getSession(sshLogin, uri.getHost(), 22);
	session.setConfig("StrictHostKeyChecking", "no");
	session.connect();
	System.out.println("Connected to SFTP server");

	Channel channel = session.openChannel("sftp");
	channel.connect();
	ChannelSftp sftpChannel = (ChannelSftp) channel;
	Vector<LsEntry> directoryEntries = sftpChannel.ls(uri.getPath());
	for (LsEntry file : directoryEntries) {
		System.out.println(String.format("File - %s", file.getFilename()));
	}
	sftpChannel.exit();
	session.disconnect();
}
 
开发者ID:szaqal,项目名称:KitchenSink,代码行数:29,代码来源:App.java

示例7: upload

import com.jcraft.jsch.ChannelSftp; //导入依赖的package包/类
/**
 * 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();
}
 
开发者ID:Azure-Samples,项目名称:acr-java-manage-azure-container-registry,代码行数:32,代码来源:SSHShell.java

示例8: renameFile

import com.jcraft.jsch.ChannelSftp; //导入依赖的package包/类
@Override
public boolean renameFile(String fromFilePath, String toFilePath, boolean closeSession) {
    ChannelSftp sftp = null;
    try {
        // Get a reusable channel if the session is not auto closed.
        sftp = (closeSession) ? openConnectedChannel() : openConnectedChannel(CHANNEL_1);
        sftp.cd(basePath);
        sftp.rename(fromFilePath, toFilePath);
        return true;
    } catch (Exception e) {
        return false;
    } finally {
        if (closeSession) {
            close();
        }
    }
}
 
开发者ID:JumpMind,项目名称:metl,代码行数:18,代码来源:SftpDirectory.java

示例9: createStatInfo

import com.jcraft.jsch.ChannelSftp; //导入依赖的package包/类
private StatInfo createStatInfo(String dirName, String baseName, SftpATTRS attrs, ChannelSftp cftp) throws SftpException {
    String linkTarget = null;
    if (attrs.isLink()) {
        String path = dirName + '/' + baseName;
        RemoteStatistics.ActivityID activityID = RemoteStatistics.startChannelActivity("readlink", path); // NOI18N
        try {
            if (LOG.isLoggable(Level.FINE)) {
                LOG.log(Level.FINE, "performing readlink {0}", path);
            }
            linkTarget = cftp.readlink(path);
        } finally {
            RemoteStatistics.stopChannelActivity(activityID);
        }
    }
    Date lastModified = new Date(attrs.getMTime() * 1000L);
    StatInfo result = new FileInfoProvider.StatInfo(baseName, attrs.getUId(), attrs.getGId(), attrs.getSize(),
            attrs.isDir(), attrs.isLink(), linkTarget, attrs.getPermissions(), lastModified);
    return result;
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:20,代码来源:SftpSupport.java

示例10: download

import com.jcraft.jsch.ChannelSftp; //导入依赖的package包/类
/**
 * Perform the specified SSH file download.
 * 
 * @param from source remote file URI ({@code ssh} protocol)
 * @param to target local folder URI ({@code file} protocol)
 */
private static void download(URI from, URI to) {
    File out = new File(new File(to), getName(from.getPath()));
    try (SessionHolder<ChannelSftp> session = new SessionHolder<>(ChannelType.SFTP, from);
            OutputStream os = new FileOutputStream(out);
            BufferedOutputStream bos = new BufferedOutputStream(os)) {

        LOG.info("Downloading {} --> {}", session.getMaskedUri(), to);
        ChannelSftp channel = session.getChannel();
        channel.connect();
        channel.cd(getFullPath(from.getPath()));
        channel.get(getName(from.getPath()), bos);

    } catch (Exception e) {
        throw new RemoteFileDownloadFailedException("Cannot download file", e);
    }
}
 
开发者ID:Nordstrom,项目名称:Remote-Session,代码行数:23,代码来源:SshUtils.java

示例11: listFiles

import com.jcraft.jsch.ChannelSftp; //导入依赖的package包/类
public synchronized List<ChannelSftp.LsEntry> listFiles(String path) throws GenericFileOperationFailedException {
    LOG.trace("listFiles({})", path);
    if (ObjectHelper.isEmpty(path)) {
        // list current directory if file path is not given
        path = ".";
    }

    try {
        final List<ChannelSftp.LsEntry> list = new ArrayList<ChannelSftp.LsEntry>();

        @SuppressWarnings("rawtypes")
        Vector files = channel.ls(path);
        // can return either null or an empty list depending on FTP servers
        if (files != null) {
            for (Object file : files) {
                list.add((ChannelSftp.LsEntry) file);
            }
        }
        return list;
    } catch (SftpException e) {
        throw new GenericFileOperationFailedException("Cannot list directory: " + path, e);
    }
}
 
开发者ID:HydAu,项目名称:Camel,代码行数:24,代码来源:SftpOperations.java

示例12: copyFile

import com.jcraft.jsch.ChannelSftp; //导入依赖的package包/类
@Override
public void copyFile(String fromFilePath, String toFilePath, boolean closeSession) {
    ChannelSftp uploadSftp = null;
    InputStream inputStream = null;
    try {
        // Get a reusable channel if the session is not auto closed.
        uploadSftp = (closeSession) ? openConnectedChannel() : openConnectedChannel(CHANNEL_1);
        uploadSftp.cd(basePath);
        inputStream = getInputStream(fromFilePath, true);
        uploadSftp.put(inputStream, toFilePath);
    } catch (Exception e) {
        throw new IoException("Error copying file.  Error %s", e.getMessage());
    } finally {
        if (closeSession) {
            close();
        }
    }  
}
 
开发者ID:JumpMind,项目名称:metl,代码行数:19,代码来源:SftpDirectory.java

示例13: copyToDir

import com.jcraft.jsch.ChannelSftp; //导入依赖的package包/类
@Override
public void copyToDir(String fromFilePath, String toDirPath, boolean closeSession) {
    ChannelSftp uploadSftp = null;
    FileInfo fileInfo = new FileInfo(fromFilePath, false, new java.util.Date().getTime(), -1);
    InputStream inputStream = null;
    try {
        // Get a reusable channel if the session is not auto closed.
        uploadSftp = (closeSession) ? openConnectedChannel() : openConnectedChannel(CHANNEL_1);
        uploadSftp.cd(basePath);
        
        if (!toDirPath.endsWith("/")) {
        	toDirPath += "/";
        }
        inputStream = getInputStream(fromFilePath, true);
        uploadSftp.put(inputStream, toDirPath + fileInfo.getName());
    } catch (Exception e) {
        throw new IoException("Error copying directory.  Error %s", e.getMessage());
    } finally {
        if (closeSession) {
            close();
        }
    }
}
 
开发者ID:JumpMind,项目名称:metl,代码行数:24,代码来源:SftpDirectory.java

示例14: moveToDir

import com.jcraft.jsch.ChannelSftp; //导入依赖的package包/类
@Override
public void moveToDir(String fromFilePath, String toDirPath, boolean closeSession) {
    ChannelSftp sftp = null;
    FileInfo fileInfo = new FileInfo(fromFilePath, false, new java.util.Date().getTime(), -1);
    try {
        // Get a reusable channel if the session is not auto closed.
        sftp = (closeSession) ? openConnectedChannel() : openConnectedChannel(CHANNEL_1);
        sftp.cd(basePath);
        if (!toDirPath.endsWith("/")) {
        	toDirPath += "/";
        }
        sftp.rename(fromFilePath, toDirPath + fileInfo.getName());
    } catch (Exception e) {
        throw new IoException("Error moving (renaming) directory.  Error %s", e.getMessage());
    } finally {
        if (closeSession) {
            close();
        }
    }
}
 
开发者ID:JumpMind,项目名称:metl,代码行数:21,代码来源:SftpDirectory.java

示例15: getInputStream

import com.jcraft.jsch.ChannelSftp; //导入依赖的package包/类
@Override
public InputStream getInputStream(String relativePath, boolean mustExist, boolean closeSession) {
	Session session = null;
	ChannelSftp sftp = null;
    try {
    	session = openSession();
        // Get a reusable channel if the session is not auto closed.
        sftp = (closeSession) ? openConnectedChannel() : openConnectedChannel(CHANNEL_IN);
        sftp.cd(basePath);
        if (mustExist && !fileExists(sftp, relativePath)) {
            throw new IoException("Could not find endpoint '%s' that was configured as MUST EXIST",relativePath);
        }
        return new CloseableInputStream(sftp.get(relativePath), session, sftp, closeSession);
    } catch (Exception e) {
        if (e instanceof IoException || 
                (e instanceof SftpException && ((SftpException) e).id != 2)) {
            throw new IoException("Error getting the input stream for sftp endpoint.  Error %s", e.getMessage());
        } else {
            return null;
        }
    } 
}
 
开发者ID:JumpMind,项目名称:metl,代码行数:23,代码来源:SftpDirectory.java


注:本文中的com.jcraft.jsch.ChannelSftp类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。