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


Java Channel.getOutputStream方法代碼示例

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


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

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

示例2: testRead

import com.jcraft.jsch.Channel; //導入方法依賴的package包/類
@Test
public void testRead(TestContext context) throws Exception {
  Async async = context.async();
  termHandler = term -> {
    term.stdinHandler(s -> {
      context.assertEquals("hello", s);
      async.complete();
    });
  };
  startShell();
  Session session = createSession("paulo", "secret", false);
  session.connect();
  Channel channel = session.openChannel("shell");
  channel.connect();
  OutputStream out = channel.getOutputStream();
  out.write("hello".getBytes());
  out.flush();
  channel.disconnect();
  session.disconnect();
}
 
開發者ID:vert-x3,項目名稱:vertx-shell,代碼行數:21,代碼來源:SSHServerTest.java

示例3: doSingleTransfer

import com.jcraft.jsch.Channel; //導入方法依賴的package包/類
private void doSingleTransfer() throws IOException, JSchException {
    StringBuilder sb = new StringBuilder("scp -t ");
    if (getPreserveLastModified()) {
        sb.append("-p ");
    }
    if (getCompressed()) {
        sb.append("-C ");
    }
    sb.append(remotePath);
    final String cmd = sb.toString();
    final Channel channel = openExecChannel(cmd);
    try {
        final OutputStream out = channel.getOutputStream();
        final InputStream in = channel.getInputStream();

        channel.connect();

        waitForAck(in);
        sendFileToRemote(localFile, in, out);
    } finally {
        if (channel != null) {
            channel.disconnect();
        }
    }
}
 
開發者ID:apache,項目名稱:ant,代碼行數:26,代碼來源:ScpToMessage.java

示例4: doMultipleTransfer

import com.jcraft.jsch.Channel; //導入方法依賴的package包/類
private void doMultipleTransfer() throws IOException, JSchException {
    StringBuilder sb = new StringBuilder("scp -r -d -t ");
    if (getPreserveLastModified()) {
        sb.append("-p ");
    }
    if (getCompressed()) {
        sb.append("-C ");
    }
    sb.append(remotePath);
    final Channel channel = openExecChannel(sb.toString());
    try {
        final OutputStream out = channel.getOutputStream();
        final InputStream in = channel.getInputStream();

        channel.connect();

        waitForAck(in);
        for (Directory current : directoryList) {
            sendDirectory(current, in, out);
        }
    } finally {
        if (channel != null) {
            channel.disconnect();
        }
    }
}
 
開發者ID:apache,項目名稱:ant,代碼行數:27,代碼來源:ScpToMessage.java

示例5: scpFileFromRemoteServer

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

示例6: runShellCommand

import com.jcraft.jsch.Channel; //導入方法依賴的package包/類
@Override
public RemoteCommandReturnInfo runShellCommand(RemoteSystemConnection remoteSystemConnection, String command, long timeout) {
    final ChannelSessionKey channelSessionKey = new ChannelSessionKey(remoteSystemConnection, ChannelType.SHELL);
    LOGGER.debug("channel session key = {}", channelSessionKey);
    Channel channel = null;
    try {
        channel = getChannelShell(channelSessionKey);

        final InputStream in = channel.getInputStream();
        final OutputStream out = channel.getOutputStream();

        LOGGER.debug("Executing command \"{}\"", command);
        out.write(command.getBytes(StandardCharsets.UTF_8));
        out.write(CRLF.getBytes(StandardCharsets.UTF_8));
        out.write("echo 'EXIT_CODE='$?***".getBytes(StandardCharsets.UTF_8));
        out.write(CRLF.getBytes(StandardCharsets.UTF_8));
        out.write("echo -n -e '\\xff'".getBytes(StandardCharsets.UTF_8));
        out.write(CRLF.getBytes(StandardCharsets.UTF_8));
        out.flush();

        return getShellRemoteCommandReturnInfo(command, in, timeout);
    } catch (final Exception e) {
        final String errMsg = MessageFormat.format("Failed to run the following command: {0}", command);
        LOGGER.error(errMsg, e);
        throw new JschServiceException(errMsg, e);
    } finally {
        if (channel != null) {
            channelPool.returnObject(channelSessionKey, channel);
            LOGGER.debug("channel {} returned", channel.getId());
        }
    }
}
 
