當前位置: 首頁>>代碼示例>>Java>>正文


Java Channel類代碼示例

本文整理匯總了Java中com.jcraft.jsch.Channel的典型用法代碼示例。如果您正苦於以下問題:Java Channel類的具體用法?Java Channel怎麽用?Java Channel使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Channel類屬於com.jcraft.jsch包,在下文中一共展示了Channel類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: upload

import com.jcraft.jsch.Channel; //導入依賴的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: executeCommand

import com.jcraft.jsch.Channel; //導入依賴的package包/類
/**
 * Executes a given command. It opens exec channel for the command and closes
 * the channel when it's done.
 *
 * @param session ssh connection to a remote server
 * @param command command to execute
 * @return command output string if the command succeeds, or null
 */
private static String executeCommand(Session session, String command) {
    if (session == null || !session.isConnected()) {
        return null;
    }

    log.trace("Execute command {} to {}", command, session.getHost());

    try {
        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        channel.setInputStream(null);
        InputStream output = channel.getInputStream();

        channel.connect();
        String result = CharStreams.toString(new InputStreamReader(output));
        channel.disconnect();

        log.trace("Result of command {} on {}: {}", command, session.getHost(), result);

        return result;
    } catch (JSchException | IOException e) {
        log.error("Failed to execute command {} on {} due to {}", command, session.getHost(), e.toString());
        return null;
    }
}
 
開發者ID:opencord,項目名稱:vtn,代碼行數:34,代碼來源:RemoteIpCommandUtil.java

示例3: getRemoteFileList

import com.jcraft.jsch.Channel; //導入依賴的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

示例4: listFiles

import com.jcraft.jsch.Channel; //導入依賴的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

示例5: forceStopJavaApplication

import com.jcraft.jsch.Channel; //導入依賴的package包/類
/**
 * Stops java application that needs to, this should be called when the user wants to manually stop the application
 * so that it kills the remote java process
 *
 * @param session
 * @param isRunningAsRoot
 * @param mainClass
 * @throws JSchException
 * @throws IOException
 */
public void forceStopJavaApplication(@Nullable Session session, @NotNull boolean isRunningAsRoot, @NotNull String mainClass) throws JSchException, IOException {
    if (session == null) {
        return;
    }
    String javaKillCmd = String.format("%s kill -9 $(ps -efww | grep \"%s\"| grep -v grep | tr -s \" \"| cut -d\" \" -f2)",
            isRunningAsRoot ? "sudo" : "", mainClass);
    Channel channel = session.openChannel("shell");

    OutputStream inputstream_for_the_channel = channel.getOutputStream();
    PrintStream commander = new PrintStream(inputstream_for_the_channel, true);

    channel.connect();

    commander.println(javaKillCmd);
    commander.close();
    channel.disconnect();
    session.disconnect();
}
 
開發者ID:asebak,項目名稱:embeddedlinux-jvmdebugger-intellij,代碼行數:29,代碼來源:JavaStatusChecker.java

示例6: connect

import com.jcraft.jsch.Channel; //導入依賴的package包/類
/**
 * Connect to a remote host and return a channel (session and jsch are set)
 */
Channel connect(String channleType, String sshCommand) throws Exception {
	JSch.setConfig("StrictHostKeyChecking", "no"); // Not recommended, but useful
	jsch = new JSch();

	// Some "reasonable" defaults
	if (Gpr.exists(defaultKnownHosts)) jsch.setKnownHosts(defaultKnownHosts);
	for (String identity : defaultKnownIdentity)
		if (Gpr.exists(identity)) jsch.addIdentity(identity);

	// Create session and connect
	if (debug) Gpr.debug("Create conection:\n\tuser: '" + host.getUserName() + "'\n\thost : '" + host.getHostName() + "'\n\tport : " + host.getPort());
	session = jsch.getSession(host.getUserName(), host.getHostName(), host.getPort());
	session.setUserInfo(new SshUserInfo());
	session.connect();

	// Create channel
	channel = session.openChannel(channleType);
	if ((sshCommand != null) && (channel instanceof ChannelExec)) ((ChannelExec) channel).setCommand(sshCommand);

	return channel;
}
 
