简体   繁体   中英

Using Jsch to SSH to my Raspberry Pi and Shutdown command not working…

hopefully someone might be able to show me what I'm doing wrong.

I'm writing a small android app to send commands to SSH servers. I have the following code in a separate method running on its own thread into which I pass username, server, and command.

I send a command and it puts a toast on the screen showing the output of that command. Now the code works with my windows machine running an SSH server. It also works (sort of) with my raspberry pi. However, if I send a command like "pwd;" to the pi I get the current directory back. Cool. If i send "sudo touch /media/MYUSBSTICK/testfile" it will create a file in the path specified. If I send "ls /" I get a list of everything in the root directory. "sudo ls /" also works.

HOWEVER... if I send "sudo shutdown -h now", or even just "shutdown" as a command using the exact same code I get nothing. It doesn't seem to execute and I get nothing back in my input buffer. If i do it from a SSH client connected directly with the Pi this works. I tried "sudo halt" and this also did nothing and returned nothing.

How come some commands work and other don't? Am I missing something obvious here? Is there some obvious mistake in my code?

Thanks

Nat

I there something special about

    try {
        JSch jsch = new JSch();
        Session session = jsch.getSession(username, server, 22);
        session.setPassword(password);

        // Avoid asking for key confirmation
        Properties prop = new Properties();
        prop.put("StrictHostKeyChecking", "no");
        session.setConfig(prop);

        session.connect(10000);


        ChannelExec channel=(ChannelExec) session.openChannel("exec");
        BufferedReader in=new BufferedReader(new InputStreamReader(channel.getInputStream()));

        channel.setCommand(command); //could be "pwd;" or "sudo shutdown -h now"
        channel.connect();

        String msg=null;
        String wholemessage = "";

        while ((msg = in.readLine()) != null) {
            wholemessage += msg + "\n";

        }

        Thread.sleep(8000);

        channel.disconnect();
        session.disconnect();


        final String thereturnresult = wholemessage;
        final String tempcommand = command;

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), thereturnresult ,Toast.LENGTH_SHORT).show();
            }
        });
    }

Ok worked this out myself.

The trick is to capture the error data as well with channel.getErrStream() then all becomes clear...

Hope this helps someone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM