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


Java JSch.getSession方法代码示例

本文整理汇总了Java中com.jcraft.jsch.JSch.getSession方法的典型用法代码示例。如果您正苦于以下问题:Java JSch.getSession方法的具体用法?Java JSch.getSession怎么用?Java JSch.getSession使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在com.jcraft.jsch.JSch的用法示例。


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

示例1: 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

示例2: 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

示例3: 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

示例4: 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

示例5: 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

示例6: 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

示例7: testJschConnection

import com.jcraft.jsch.JSch; //导入方法依赖的package包/类
@Test
public void testJschConnection() throws InterruptedException, SftpException, JSchException, IOException {
    JSch jsch = new JSch();
    String passphrase = "";
    jsch.addIdentity(privateKey,
        StringUtil.isEmpty(passphrase) ?
        null : passphrase);

    Session session = jsch.getSession(user, host, port);
    System.out.println("session created.");

    java.util.Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking", "no");
    config.put("PreferredAuthentications",
        "publickey,keyboard-interactive,password");
    session.setConfig(config);
    session.connect();
    Thread.sleep(500);
    session.disconnect();
}
 
开发者ID:sanchouss,项目名称:InstantPatchIdeaPlugin,代码行数:21,代码来源:RemoteClientImplTest.java

示例8: transferFile

import com.jcraft.jsch.JSch; //导入方法依赖的package包/类
/**
 * Transfer a file to remote destination via JSCH library using sFTP protocol
 * 
 * @param username String remote SFTP server user name.
 * @param password String remote SFTP server user password
 * @param host String remote SFTP server IP address or host name.
 * @param file File to transfer to SFTP Server.
 * @param transferProtocol protocol to transfer a file. {@link FileTransferProtocol}
 * @return boolean true if file is transfered otherwise false.
 * @throws ApplicationException
 */
public static boolean transferFile(final String username, final String password, final String host,
                                   final File file, final FileTransferProtocol transferProtocol)
    throws ApplicationException {
    // currently can deal with sftp only.
    LOGGER.trace("Invoking transferFile...");
    JSch jsch = new JSch();
    try {
        Session session = jsch.getSession(username, host);
        LOGGER.debug("Session Host: " + session.getHost());
        session.setPassword(password);
        Properties properties = new Properties();
        properties.put("StrictHostKeyChecking", "no");
        session.setConfig(properties);
        LOGGER.debug("Connecting to a session Host Server...");
        session.connect();
        LOGGER.debug("session is established with host server.");
        Channel channel = session.openChannel(transferProtocol.ftpStringRepresentation());
        LOGGER.debug("Connecting to a sftp Channel...");
        channel.connect();
        LOGGER.debug("Connected with sftp Channel.");
        ChannelSftp channelSftp = (ChannelSftp) channel;
        channelSftp.put(new FileInputStream(file), file.getName());
        LOGGER.debug("File transfered successfully");
        channelSftp.exit();
        LOGGER.debug("sftp channel disconnected.");
        channel.disconnect();
        LOGGER.debug("channel disconnected.");
        session.disconnect();
        LOGGER.debug("session disconnected.");
        return true;
    } catch (JSchException | FileNotFoundException | SftpException e) {
        LOGGER.error(e.getMessage(), e.getCause());
        throw new ApplicationException(e.getMessage(), ApplicationSeverity.ERROR, e.getCause(), e);
    }
}
 
开发者ID:SanjayMadnani,项目名称:com.sanjay.common.common-utils,代码行数:47,代码来源:FileUtil.java

示例9: connect

import com.jcraft.jsch.JSch; //导入方法依赖的package包/类
/**
 * Connects to and maintains a ssh connection.  If this method is called
 * twice, a reconnection is attempted
 *
 * @throws SshException          If the members of the SshConnection class are not properly set or if
 *                               there was a problem actually connecting to the specified host.
 * @throws IllegalStateException If connect() was called once successfully. connect() and any setter
 *                               method can't be called after successfully connecting without first
 *                               disconnecting.
 */
public void connect() throws SshException {
    exceptIfAlreadyConnected();

    try {
        JSch jsch = new JSch();

        validateMembers();

        if (this.usePrivateKey) {
            jsch.addIdentity(this.privateKeyFile.getAbsolutePath());
        }

        this.sshSession = jsch.getSession(this.username, this.host, this.port);
        this.sshSession.setConfig(SSH_PROPERTIES);

        if (!this.usePrivateKey && this.password != null) {
            this.sshSession.setPassword(this.password);
        }

        this.sshSession.connect();
    } catch (JSchException e) {
        throw new SshException(e);
    }

}
 
开发者ID:houdejun214,项目名称:lakeside-java,代码行数:36,代码来源:SshConnection.java

示例10: ssh

import com.jcraft.jsch.JSch; //导入方法依赖的package包/类
private static void ssh(String user, String passwd, String host){
    try{JSch jsch = new JSch();
        session = jsch.getSession(user, host, 22);
        session.setPassword(passwd);
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();
        Channel channel = session.openChannel("shell");
        channel.connect();
        Thread.sleep(1000);
        channel.disconnect();
        session.disconnect();
    }catch(Exception e){
        e.printStackTrace();
    }
}
 
开发者ID:twister,项目名称:twister.github.io,代码行数:16,代码来源:RunnerRepository.java

示例11: initializeSftp

