How to read the output of single command

1,313 views
Skip to first unread message

shve...@gmail.com

unread,
Jul 31, 2014, 6:10:57 AM7/31/14
to java-e...@googlegroups.com
Hi, Alexey!
Thank you for your job!
I'm sorry for a stupid question, nut how can I read the output of single command?
For example (for ssh): expect.sendLine("pwd")
I want to get the output of pwd (something like /usr/home). How can I get it?

Alexey Gavrilov

unread,
Jul 31, 2014, 10:17:28 AM7/31/14
to shve...@gmail.com, java-e...@googlegroups.com
Hi!

You can try something like: expect.sendLine("pwd").expect(contains("\n")).getBefore() .

Regards,
Alexey



--
You received this message because you are subscribed to the Google Groups "Yet another Expect for Java" group.
To unsubscribe from this group and stop receiving emails from it, send an email to java-expecti...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Игорь Швецов

unread,
Jul 31, 2014, 10:50:57 AM7/31/14
to Alexey Gavrilov, java-e...@googlegroups.com
Thank you for your response!
But i meant I want to get String with output of command.

С уважением, Швецов Игорь

Alexey Gavrilov

unread,
Jul 31, 2014, 3:51:41 PM7/31/14
to Игорь Швецов, java-e...@googlegroups.com
[now cc to the group]

Well, it supposes to return the output of the pwd command.  The "contains" matcher is awaiting for the end of the line, while the getBefore method should returns the preceding string. 

