What is the difference between the 'shell' channel and the 'exec' channel in JSch

前端 未结 4 1908
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-29 05:36

I want to be able to send many consecutive command represented as strings within a Java application to a SSH server for execution. Should I use:

Channel cha         


        
4条回答
  •  无人及你
    2020-11-29 06:37

    well, I found out that this works and it's really convenient if you want to preserve state like a regular shell would:

    Session session = jsch.getSession(user, host, 22);
    
    Channel channel = session.openChannel("shell");
    
    OutputStream inputstream_for_the_channel = channel.getOutputStream();
    PrintStream commander = new PrintStream(inputstream_for_the_channel, true);
    
    channel.setOutputStream(System.out, true);
    
    channel.connect();
    
    commander.println("ls -la");    
    commander.println("cd folder");
    commander.println("ls -la");
    commander.println("exit");
    commander.close();
    
    do {
        Thread.sleep(1000);
    } while(!channel.isEOF());
    
    session.disconnect();
    

    You could change

    channel.setOutputStream(System.out, true);
    

    with

    InputStream outputstream_from_the_channel = channel.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(outputstream_from_the_channel));
    String line;
    while ((line = br.readLine()) != null)
        System.out.print(line+"\n");
    

    if you want more control on the output.

    =============================================================================

    EDITED: follow up

    why sometimes the commands I send through the PrintStream appear randomly in the output. i.e. the following code:

    shell[0].println("cd ..");
    shell[0].println("cd ..");
    shell[0].println("ls -la");
    shell[0].println("exit");
    

    produces this: (marked with {thing} are things that shouldnt be there!)

    Last login: Thu Jul 21 21:49:13 2011 from gateway

    Manifests: trunk-latest

    [host ~]$ cd ..
    {cd ..}[host home]$
    [host home]$ cd ..
    [host /]$
    [host /]$ ls -la
    {exit}

    total 9999
    ---------- 27 root root 4096 Jan 26 2010 .
    ---------- 27 root root 4096 Jan 26 2010 ..
    ---------- 1 root root 0 Mar 14 19:16 .autojyk
    ---------- 1 root root 0 Feb 9 2009 .automan
    ---------- 1 root root 3550 May 14 2010 .bash_history
    d--------- 2 root root 4096 Apr 26 04:02 put
    d--------- 5 root root 4024 Apr 25 19:31 boot
    [m[host /]$
    [host /]$ exit
    logout

提交回复
热议问题