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


Java JSch類代碼示例

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


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

示例1: upload

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

import com.jcraft.jsch.JSch; //導入依賴的package包/類
public JSch build() throws JSchException {
    LOGGER.debug("Initializing JSch Logger");
    JSch.setLogger(new JschLogger());
    final JSch jsch = new JSch();
    try {
        if (null != knownHostsFileName && new File(knownHostsFileName).exists()) {
            jsch.setKnownHosts(knownHostsFileName);
        }
        if (null != privateKeyFileName && new File(privateKeyFileName).exists()) {
            jsch.addIdentity(privateKeyFileName);
        }
    } catch (JSchException e) {
        LOGGER.error("Could not access known hosts or private key file.", e);
        if (!(e.getCause() instanceof FileNotFoundException)) {
            throw new JSchException();
        }
    }
    return jsch;
}
 
開發者ID:cerner,項目名稱:jwala,代碼行數:20,代碼來源:JschBuilder.java

示例4: listFiles

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

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

示例6: init

import com.jcraft.jsch.JSch; //導入依賴的package包/類
public SftpClient init() {
    try {
        String host = PropertiesUtil.getString("sftp.host");
        int port = PropertiesUtil.getInt("sftp.port");
        String userName = PropertiesUtil.getString("sftp.user.name");
        String password = PropertiesUtil.getString("sftp.user.password");
        Integer timeout = PropertiesUtil.getInt("sftp.timeout");
        Integer aliveMax = PropertiesUtil.getInt("sftp.aliveMax");
        JSch jsch = new JSch(); // 創建JSch對象
        session = jsch.getSession(userName, host, port); // 根據用戶名,主機ip,端口獲取一個Session對象
        if (password != null) {
            session.setPassword(password); // 設置密碼
        }
        session.setConfig("StrictHostKeyChecking", "no"); // 為Session對象設置properties
        if (timeout != null) session.setTimeout(timeout); // 設置timeout時間
        if (aliveMax != null) session.setServerAliveCountMax(aliveMax);
        session.connect(); // 通過Session建立鏈接
        channel = (ChannelSftp)session.openChannel("sftp"); // 打開SFTP通道
        channel.connect(); // 建立SFTP通道的連接
        logger.info("SSH Channel connected.");
    } catch (JSchException e) {
        throw new FtpException("", e);
    }
    return this;
}
 
開發者ID:iBase4J,項目名稱:iBase4J-Common,代碼行數:26,代碼來源:SftpClient.java

示例7: testTestCommand

import com.jcraft.jsch.JSch; //導入依賴的package包/類
@Test
public void testTestCommand() throws JSchException, IOException {
    JSch jsch = new JSch();
    Session session = jsch.getSession("admin", "localhost", properties.getShell().getPort());
    jsch.addIdentity("src/test/resources/id_rsa");
    Properties config = new Properties();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    session.connect();
    ChannelShell channel = (ChannelShell) session.openChannel("shell");
    PipedInputStream pis = new PipedInputStream();
    PipedOutputStream pos = new PipedOutputStream();
    channel.setInputStream(new PipedInputStream(pos));
    channel.setOutputStream(new PipedOutputStream(pis));
    channel.connect();
    pos.write("test run bob\r".getBytes(StandardCharsets.UTF_8));
    pos.flush();
    verifyResponse(pis, "test run bob");
    pis.close();
    pos.close();
    channel.disconnect();
    session.disconnect();
}
 
開發者ID:anand1st,項目名稱:sshd-shell-spring-boot,代碼行數:24,代碼來源:SshdShellAutoConfigurationWithPublicKeyAndBannerImageTest.java

示例8: executeCommand

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

示例9: connectWithIdentity

import com.jcraft.jsch.JSch; //導入依賴的package包/類
public void connectWithIdentity(String identityPath, String passPhrase) throws JSchException,FileNotFoundException {
    if (identityPath == null || new File(identityPath).exists() == false) {
        throw new FileNotFoundException("Identity file not found !") ;
    }
    if (m_session != null) {
        m_session.disconnect();
    }
    preConnect();
    JSch jsch = new JSch();
    if (passPhrase != null && passPhrase.length() >0) {
        jsch.addIdentity(identityPath, passPhrase);
    }
    else {
        jsch.addIdentity(identityPath);
    }

    SSH2User userInfo = new SSH2User(m_username, passPhrase);
    m_session = jsch.getSession(m_username, m_host, m_port);
    m_session.setConfig(infos);
    m_session.setUserInfo(userInfo);
    m_session.connect();
}
 
開發者ID:vmware,項目名稱:vco-powershel-plugin,代碼行數:23,代碼來源:SSH2AbstractSession.java

示例10: SSHShell

import com.jcraft.jsch.JSch; //導入依賴的package包/類
/**
 * Creates SSHShell.
 *
 * @param host the host name
 * @param port the ssh port
 * @param userName the ssh user name
 * @param sshPrivateKey the ssh password
 * @return the shell
 * @throws JSchException
 * @throws IOException
 */
private SSHShell(String host, int port, String userName, byte[] sshPrivateKey)
    throws JSchException, IOException {
    Closure expectClosure = getExpectClosure();
    for (String linuxPromptPattern : new String[]{"\\>", "#", "~#", "~\\$"}) {
        try {
            Match match = new RegExpMatch(linuxPromptPattern, expectClosure);
            linuxPromptMatches.add(match);
        } catch (MalformedPatternException malformedEx) {
            throw new RuntimeException(malformedEx);
        }
    }
    JSch jsch = new JSch();
    jsch.setKnownHosts(System.getProperty("user.home") + "/.ssh/known_hosts");
    jsch.addIdentity(host, sshPrivateKey, (byte[]) null, (byte[]) null);
    this.session = jsch.getSession(userName, host, port);
    this.session.setConfig("StrictHostKeyChecking", "no");
    this.session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
    session.connect(60000);
    this.channel = (ChannelShell) session.openChannel("shell");
    this.expect = new Expect4j(channel.getInputStream(), channel.getOutputStream());
    channel.connect();
}
 
開發者ID:Azure-Samples,項目名稱:acr-java-manage-azure-container-registry,代碼行數:34,代碼來源:SSHShell.java

示例11: generateSSHKeys

import com.jcraft.jsch.JSch; //導入依賴的package包/類
/**
 * Automatically generate SSH keys.
 * @param passPhrase the byte array content to be uploaded
 * @param comment the name of the file for which the content will be saved into
 * @return SSH public and private key
 * @throws Exception exception thrown
 */
public static SshPublicPrivateKey generateSSHKeys(String passPhrase, String comment) throws Exception {
    JSch jsch = new JSch();
    KeyPair keyPair = KeyPair.genKeyPair(jsch, KeyPair.RSA);
    ByteArrayOutputStream privateKeyBuff = new ByteArrayOutputStream(2048);
    ByteArrayOutputStream publicKeyBuff = new ByteArrayOutputStream(2048);

    keyPair.writePublicKey(publicKeyBuff, (comment != null) ? comment : "SSHCerts");

    if (passPhrase == null  || passPhrase.isEmpty()) {
        keyPair.writePrivateKey(privateKeyBuff);
    } else {
        keyPair.writePrivateKey(privateKeyBuff, passPhrase.getBytes());
    }

    return new SshPublicPrivateKey(privateKeyBuff.toString(), publicKeyBuff.toString());
}
 
開發者ID:Azure-Samples,項目名稱:acr-java-manage-azure-container-registry,代碼行數:24,代碼來源:SSHShell.java

示例12: connectAndExecute

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

示例13: init

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

示例14: createSession

import com.jcraft.jsch.JSch; //導入依賴的package包/類
private Session createSession(String host, Args args) throws JSchException {
  JSch jsch = new JSch();
  for (String keyFile : getKeyFiles()) {
    jsch.addIdentity(keyFile);
  }
  JSch.setLogger(new LogAdapter());

  Session session = jsch.getSession(args.user, host, args.sshPort);
  session.setConfig("StrictHostKeyChecking", "no");
  return session;
}
 
開發者ID:naver,項目名稱:hadoop,代碼行數:12,代碼來源:SshFenceByTcpPort.java

示例15: establishWithKey

import com.jcraft.jsch.JSch; //導入依賴的package包/類
public static Session establishWithKey(String sshHost, int sshPort, String user, String keyFilePath) throws JSchException {
    File keyFile = new File(keyFilePath);
    if (!keyFile.exists()) {
        String errorMsg = "Could not find SSH public key file in path: " + keyFilePath;
        logger.info(errorMsg);
        throw new JSchException(errorMsg);
    }
    Session session;
    JSch jsch = new JSch();
    try {
        jsch.addIdentity(keyFile.getAbsolutePath());
        session = jsch.getSession(user, sshHost, sshPort);
    }
    catch (JSchException e) {
        logger.error("SSH connection attempt to host: " + sshHost + ":" + sshPort + " failed");
        throw e;
    }
    return connect(session, sshHost, sshPort);
}
 
開發者ID:razreg,項目名稱:ubongo,代碼行數:20,代碼來源:SSHConnection.java


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