開發者ID:pcingola,項目名稱:BigDataScript,代碼行數:25,代碼來源:Ssh.java

示例7: rename

import com.jcraft.jsch.Channel; //導入依賴的package包/類
@Override
public boolean rename(String newName){
    Channel channel = null;
    try {
         channel = SFTPSession.getInstance().getSFTPChannel(mUri);
        ((ChannelSftp)channel).rename(mUri.getPath(), new File(new File(mUri.getPath()).getParentFile(), newName).getAbsolutePath());
        channel.disconnect();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        if(channel!=null&&channel.isConnected())
            channel.disconnect();
    }
    return false;
}
 
開發者ID:archos-sa,項目名稱:aos-FileCoreLibrary,代碼行數:17,代碼來源:SftpFileEditor.java

示例8: move

import com.jcraft.jsch.Channel; //導入依賴的package包/類
@Override
public boolean move(Uri uri) {
    if(!mUri.getScheme().equals(uri.getScheme())|| !mUri.getHost().equals(uri.getHost())||mUri.getPort()!=uri.getPort())
        return false;
    Channel channel = null;
    try {
        channel = SFTPSession.getInstance().getSFTPChannel(mUri);
        ((ChannelSftp)channel).rename(mUri.getPath(),uri.getPath());
        channel.disconnect();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        if(channel!=null&&channel.isConnected())
            channel.disconnect();
    }
    return false;
}
 
開發者ID:archos-sa,項目名稱:aos-FileCoreLibrary,代碼行數:19,代碼來源:SftpFileEditor.java

示例9: exists

import com.jcraft.jsch.Channel; //導入依賴的package包/類
@Override
public boolean exists() {
    Channel channel = null;
    try {
        channel = SFTPSession.getInstance().getSFTPChannel(mUri);
        SftpATTRS attrs =  ((ChannelSftp)channel).stat(mUri.getPath());
        channel.disconnect();
        return attrs !=null;
    } catch (Exception e) {
        if(channel!=null&&channel.isConnected())
            channel.disconnect();
        e.printStackTrace();
    }finally {
        if(channel!=null&&channel.isConnected())
            channel.disconnect();
    }
    return false;
}
 
開發者ID:archos-sa,項目名稱:aos-FileCoreLibrary,代碼行數:19,代碼來源:SftpFileEditor.java

示例10: executeCommand

import com.jcraft.jsch.Channel; //導入依賴的package包/類
public void executeCommand(final String command) throws IOException { // Cliente SSH final
    JSch jsch = new JSch();
    Properties props = new Properties();
    props.put("StrictHostKeyChecking", "no");
    try {
        Session session = jsch.getSession(user, host, 22);
        session.setConfig(props);
        session.setPassword(password);
        session.connect();
        java.util.logging.Logger.getLogger(RemoteShell.class.getName())
                .log(Level.INFO, session.getServerVersion());

        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        // Daqui para baixo é somente para imprimir a saida
        channel.setInputStream(null);

        ((ChannelExec) channel).setErrStream(System.err);

        InputStream in = channel.getInputStream();

        channel.connect();

        byte[] tmp = new byte[1024];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                if (i < 0) {
                    break;
                }
                System.out.print(new String(tmp, 0, i));
            }
            if (channel.isClosed()) {
                if (in.available() > 0) {
                    continue;
                }
                System.out
                        .println("exit-status: " + channel.getExitStatus());
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (Exception ee) {
            }
        }
        channel.disconnect();
        session.disconnect();

    } catch (JSchException ex) {
        java.util.logging.Logger.getLogger(RemoteShell.class.getName())
                .log(Level.SEVERE, null, ex);
    }
}
 
開發者ID:nailtonvieira,項目名稱:pswot-cloud-java-spring-webapp,代碼行數:54,代碼來源:RemoteShell.java

示例11: executeCommandReader

import com.jcraft.jsch.Channel; //導入依賴的package包/類
/**
 * Execute an ssh command on the server, without closing the session
 * so that a Reader can be returned with streaming data from the server.
 *
 * @param command the command to execute.
 * @return a Reader with streaming data from the server.
 * @throws IOException  if it is so.
 * @throws SshException if there are any ssh problems.
 */