開發者ID:cerner,項目名稱:jwala,代碼行數:33,代碼來源:JschServiceImpl.java

示例7: setChannel

import com.jcraft.jsch.Channel; //導入方法依賴的package包/類
protected void setChannel(Channel channel) throws IOException {
    this.channel = channel;
    if (channel == null) {
        output = null;
        input = null;
    } else {
        output = channel.getOutputStream();
        input = channel.getInputStream();
    }
}
 
開發者ID:kemitix,項目名稱:kxssh,代碼行數:11,代碼來源:JSchIOChannel.java

示例8: SshChannel

import com.jcraft.jsch.Channel; //導入方法依賴的package包/類
SshChannel(Channel channel) throws SshException {
	try {
		in = channel.getInputStream();
		out = channel.getOutputStream();
		channel.connect();
	} catch (IOException | JSchException ex) {
		throw new SshException(ex);
	}
}
 
開發者ID:nyrkovalex,項目名稱:java-seed,代碼行數:10,代碼來源:SshChannel.java

示例9: execute

import com.jcraft.jsch.Channel; //導入方法依賴的package包/類
/**
 * Carry out the transfer.
 * @throws IOException on i/o errors
 * @throws JSchException on errors detected by scp
 */
@Override
public void execute() throws IOException, JSchException {
    String command = "scp -f ";
    if (isRecursive) {
        command += "-r ";
    }
    if (getCompressed()) {
        command += "-C ";
    }
    command += remoteFile;
    final Channel channel = openExecChannel(command);
    try {
        // get I/O streams for remote scp
        final OutputStream out = channel.getOutputStream();
        final InputStream in = channel.getInputStream();

        channel.connect();

        sendAck(out);
        startRemoteCpProtocol(in, out, localFile);
    } finally {
        if (channel != null) {
            channel.disconnect();
        }
    }
    log("done\n");
}
 
開發者ID:apache,項目名稱:ant,代碼行數:33,代碼來源:ScpFromMessage.java

示例10: execCmd

import com.jcraft.jsch.Channel; //導入方法依賴的package包/類
/**
 * Execute command
 * @param host
 * @param user
 * @param passwd
 * @param cmd
 * @return String the reply of remote session
 */
public String execCmd (String host, String user, String passwd, String cmd){
    String replyy = "";
    String reply = null;
    try{
        JSch jsch=new JSch();
        Session session=jsch.getSession(user, host, 22);
        UserInfo ui = new MyUserInfo(passwd);
        session.setUserInfo(ui);
        session.setTimeout(600000);
        session.connect();
        Channel channel=session.openChannel("exec");
        ((ChannelExec)channel).setCommand(cmd);
        channel.setInputStream(null);
        InputStreamReader in = new InputStreamReader(channel.getInputStream());
        OutputStreamWriter out = new OutputStreamWriter(channel.getOutputStream());
        BufferedWriter bw = new BufferedWriter(out);
        BufferedReader br = new BufferedReader(in);
        channel.connect();
        while ((reply = br.readLine()) != null) {
            bw.write(reply);
            replyy=replyy+"\n"+reply;
            bw.flush();
            Thread.sleep(100);
        }
        while(true){
            if(channel.isClosed()){
                break;
            } try{
                Thread.sleep(1500);
            } catch(Exception ee){
            }
        }
        in.close();
        out.close();
        br.close();
        bw.close();
        channel.disconnect();
        session.disconnect();
    }
    catch(Exception e){
        log.error("ERROR , Possible no connection with : "+user+" "+passwd+ " "+host+"\n\t\t please check LAN and vpn connection or host");
    }
    return replyy;
}
 