I`ve just pushed an example of reading the output of the pwd command  from a forked shell. See line #46:
https://github.com/Alexey1Gavrilov/ExpectIt/blob/master/expectit-core/src/test/java/net/sf/expectit/ProcessExample.java

If it does not work for you, can please post your code?

Regards,
Alexey

Игорь Швецов

unread,
Aug 1, 2014, 12:54:42 AM8/1/14
to Alexey Gavrilov, java-e...@googlegroups.com
This line "System.out.println("PWD:" + expect.sendLine("pwd").expect(contains("\n")).getBefore());" outputs this:
"PWD: pwd"
And I want to get: "/usr/home..."

С уважением, Швецов Игорь


Игорь Швецов

unread,
Aug 1, 2014, 1:58:30 AM8/1/14
to Alexey Gavrilov, java-e...@googlegroups.com
System.out.println("PWD:" + expect.sendLine("pwd").expect(contains("\n")).getBefore()) - in such way Expect finds first entry of ("\n") and outputs all chars before it. And it will be exactly "pwd". Is there some way to find the last entry of "\n"?

С уважением, Швецов Игорь


Alexey Gavrilov

unread,
Aug 1, 2014, 3:18:20 AM8/1/14
to Игорь Швецов, java-e...@googlegroups.com
The example which I pointed you to prints the result of the pwd command, not the command itself.

Looks like you are getting the command echo of from your service. Are you connecting to some host over SSH? 
Which version are you using?  Can I see the code? I

Игорь Швецов

unread,
Aug 1, 2014, 3:30:47 AM8/1/14
to Alexey Gavrilov, java-e...@googlegroups.com
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import net.sf.expectit.Expect;
import net.sf.expectit.ExpectBuilder;
import net.sf.expectit.echo.EchoOutput;

import java.io.IOException;
import java.util.Properties;

import static net.sf.expectit.filter.Filters.removeColors;
import static net.sf.expectit.filter.Filters.removeNonPrintable;
import static net.sf.expectit.matcher.Matchers.contains;

/**
 * An example of interacting with SSH server
 */
public class SshExample {

    public static String host = "10.149.127.141";
    public static String user = "support";
    public static String password = "somepassword";



    public static void main(String[] args) throws JSchException, IOException {
        JSch jSch = new JSch();
        Session 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("shell");

        Expect expect = new ExpectBuilder()
                .withOutput(channel.getOutputStream())
                .withInputs(channel.getInputStream(), channel.getExtInputStream())
                .withEchoInput(System.out)
                .withEchoOutput(new EchoOutput() {
                    @Override
                    public void onReceive(int input, String string) throws IOException {
                        System.out.println("RECEIVE:" + string);
                    }

                    @Override
                    public void onSend(String string) throws IOException {
                        System.out.println("SEND:" + string);
                    }
                })
                .withInputFilters(removeColors(), removeNonPrintable())
                .withErrorOnTimeout(true)
                .build();
        try {
            channel.connect();
            expect.expect(contains("$"));
            System.out.println("PWD:" + expect.sendLine("pwd").expect(contains("\n")).getBefore());
        } finally {
            channel.disconnect();
            session.disconnect();
            expect.close();
        }
    }
}

And the output:


RECEIVE:Last login: Fri Aug  1 16:04:05 2014 from 10.112.142.198
Copyright (c) 1980, 1983, 1986, 1988, 1990, 1991, 1993, 1994
The Regents of the University of California.  All rights reserved.

FreeBSD 6.1-RELEASE (GENERIC) #0: Fri Mar 21 13:32:37 UTC 2008

Welcome to FreeBSD!

Before seeking technical support, please use the following resources:

o  Security advisories and updated errata information for all releases are
   at http://www.FreeBSD.org/releases/ - always consult the ERRATA section
   for your release first as it's updated frequently.

o  The Handbook and FAQ documents are at http://www.FreeBSD.org/ and,
   along with the mailing lists, can be searched by going to
   http://www.FreeBSD.org/search/.  If the doc distribution has
   been installed, they're also available formatted in /usr/share/doc.

If you still have a question or problem, please take the output of
`uname -a', along with any relevant error messages, and email it
as a question to the ques...@FreeBSD.org mailing list
RECEIVE:.  If you are
unfamiliar with FreeBSD's directory layout, please refer to the hier(7)
manual page.  If you are not familiar with manual pages, type `man man'.

You may also use sysinstall(8) to re-enter the installation and
configuration utility.  Edit /etc/motd to change this login announcement.

SEND:pwd

RECEIVE:pwd

PWD: pwd
Disconnected from the target VM, address: '127.0.0.1:52490', transport: 'socket'

Process finished with exit code 0

С уважением, Швецов Игорь


Alexey Gavrilov

unread,
Aug 1, 2014, 3:47:37 AM8/1/14
to Игорь Швецов, Alexey Gavrilov, java-e...@googlegroups.com
Thank you for the code. 
Yes, you are getting command echo for some reason.

Are using 0.4.0? If not, then can you try it? What happen if you connect to the server using normal ssh? Can you see that the server returns 'pwd'?




1. aug. 2014, в 10:30, Игорь Швецов <shve...@gmail.com> написал(а):

Игорь Швецов

unread,
Aug 1, 2014, 4:14:20 AM8/1/14
to Alexey Gavrilov, Alexey Gavrilov, java-e...@googlegroups.com
Yes, I'm using 0.4.0.
I have tried another server - the same situation.
Have tried send "stty -echo" with no result.

But when I put command two times it helped me. Like this:
System.out.println("PWD:" + expect.sendLine("pwd").expect(contains("\n")).getBefore());
System.out.println("PWD:" + expect.sendLine("pwd").expect(contains("\n")).getBefore());

Then the output:
SEND:pwd

RECEIVE:pwd

PWD: pwd
SEND:pwd

RECEIVE:/usr/home/support
PWD:/usr/home/support

Process finished with exit code 0

С уважением, Швецов Игорь


Игорь Швецов

unread,
Aug 1, 2014, 4:28:47 AM8/1/14
to Alexey Gavrilov, Alexey Gavrilov, java-e...@googlegroups.com
But this workaround won't help me. Because I need to telnet to the router and then pass the command and get output of router. I can't pass this command two times.

My code:
try {
            channel.connect();
            expect.expect(contains("$"));
            expect.sendLine("stty -echo");
            expect.sendLine("telnet 192.168.11.62");
            expect.expect(contains("UserName:"));
            expect.sendLine("admin");
            expect.expect(contains("PassWord:"));
            expect.sendLine("password");
            expect.expect(contains("#"));
            System.out.println("PWD:" + expect.sendLine("show ports 1").expect(contains("\n")).getBefore());
            System.out.println("PWD:" + expect.sendLine("show ports 1").expect(contains("\n")).getBefore());
        } finally {
            channel.disconnect();
            session.disconnect();
            expect.close();
        }

And output:
SEND:telnet 192.168.11.62

RECEIVE:telnet 192.168.11.62

RECEIVE:Trying 192.168.11.62...

RECEIVE:Connected to 192.168.11.62.
Escape character is '^]'.

RECEIVE:mand Line Interface

                            Firmware: Build 2.92.B04
           Copyright(C) 2008 D-Link Corporation. All rights reserved.
UserName:
SEND:admin

RECEIVE:a
RECEIVE:dmin
PassWord:
SEND:password

RECEIVE:*
RECEIVE:******

DES-3028:5#
SEND:show ports 1

RECEIVE:s
RECEIVE:how ports 1
Command: show ports 1

 Port   State/          Settings             Connection           Address 
        MDI       Speed/Duplex/FlowCtrl  Speed/Duplex/FlowCtrl    Learning
 -----  --------  ---------------------  ---------------------    --------
 1      Enabled   Auto/Disabled          LinkDown                 Enabled 
        Auto          
                                                                               
                                                     
PWD:show ports 1
SEND:show ports 1

Command: show ports 1

Process finished with exit code 0


I want to get th the String what Command outputs (device info).

С уважением, Швецов Игорь


Alexey Gavrilov

unread,
Aug 1, 2014, 4:21:15 PM8/1/14
to Игорь Швецов, java-e...@googlegroups.com
Hi,

You can try to ignore the command echo either by expecting two new lines in a row :
    expect.expect(times(2, contains("\n"))).getResults().get(1).getBefore());

or using a multi-line regular expression:
    expect.expect(regexp("(?m)\\n(.*)$")).group(1);

Please let me know if it works for you.


In a meanwhile, I will think about ability to ignore the command echo on the "expect" side.

Regards,
Alexey

Игорь Швецов

unread,
Aug 2, 2014, 2:22:06 AM8/2/14
to Alexey Gavrilov, java-e...@googlegroups.com
Alexey, I'm sorry but it doesn't help me. In first case (expect.expect(times(2, contains("\n"))).getResults().get(1).getBefore());) there's again "pwd".
In another case (expect.expect(regexp("(?m)\\n(.*)$")).group(1);) there's no output.
As I mentioned in previous message, I see in console:
SEND:show ports 1

RECEIVE:s
RECEIVE:how ports 1
Command: show ports 1

 Port   State/          Settings             Connection           Address 
        MDI       Speed/Duplex/FlowCtrl  Speed/Duplex/FlowCtrl    Learning
 -----  --------  ---------------------  ---------------------    --------
 1      Enabled   Auto/Disabled          LinkDown                 Enabled 
        Auto          
                       

How can I grab it into the String?


С уважением, Швецов Игорь


Alexey Gavrilov

unread,
Aug 3, 2014, 7:46:01 AM8/3/14
to Игорь Швецов, java-e...@googlegroups.com
Hi,

For getting the output from the pwd command you can try more robust regexp: regexp("(?m)\\n([^\\n]*)\\n") . If it does not work, you can try to do dowble expect call: first wait for the new line from echo, then expect the string ended with a new line.

For getting the multi-line output take a look at the "ls -l" command example I`ve just pushed. It also has a pwd part:
https://github.com/Alexey1Gavrilov/ExpectIt/blob/master/expectit-core/src/test/java/net/sf/expectit/SshLocalhostExample.java

I have tested it on my local linux box.

Keep me posted :).

Игорь Швецов

unread,
Aug 10, 2014, 11:29:00 PM8/10/14
to Alexey Gavrilov, java-e...@googlegroups.com
Hi, Alexey!
I'm sorry, there wasn't possibility to check out last week...
I've tried  0.5.0. "ls -l" works fine for me. Thank you for your job!

But in my case with telnet to routers it's more complicated. I'm playing with regexps...
Thank you!

С уважением, Швецов Игорь


Reply all
Reply to author
Forward
0 new messages