import com.jcraft.jsch.JSch; //导入方法依赖的package包/类
private void initializeSftp(){
    try{
        JSch jsch = new JSch();
        session = jsch.getSession(RunnerRepository.user, RunnerRepository.host, 22);
        session.setPassword(RunnerRepository.password);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        Channel channel = session.openChannel("sftp");
        channel.connect();
        connection = (ChannelSftp)channel;
    } catch (Exception e){
        e.printStackTrace();
    }
}
 
开发者ID:twister,项目名称:twister.github.io,代码行数:17,代码来源:ConfigTree.java

示例12: userpassword

import com.jcraft.jsch.JSch; //导入方法依赖的package包/类
public static boolean userpassword(String user,String password, String host){
        boolean passed = false;
            try{
                JSch jsch = new JSch();
                session = jsch.getSession(user, host, 22);
                session.setPassword(password);
                Properties config = new Properties();
                config.put("StrictHostKeyChecking", "no");
                session.setConfig(config);
                session.connect();
                Channel channel = session.openChannel("sftp");
                channel.connect();
                connection = (ChannelSftp)channel;
                try{USERHOME = connection.pwd();}
                catch(Exception e){
                    System.out.println("ERROR: Could not retrieve remote user home directory");}
                REMOTECONFIGDIRECTORY = USERHOME+"/twister/config/";
                passed = true;
            }
            catch(JSchException ex){
                if(ex.toString().indexOf("Auth fail")!=-1)
                    System.out.println("wrong user and/or password");
                else{ex.printStackTrace();
                    System.out.println("Could not connect to server");}}
//                 }
        return true;}
 
开发者ID:twister,项目名称:twister.github.io,代码行数:27,代码来源:RunnerRepository.java

示例13: scpFileFromRemoteServer

import com.jcraft.jsch.JSch; //导入方法依赖的package包/类
/**
 * 
 * Scp file from remote server
 * 
 * @param host
 * @param user
 * @param password
 * @param remoteFile
 * @param localFile
 * @throws JSchException 
 * @throws IOException 
 */
public void scpFileFromRemoteServer(String host, String user, String password, String remoteFile, String localFile) throws JSchException, IOException {
	
	String prefix = null;
	if (new File(localFile).isDirectory()) {
		prefix = localFile + File.separator;
	}

	JSch jsch = new JSch();
	Session session = jsch.getSession(user, host, 22);

	// username and password will be given via UserInfo interface.
	UserInfo userInfo = new UserInformation(password);
	session.setUserInfo(userInfo);
	session.connect();

	// exec 'scp -f remoteFile' remotely
	String command = "scp -f " + remoteFile;
	Channel channel = session.openChannel("exec");
	((ChannelExec) channel).setCommand(command);

	// get I/O streams for remote scp
	OutputStream out = channel.getOutputStream();
	InputStream in = channel.getInputStream();

	channel.connect();

	byte[] buf = new byte[1024];

	// send '\0'
	buf[0] = 0;
	out.write(buf, 0, 1);
	out.flush();
	
	readRemoteFileAndWriteToLocalFile(localFile, prefix, out, in, buf);

	session.disconnect();		
}
 
开发者ID:capitalone,项目名称:Hydrograph,代码行数:50,代码来源:SCPUtility.java

示例14: sshCall

import com.jcraft.jsch.JSch; //导入方法依赖的package包/类
protected void sshCall(String username, String password, SshExecutor executor, String channelType) {
    try {
        JSch jsch = new JSch();
        Session session = jsch.getSession(username, props.getShell().getHost(), props.getShell().getPort());
        session.setPassword(password);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        Channel channel = session.openChannel(channelType);
        PipedInputStream pis = new PipedInputStream();
        PipedOutputStream pos = new PipedOutputStream();
        channel.setInputStream(new PipedInputStream(pos));
        channel.setOutputStream(new PipedOutputStream(pis));
        channel.connect();
        try {
            executor.execute(pis, pos);
        } finally {
            pis.close();
            pos.close();
            channel.disconnect();
            session.disconnect();
        }
    } catch(JSchException | IOException ex) {
        fail(ex.toString());
    }
}
 
开发者ID:anand1st,项目名称:sshd-shell-spring-boot,代码行数:28,代码来源:AbstractSshSupport.java

示例15: executeSSH

import com.jcraft.jsch.JSch; //导入方法依赖的package包/类
private boolean executeSSH(){ 
	//get deployment descriptor, instead of this hard coded.
	// or execute a script on the target machine which download artifact from nexus
       String command ="nohup java -jar -Dserver.port=8091 ./work/codebox/chapter6/chapter6.search/target/search-1.0.jar &";
      try{	
   	   System.out.println("Executing "+ command);
          java.util.Properties config = new java.util.Properties(); 
          config.put("StrictHostKeyChecking", "no");
          JSch jsch = new JSch();
          Session session=jsch.getSession("rajeshrv", "localhost", 22);
          session.setPassword("rajeshrv");
          
          session.setConfig(config);
          session.connect();
          System.out.println("Connected");
           
          ChannelExec channelExec = (ChannelExec)session.openChannel("exec");
          InputStream in = channelExec.getInputStream();
          channelExec.setCommand(command);
          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();
          session.disconnect();

          System.out.println("Done!");

      }catch(Exception e){
          e.printStackTrace();
          return false;
      }
	
	return true;
}
 
开发者ID:rajeshrv,项目名称:SpringMicroservice,代码行数:41,代码来源:DeploymentEngine.java


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