開發者ID:GiannisPapadakis,項目名稱:seletest,代碼行數:53,代碼來源:SSHUtils.java

示例11: upload

import com.jcraft.jsch.Channel; //導入方法依賴的package包/類
public void upload(String directory, File file,String name) throws Exception{
	if(notify != null){
		notify.terminal("upload " + file.getPath());
	}
	boolean ptimestamp = true;
	String command = "scp " + (ptimestamp ? "-p" : "") + " -t " + directory;
	Channel channel = session.openChannel("exec");
	((ChannelExec) channel).setCommand(command);
	OutputStream out = channel.getOutputStream();
	InputStream in = channel.getInputStream();
	try {
		channel.connect();
		if (checkAck(in) != 0) {
			return;
		}
		if (ptimestamp) {
			command = "T " + (file.lastModified() / 1000) + " 0";
			command += (" " + (file.lastModified() / 1000) + " 0\n");
			out.write(command.getBytes());
			out.flush();
			if (checkAck(in) != 0) {
				return;
			}
		}
		long filesize = file.length();
		command = "C0644 " + filesize + " " + name + "\n";
		out.write(command.getBytes());
		out.flush();
		if (checkAck(in) != 0) {
			return;
		}
		FileInputStream fis = new FileInputStream(file);
		byte[] buf = new byte[1024];
		while (true) {
			int len = fis.read(buf, 0, buf.length);
			if (len <= 0)
				break;
			out.write(buf, 0, len);
		}
		fis.close();
		fis = null;
		buf[0] = 0;
		out.write(buf, 0, 1);
		out.flush();
		if (checkAck(in) != 0) {
			return;
		}
		if(notify != null){
			notify.terminal("upload success");
		}
	}finally{
		out.close();
		channel.disconnect();
	}
}
 
開發者ID:yanfanvip,項目名稱:RedisClusterManager,代碼行數:56,代碼來源:ScpClient.java

示例12: onTrigger

import com.jcraft.jsch.Channel; //導入方法依賴的package包/類
@Override
public void onTrigger(final ProcessContext context, final ProcessSession processSession) {
    List<FlowFile> flowFiles = processSession.get(batchSize);
    if (flowFiles.isEmpty()) {
        return;
    }

    Session jschSession = null;
    Channel channel = null;
    try {
        jschSession = openSession(context);
        final String remotePath = context.getProperty(REMOTE_PATH).evaluateAttributeExpressions().getValue();
        channel = openExecChannel(context, jschSession, "scp -r -d -t " + remotePath);

        InputStream channelIn = channel.getInputStream();
        OutputStream channelOut = channel.getOutputStream();

        channel.connect();
        waitForAck(channelIn);

        ListIterator<FlowFile> fileIt = flowFiles.listIterator();
        while (fileIt.hasNext()) {
            final FlowFile flowFile = fileIt.next();

            // conditionally reject files that are zero bytes or less
            if (context.getProperty(REJECT_ZERO_BYTE).asBoolean() && flowFile.getSize() == 0) {
                logger.warn("Rejecting {} because it is zero bytes", new Object[]{flowFile});
                processSession.transfer(processSession.penalize(flowFile), REL_REJECT);
                fileIt.remove();
                continue;
            }

            final String filename = flowFile.getAttribute(CoreAttributes.FILENAME.key());
            final String permissions = context.getProperty(PERMISSIONS).evaluateAttributeExpressions(flowFile).getValue();

            // destination path + filename
            // final String fullPath = buildFullPath(context, flowFile, filename);

            processSession.read(flowFile, new InputStreamCallback() {
                @Override
                public void process(final InputStream flowFileIn) throws IOException {
                    // send "C0644 filesize filename", where filename should not include '/'
                    StringBuilder command = new StringBuilder("C").append(permissions).append(' ');
                    command.append(flowFile.getSize()).append(' ');
                    command.append(filename).append('\n');

                    channelOut.write(command.toString().getBytes(StandardCharsets.UTF_8));
                    channelOut.flush();
                    waitForAck(channelIn);

                    IOUtils.copy(flowFileIn, channelOut);
                    channelOut.flush();
                    sendAck(channelOut);
                    waitForAck(channelIn);
                }
            });

            processSession.transfer(flowFile, REL_SUCCESS);
            processSession.getProvenanceReporter().send(flowFile, remotePath);
            fileIt.remove();
            if (logger.isDebugEnabled()) {
                logger.debug("Sent {} to remote host", new Object[]{flowFile});
            }
        }

    } catch (JSchException | IOException ex) {
        context.yield();
        logger.error("Unable to create session to remote host due to {}", new Object[]{ex}, ex);
        processSession.transfer(flowFiles, REL_FAILURE);

    } finally {
        if (channel != null) {
            channel.disconnect();
        }
        if (jschSession != null) {
            jschSession.disconnect();
        }
    }
}
 