@Override
public synchronized Reader executeCommandReader(String command) throws SshException, IOException {
    if (!isConnected()) {
        throw new IllegalStateException("Not connected!");
    }
    try {
        Channel channel = connectSession.openChannel("exec");
        ((ChannelExec)channel).setCommand(command);
        InputStreamReader reader = new InputStreamReader(channel.getInputStream(), "utf-8");
        channel.connect();
        return reader;
    } catch (JSchException ex) {
        throw new SshException(ex);
    }
}
 
開發者ID:sonyxperiadev,項目名稱:gerrit-events,代碼行數:25,代碼來源:SshConnectionImpl.java

示例12: uploadFile

import com.jcraft.jsch.Channel; //導入依賴的package包/類
public void uploadFile(InputStream toBePrinted, String directory, String filename, SftpProgressMonitor progressMonitor) throws SftpException, JSchException, IOException {
    if(session== null){
        throw new JSchException(context.getString(R.string.misc_connection_not_set_up));
    }

    Channel channel = session.openChannel("sftp");

    channel.connect();
    ChannelSftp channelSftp = (ChannelSftp)channel;

    try{
        channelSftp.mkdir(directory);
    } catch (SftpException e){
        //If cannot make directory, means directory already created
    }
    channelSftp.cd(directory);
    channelSftp.put(toBePrinted, filename, progressMonitor, ChannelSftp.OVERWRITE);
    channelSftp.disconnect();
}
 
開發者ID:yeokm1,項目名稱:nus-soc-print,代碼行數:20,代碼來源:SSHConnectivity.java

示例13: connectAndExecute

import com.jcraft.jsch.Channel; //導入依賴的package包/類
public static String connectAndExecute(String user, String host, String password, String command1) {
	String CommandOutput = null;
	try {

		java.util.Properties config = new java.util.Properties();
		config.put("StrictHostKeyChecking", "no");
		JSch jsch = new JSch();

		Session session = jsch.getSession(user, host, 22);
		session.setPassword(password);
		session.setConfig(config);
		session.connect();
		// System.out.println("Connected");

		Channel channel = session.openChannel("exec");
		((ChannelExec) channel).setCommand(command1);
		channel.setInputStream(null);
		((ChannelExec) channel).setErrStream(System.err);

		InputStream in = channel.getInputStream();

		channel.connect();
		byte[] tmp = new byte[1024];
		while (true) {
			while (in.available() > 0) {
				int i = in.read(tmp, 0, 1024);

				if (i < 0)
					break;
				// System.out.print(new String(tmp, 0, i));
				CommandOutput = new String(tmp, 0, i);
			}

			if (channel.isClosed()) {
				// System.out.println("exit-status: " +
				// channel.getExitStatus());
				break;
			}
			try {
				Thread.sleep(1000);
			} catch (Exception ee) {
			}
		}
		channel.disconnect();
		session.disconnect();
		// System.out.println("DONE");

	} catch (Exception e) {
		e.printStackTrace();
	}
	return CommandOutput;

}
 
開發者ID:saiscode,項目名稱:kheera,代碼行數:54,代碼來源:SeleniumGridManager.java

示例14: init

import com.jcraft.jsch.Channel; //導入依賴的package包/類
ChannelSftp init(String filename) throws JSchException, UnsupportedEncodingException {
	jsch = new JSch();
	ConnectionInfo ci = splitStringToConnectionInfo(filename);

	Session session = jsch.getSession(ci.username, ci.host, ci.port);
	UserInfo ui = new SftpUserInfo(ci.password);
	session.setUserInfo(ui);

	session.connect();

	Channel channel = session.openChannel("sftp");
	channel.connect();
	ChannelSftp c = (ChannelSftp) channel;

	logDebug("success: init Sftp");
	return c;

}
 
開發者ID:PhilippC,項目名稱:keepass2android,代碼行數:19,代碼來源:SftpStorage.java

示例15: put

import com.jcraft.jsch.Channel; //導入依賴的package包/類
/**
 * 本地檔案放到遠端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();				
	}		
}
 
開發者ID:billchen198318,項目名稱:bamboobsc,代碼行數:38,代碼來源:SFtpClientUtils.java


注:本文中的com.jcraft.jsch.Channel類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。