開發者ID:Asymmetrik,項目名稱:nifi-nars,代碼行數:80,代碼來源:PutScp.java

示例13: scpFile

import com.jcraft.jsch.Channel; //導入方法依賴的package包/類
/**
 * Scps a file to the given roboRio session.
 *
 * @param tgzFile        The tar file to scp
 * @param roboRioSession The roboRio to scp to
 * @throws JSchException If a ssh error occurs
 * @throws IOException   If an IO error occurs
 */
private void scpFile(File tgzFile, Session roboRioSession) throws JSchException, IOException {
    Platform.runLater(() -> commandLabel.setText("Copying " + tgzFile.getAbsolutePath() + " to the roboRIO"));

    // Execute the scp -t /home/admin/JRE.tar.gz command. This opens a channel waiting for the data on the
    // roboRio side. This code is adapted from an official JSch example, found here:
    // http://www.jcraft.com/jsch/examples/ScpTo.java.html
    Channel scpChannel = roboRioSession.openChannel(EXEC_COMMAND);
    OutputStream scpOutput = scpChannel.getOutputStream();
    InputStream scpInput = scpChannel.getInputStream();
    ((ChannelExec) scpChannel).setCommand(SCP_T_COMMAND);
    scpChannel.connect();

    // Create our command for sending the file size
    String command = "C0644 " + tgzFile.length() + " " + JRE_TGZ_NAME + "\n";
    m_logger.debug("Size command is " + command);
    scpOutput.write(command.getBytes());
    scpOutput.flush();
    if (checkAck(scpInput) != SUCCESS) {
        throw new IOException("Unknown error when sending file size");
    }

    BufferedInputStream fis = new BufferedInputStream(new FileInputStream(tgzFile));
    byte[] buffer = new byte[BUFF_SIZE];
    while (true) {
        int len = fis.read(buffer);
        if (len < 0) {
            break;
        }
        scpOutput.write(buffer);
    }
    fis.close();
    // Send the final \0
    scpOutput.write('\0');
    scpOutput.flush();
    if (checkAck(scpInput) != SUCCESS) {
        throw new IOException("Failure when scping the JRE");
    }
    scpOutput.close();
    scpInput.close();
    scpChannel.disconnect();
}
 
開發者ID:wpilibsuite,項目名稱:java-installer,代碼行數:50,代碼來源:DeployController.java

示例14: pairComputer

import com.jcraft.jsch.Channel; //導入方法依賴的package包/類
public void pairComputer(final Context con) {
    Thread thread = new Thread() {
        @Override
        public void run() {
            try {
                Channel channel = session.openChannel("shell");
                OutputStream ops = channel.getOutputStream();
                PrintStream ps = new PrintStream(ops, true);

                channel.connect();
                ps.println("cd " + device.directory);
                ps.println("java -jar limelight.jar pair " + device.hostIP);
                //give commands to be executed inside println.and can have any no of commands sent.
                ps.close();

                InputStream in = channel.getInputStream();
                byte[] tmp = new byte[1024];
                while (true) {
                    while (in.available() > 0) {
                        int i = in.read(tmp, 0, 1024);
                        if (i < 0) break;

                        String tmpString = new String(tmp, 0, i);
                        System.out.println(tmpString);

                        if(tmpString.contains("Please enter the following")){
                            String pairCode = tmpString.replaceAll("\\D+","");
                            dispatchEventBus(con, new PairEvent(pairCode));
                        } else if(tmpString.contains("Paired successfully")){
                            dispatchEventBus(con, new PairEvent(true));
                            break;
                        } else if(tmpString.contains("Pairing failed")){
                            dispatchEventBus(con, new PairEvent(false));
                            break;
                        } else if(tmpString.contains("Already paired")){
                            dispatchEventBus(con, new PairEvent(true));
                            break;
                        } else if(tmpString.contains("timed out")){
                            dispatchEventBus(con, new PairEvent(false));
                            break;
                        }
                    }

                    if (channel.isClosed()) {
                        if (in.available() > 0) continue;
                        System.out.println("exit-status: " + channel.getExitStatus());
                        break;
                    }
                    try {
                        Thread.sleep(100);
                    } catch (Exception ee) {
                    }
                }
                channel.disconnect();
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    };

    thread.start();
}
 
開發者ID:ChrisOwen101,項目名稱:MoonlightEmbeddedController,代碼行數:63,代碼來源:SSHManager.java

示例15: createFolderAndDownloadFiles

import com.jcraft.jsch.Channel; //導入方法依賴的package包/類
public void createFolderAndDownloadFiles(final Context con) {
    Thread thread = new Thread() {
        @Override
        public void run() {
            try {
                Channel channel=session.openChannel("shell");
                OutputStream ops = channel.getOutputStream();
                PrintStream ps = new PrintStream(ops, true);

                channel.connect();
                ps.println("mkdir limelight");
                ps.println("cd limelight");
                ps.println("wget https://github.com/irtimmer/limelight-embedded/releases/download/v1.2.2/libopus.so");
                ps.println("wget https://github.com/irtimmer/limelight-embedded/releases/download/v1.2.2/limelight.jar");
                //give commands to be executed inside println.and can have any no of commands sent.
                ps.close();


                InputStream in = channel.getInputStream();
                byte[] tmp = new byte[1024];
                while (true) {
                    while (in.available() > 0) {
                        int i = in.read(tmp, 0, 1024);
                        if (i < 0) break;

                        String tmpString = new String(tmp, 0, i);
                        System.out.println(tmpString);

                        if(tmpString.contains("%")){
                            String perc = tmpString.substring(0, tmpString.indexOf("%")).trim();

                            if(tmpString.contains("limelight.jar' saved")){
                                System.out.println("exit-status: " + channel.getExitStatus());
                                dispatchEventBus(con, new LimelightDownloadedEvent(true));
                                break;
                            }

                            if(isNumeric(perc)){
                                dispatchEventBus(con, new LimelightDownloadedEvent(Integer.parseInt(perc)));
                            } else {
                                dispatchEventBus(con, new LimelightDownloadedEvent(-1));
                            }
                        }
                    }

                    if (channel.isClosed()) {
                        if (in.available() > 0) continue;
                        System.out.println("exit-status: " + channel.getExitStatus());

                        dispatchEventBus(con, new LimelightDownloadedEvent(true));
                        break;
                    }
                    try {
                        Thread.sleep(100);
                    } catch (Exception ee) {
                    }
                }
                channel.disconnect();
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    };

    thread.start();
}
 
開發者ID:ChrisOwen101,項目名稱:MoonlightEmbeddedController,代碼行數:67,代碼來源:SSHManager.java


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