macintoshgeek
Posts: 24
Joined: Sun Feb 24, 2013 1:21 am

Using SSHJ to send SSH commands to Raspberry Pi in Java App

Tue Mar 19, 2013 2:53 am

Hello,
I want to make a java application that will do some simple comands for my Raspberry Pi using SSH. I found that the SSHJ library should do the trick, but I'm having trouble trying to figure out exactly how to use it.

Does anyone have any experience with it? The examples don't seem to help me much, seen here:
https://github.com/shikhar/sshj/tree/ma ... a/examples

Let's say my Pi is at 192.168.1.xxx, with default username "pi" and password "raspberry" and I want to do a sudo reboot. How could I do that using SSHJ?

Thanks!

User avatar
azeam
Posts: 194
Joined: Fri Oct 26, 2012 11:13 pm
Contact: Website

Re: Using SSHJ to send SSH commands to Raspberry Pi in Java

Tue Mar 19, 2013 9:58 am

The problem with SSHJ is that there's (afaik) no easy way to use it with interactive sessions (when it asks for the sudo password) without writing a GUI application and implement the PTY function, so you'll probably need to send the password in one command, like

Code: Select all

echo raspberry | sudo -S reboot
If you do it that way it's best to not hard code the password, but let the user enter it some way. Another (more secure) option would be to set up ssh keys (using BouncyCastle) and log in as root (instead of pi) without having to enter a password and a third option would be to just login as root with a password or (not recommended) remove the sudo password. The Exec.java example is what you need to send a simple command, stripped down for your reboot command it would be something like this

Code: Select all

public class Exec {

    public static void main(String... args)
            throws IOException {
        final SSHClient ssh = new SSHClient();

        ssh.connect("192.168.1.xxx, 22");
        try {
            ssh.authPassword(pi, raspberry);
            final Session session = ssh.startSession();
            try {
                final Command cmd = session.exec("echo raspberry | sudo -S reboot");
            } finally {
                session.close();
            }
        } finally {
            ssh.disconnect();
        }
    }
}

macintoshgeek
Posts: 24
Joined: Sun Feb 24, 2013 1:21 am

Re: Using SSHJ to send SSH commands to Raspberry Pi in Java

Tue Mar 19, 2013 6:38 pm

A few questions, what's the purpose of the "22" in this line?:

Code: Select all

ssh.connect("192.168.1.xxx, 22");


Also, is this working code or just an example? I'm away from my Pi at the moment, but if I were to add the code into an ActionListener for a button and change the "xxx" to my pi's actual IP, should everything work?

Also, should all commands follow the same format? Let's say I wanted to send a comand to my motion application to restart. Would I do?:

Code: Select all

final Command cmd = session.exec("echo raspberry | sudo -S motion restart");

Thanks!

User avatar
azeam
Posts: 194
Joined: Fri Oct 26, 2012 11:13 pm
Contact: Website

Re: Using SSHJ to send SSH commands to Raspberry Pi in Java

Tue Mar 19, 2013 8:34 pm

macintoshgeek wrote:A few questions, what's the purpose of the "22" in this line?:

Code: Select all

ssh.connect("192.168.1.xxx, 22");
It's the port number, change it if necessary.
macintoshgeek wrote:Also, is this working code or just an example? I'm away from my Pi at the moment, but if I were to add the code into an ActionListener for a button and change the "xxx" to my pi's actual IP, should everything work?
You'll have to import the necessary packages and probably you need to add try/catch blocks. If you use an IDE (like Eclipse) it'll give suggestions so you can add them easily, aside from that it should work.
macintoshgeek wrote:Also, should all commands follow the same format? Let's say I wanted to send a comand to my motion application to restart. Would I do?:

Code: Select all

final Command cmd = session.exec("echo raspberry | sudo -S motion restart");
Yes, but skip the sudo (unless you really need it) and just send

Code: Select all

motion restart
If you want to send several commands you will have to start a new session for each command or send them all as one command, for example

Code: Select all

final Command cmd = session.exec("motion restart && echo raspberry | sudo -S reboot");

macintoshgeek
Posts: 24
Joined: Sun Feb 24, 2013 1:21 am

Re: Using SSHJ to send SSH commands to Raspberry Pi in Java

Wed Mar 20, 2013 2:46 am

Eclipse is returning a whole jumble of errors when trying to execute one of the commands from a button click.

Code: Select all

Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
	at net.schmizz.sshj.DefaultConfig.<init>(DefaultConfig.java:92)
	at net.schmizz.sshj.SSHClient.<init>(SSHClient.java:133)
	at MainWindow$2.actionPerformed(MainWindow.java:55)
	at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2028)
	at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2351)
	at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
	at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
	at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
	at java.awt.Component.processMouseEvent(Component.java:6382)
	at javax.swing.JComponent.processMouseEvent(JComponent.java:3275)
	at java.awt.Component.processEvent(Component.java:6147)
	at java.awt.Container.processEvent(Container.java:2083)
	at java.awt.Component.dispatchEventImpl(Component.java:4744)
	at java.awt.Container.dispatchEventImpl(Container.java:2141)
	at java.awt.Component.dispatchEvent(Component.java:4572)
	at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4619)
	at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4280)
	at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4210)
	at java.awt.Container.dispatchEventImpl(Container.java:2127)
	at java.awt.Window.dispatchEventImpl(Window.java:2489)
	at java.awt.Component.dispatchEvent(Component.java:4572)
	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:710)
	at java.awt.EventQueue.access$400(EventQueue.java:82)
	at java.awt.EventQueue$2.run(EventQueue.java:669)
	at java.awt.EventQueue$2.run(EventQueue.java:667)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
	at java.awt.EventQueue$3.run(EventQueue.java:683)
	at java.awt.EventQueue$3.run(EventQueue.java:681)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
	at java.awt.EventQueue.dispatchEvent(EventQueue.java:680)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
	at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
	at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
	at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
	... 39 more
Any idea where to begin with this nonsense?

User avatar
azeam
Posts: 194
Joined: Fri Oct 26, 2012 11:13 pm
Contact: Website

Re: Using SSHJ to send SSH commands to Raspberry Pi in Java

Wed Mar 20, 2013 8:37 am

macintoshgeek wrote:Eclipse is returning a whole jumble of errors when trying to execute one of the commands from a button click.

Code: Select all

Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
	at net.schmizz.sshj.DefaultConfig.<init>(DefaultConfig.java:92)
	at net.schmizz.sshj.SSHClient.<init>(SSHClient.java:133)
	at MainWindow$2.actionPerformed(MainWindow.java:55)
	at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2028)
	at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2351)
	at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
	at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
	at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
	at java.awt.Component.processMouseEvent(Component.java:6382)
	at javax.swing.JComponent.processMouseEvent(JComponent.java:3275)
	at java.awt.Component.processEvent(Component.java:6147)
	at java.awt.Container.processEvent(Container.java:2083)
	at java.awt.Component.dispatchEventImpl(Component.java:4744)
	at java.awt.Container.dispatchEventImpl(Container.java:2141)
	at java.awt.Component.dispatchEvent(Component.java:4572)
	at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4619)
	at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4280)
	at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4210)
	at java.awt.Container.dispatchEventImpl(Container.java:2127)
	at java.awt.Window.dispatchEventImpl(Window.java:2489)
	at java.awt.Component.dispatchEvent(Component.java:4572)
	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:710)
	at java.awt.EventQueue.access$400(EventQueue.java:82)
	at java.awt.EventQueue$2.run(EventQueue.java:669)
	at java.awt.EventQueue$2.run(EventQueue.java:667)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
	at java.awt.EventQueue$3.run(EventQueue.java:683)
	at java.awt.EventQueue$3.run(EventQueue.java:681)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
	at java.awt.EventQueue.dispatchEvent(EventQueue.java:680)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
	at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
	at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
	at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
	... 39 more
Any idea where to begin with this nonsense?
Looks like you didn't add SLF4J (that SSHJ depends on) in the classpath, download it here: http://www.slf4j.org/download.html and add it to the classpath.

macintoshgeek
Posts: 24
Joined: Sun Feb 24, 2013 1:21 am

Re: Using SSHJ to send SSH commands to Raspberry Pi in Java

Wed Mar 20, 2013 4:05 pm

I added the library to the projects build path and the same area is being returned. I must be missing an extra step in here somewhere to make sure this library is in the project.

Here is my build path in Eclipse
http://imgur.com/5NjMmzs

User avatar
azeam
Posts: 194
Joined: Fri Oct 26, 2012 11:13 pm
Contact: Website

Re: Using SSHJ to send SSH commands to Raspberry Pi in Java

Wed Mar 20, 2013 4:52 pm

Add only slf4j-api-1.7.4.jar and slf4j-simple-1.7.4.jar. Here is some actual tested and working code, Exec.java:

Code: Select all

import java.io.IOException;

import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.connection.channel.direct.Session.Command;

public class Exec {

    public static void main(String... args)
            throws IOException {
        final SSHClient ssh = new SSHClient();
        ssh.addHostKeyVerifier(new NullHostKeyVerifier());
        
        ssh.connect("192.168.1.70", 22);
        
        try {
			ssh.authPassword("pi", "raspberry");
            final Session session = ssh.startSession();
            try {
                final Command cmd = session.exec("ls");
            } finally {
                session.close();
            }
        } finally {
            ssh.disconnect();
        }
    }
}
NullHostKeyVerifier.java:

Code: Select all


import java.security.PublicKey;

import net.schmizz.sshj.transport.verification.HostKeyVerifier;

public class NullHostKeyVerifier implements HostKeyVerifier {

	@Override
	public boolean verify(String arg0, int arg1, PublicKey arg2) {
		return true;
	}

}

User avatar
azeam
Posts: 194
Joined: Fri Oct 26, 2012 11:13 pm
Contact: Website

Re: Using SSHJ to send SSH commands to Raspberry Pi in Java

Wed Mar 20, 2013 4:55 pm

That is also a very old version of SSHJ (0.2.0), you can download the latest (at the moment 0.8.1) from https://github.com/shikhar/sshj/downloads

macintoshgeek
Posts: 24
Joined: Sun Feb 24, 2013 1:21 am

Re: Using SSHJ to send SSH commands to Raspberry Pi in Java

Wed Mar 20, 2013 7:10 pm

First of all, thank you so much for all your help. I truly do appreciate it. I got all the correct Jar files in there now and when I run it the only error I get is:

Code: Select all

[AWT-EventQueue-0] INFO net.schmizz.sshj.common.SecurityUtils - BouncyCastle not registered, using the default JCE provider
Is that something that can be ignored or fixed?

I'm at work right now so I can't see if this will work with the Pi until later tonight, but for now it looks like it keeps trying until it gets a timeout. So I think that's a start.

User avatar
azeam
Posts: 194
Joined: Fri Oct 26, 2012 11:13 pm
Contact: Website

Re: Using SSHJ to send SSH commands to Raspberry Pi in Java

Wed Mar 20, 2013 7:34 pm

macintoshgeek wrote:Is that something that can be ignored or fixed?

I'm at work right now so I can't see if this will work with the Pi until later tonight, but for now it looks like it keeps trying until it gets a timeout. So I think that's a start.
You can ignore it, for this usage I haven't noticed any advantages using BouncyCastle, but if you want you can add the jars from http://www.bouncycastle.org/latest_releases.html

macintoshgeek
Posts: 24
Joined: Sun Feb 24, 2013 1:21 am

Re: Using SSHJ to send SSH commands to Raspberry Pi in Java

Thu Mar 21, 2013 12:03 am

Hmmm. Still doesn't seem to want to work. For reference, here is the code I'm working with:

Code: Select all

import java.awt.EventQueue;


public class MainWindow extends JFrame {

	private JPanel contentPane;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MainWindow frame = new MainWindow();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public MainWindow() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
		
		JButton btnRebootPi = new JButton("Reboot Pi");
		btnRebootPi.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				final SSHClient ssh = new SSHClient();

		        try {
					ssh.connect("192.168.1.127,22");
				} catch (IOException e3) {
					// TODO Auto-generated catch block
					e3.printStackTrace();
				}
		        try {
		            ssh.authPassword("pi", "raspberry");
		            final Session session = ssh.startSession();
		            try {
		                final Command cmd = session.exec("echo raspberry | sudo -S reboot");
		            } catch (ConnectionException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (TransportException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} finally {
		                try {
							session.close();
						} catch (TransportException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						} catch (ConnectionException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
		            }
		        } catch (ConnectionException e2) {
					// TODO Auto-generated catch block
					e2.printStackTrace();
				} catch (TransportException e2) {
					// TODO Auto-generated catch block
					e2.printStackTrace();
				} catch (UserAuthException e2) {
					// TODO Auto-generated catch block
					e2.printStackTrace();
				} finally {
		            try {
						ssh.disconnect();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
		        }
		   
				
			}
		});
		contentPane.add(btnRebootPi);
		
		JButton btnRestartFeed = new JButton("Restart Feed");
		btnRestartFeed.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				final SSHClient ssh = new SSHClient();

		        try {
					ssh.connect("192.168.1.127,22");
				} catch (IOException e3) {
					// TODO Auto-generated catch block
					e3.printStackTrace();
				}
		        try {
		            ssh.authPassword("pi", "raspberry");
		            final Session session = ssh.startSession();
		            try {
		                final Command cmd = session.exec("motion restart");
		            } catch (ConnectionException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (TransportException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} finally {
		                try {
							session.close();
						} catch (TransportException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						} catch (ConnectionException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
		            }
		        } catch (ConnectionException e2) {
					// TODO Auto-generated catch block
					e2.printStackTrace();
				} catch (TransportException e2) {
					// TODO Auto-generated catch block
					e2.printStackTrace();
				} catch (UserAuthException e2) {
					// TODO Auto-generated catch block
					e2.printStackTrace();
				} finally {
		            try {
						ssh.disconnect();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
		        }
		   
				
			
			}
		});
		contentPane.add(btnRestartFeed);
	}

}
The try catch blocks could potentially be the problem as Eclipse seemed no not really know what it wanted to do with some of them.

Here is the error that is returned:

Code: Select all

[AWT-EventQueue-0] INFO net.schmizz.sshj.common.SecurityUtils - BouncyCastle not registered, using the default JCE provider
java.net.UnknownHostException: 192.168.1.127,22
	at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
	at java.net.InetAddress$1.lookupAllHostAddr(InetAddress.java:849)
	at java.net.InetAddress.getAddressFromNameService(InetAddress.java:1202)
	at java.net.InetAddress.getAllByName0(InetAddress.java:1153)
	at java.net.InetAddress.getAllByName(InetAddress.java:1083)
	at java.net.InetAddress.getAllByName(InetAddress.java:1019)
	at java.net.InetAddress.getByName(InetAddress.java:969)
	at net.schmizz.sshj.SocketClient.connect(SocketClient.java:77)
	at net.schmizz.sshj.SocketClient.connect(SocketClient.java:103)
	at MainWindow$2.actionPerformed(MainWindow.java:57)
	at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2028)
	at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2351)
	at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
	at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
	at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
	at java.awt.Component.processMouseEvent(Component.java:6382)
	at javax.swing.JComponent.processMouseEvent(JComponent.java:3275)
	at java.awt.Component.processEvent(Component.java:6147)
	at java.awt.Container.processEvent(Container.java:2083)
	at java.awt.Component.dispatchEventImpl(Component.java:4744)
	at java.awt.Container.dispatchEventImpl(Container.java:2141)
	at java.awt.Component.dispatchEvent(Component.java:4572)
	at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4619)
	at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4280)
	at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4210)
	at java.awt.Container.dispatchEventImpl(Container.java:2127)
	at java.awt.Window.dispatchEventImpl(Window.java:2489)
	at java.awt.Component.dispatchEvent(Component.java:4572)
	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:710)
	at java.awt.EventQueue.access$400(EventQueue.java:82)
	at java.awt.EventQueue$2.run(EventQueue.java:669)
	at java.awt.EventQueue$2.run(EventQueue.java:667)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
	at java.awt.EventQueue$3.run(EventQueue.java:683)
	at java.awt.EventQueue$3.run(EventQueue.java:681)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
	at java.awt.EventQueue.dispatchEvent(EventQueue.java:680)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
	at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
DUMBASS!
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
	at net.schmizz.sshj.transport.TransportImpl.write(TransportImpl.java:424)
	at net.schmizz.sshj.transport.TransportImpl.sendServiceRequest(TransportImpl.java:330)
	at net.schmizz.sshj.transport.TransportImpl.reqService(TransportImpl.java:312)
	at net.schmizz.sshj.AbstractService.request(AbstractService.java:77)
	at net.schmizz.sshj.userauth.UserAuthImpl.authenticate(UserAuthImpl.java:66)
	at net.schmizz.sshj.SSHClient.auth(SSHClient.java:205)
	at net.schmizz.sshj.SSHClient.auth(SSHClient.java:190)
	at net.schmizz.sshj.SSHClient.authPassword(SSHClient.java:266)
	at net.schmizz.sshj.SSHClient.authPassword(SSHClient.java:236)
	at net.schmizz.sshj.SSHClient.authPassword(SSHClient.java:220)
	at MainWindow$2.actionPerformed(MainWindow.java:64)
	at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2028)
	at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2351)
	at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
	at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
	at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
	at java.awt.Component.processMouseEvent(Component.java:6382)
	at javax.swing.JComponent.processMouseEvent(JComponent.java:3275)
	at java.awt.Component.processEvent(Component.java:6147)
	at java.awt.Container.processEvent(Container.java:2083)
	at java.awt.Component.dispatchEventImpl(Component.java:4744)
	at java.awt.Container.dispatchEventImpl(Container.java:2141)
	at java.awt.Component.dispatchEvent(Component.java:4572)
	at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4619)
	at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4280)
	at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4210)
	at java.awt.Container.dispatchEventImpl(Container.java:2127)
	at java.awt.Window.dispatchEventImpl(Window.java:2489)
	at java.awt.Component.dispatchEvent(Component.java:4572)
	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:710)
	at java.awt.EventQueue.access$400(EventQueue.java:82)
	at java.awt.EventQueue$2.run(EventQueue.java:669)
	at java.awt.EventQueue$2.run(EventQueue.java:667)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
	at java.awt.EventQueue$3.run(EventQueue.java:683)
	at java.awt.EventQueue$3.run(EventQueue.java:681)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
	at java.awt.EventQueue.dispatchEvent(EventQueue.java:680)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
	at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Before while I was on my work network, it just timed out. But now that I am at home and actually trying to connect to the Pi, it returns that error almost instantly. So I'm thinking that the Pi might be denning it?

User avatar
azeam
Posts: 194
Joined: Fri Oct 26, 2012 11:13 pm
Contact: Website

Re: Using SSHJ to send SSH commands to Raspberry Pi in Java

Thu Mar 21, 2013 7:36 am

I made a mistake in the first piece of code, the second that is tested is correct. Change

Code: Select all

ssh.connect("192.168.1.127,22");
to

Code: Select all

ssh.connect("192.168.1.127", 22);
You'll probably need the NullHostKeyVerifier class (or some other solution to that) that I posted as well, don't see that in your code.

macintoshgeek
Posts: 24
Joined: Sun Feb 24, 2013 1:21 am

Re: Using SSHJ to send SSH commands to Raspberry Pi in Java

Wed Mar 27, 2013 2:37 am

Sorry for the late response, but this worked like a charm! Thanks for all your help! It's much appreciated.

Yaceq
Posts: 11
Joined: Thu Oct 17, 2013 12:18 pm

Re: Using SSHJ to send SSH commands to Raspberry Pi in Java

Thu Oct 17, 2013 12:29 pm

Sorry for bumping such old topic but I've got a question about SSHJ.
I'm trying to do Java client to my RPi. It should connect to RPi and execute commands, run programs. Connecting to RPi works fine, but I can execute only one command. When I try to execute second I get 255 error code... Here's my SSH code:

Code: Select all

public class SSH {

	SSHClient ssh = null;

	public SSH() {
		this.ssh = new SSHClient();
		try {
			ssh.addHostKeyVerifier("...");
			ssh.connect("...");
			ssh.authPassword("..", "...");
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}

	}
	
	public void disconnect(){
		try {
			ssh.disconnect();
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}

	public void sendTestCommand() {	
		try {
			Session session = ssh.startSession();
			try {
	                        Command cmd = session.exec("ping google.com");
				System.out.println(IOUtils.readFully(cmd.getInputStream())
						.toString());
				cmd.join(1, TimeUnit.SECONDS);
				System.out.println("\n** exit status: " + cmd.getExitStatus());
			} finally {
				session.close();
			}
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}
}
In my main class i create new SSH instance once:

Code: Select all

SSH ssh = new SSH(); 
And I'd like to send multiple commands to the RPi. So I try executing:

Code: Select all

ssh.sendTestCommand(); 
And like I said before, first usage is ok, I get the response to the java console:
Pinging google.com [173.194.70.101] with 32 bytes of data:
Reply from 173.194.70.101: bytes=32 time=41ms TTL=45
Reply from 173.194.70.101: bytes=32 time=41ms TTL=45
Reply from 173.194.70.101: bytes=32 time=41ms TTL=45
Reply from 173.194.70.101: bytes=32 time=48ms TTL=45

Ping statistics for 173.194.70.101:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 41ms, Maximum = 48ms, Average = 42ms

** exit status: 0
But when I try to execute this again I just get

Code: Select all

** exit status: 255
What am I doing wrong?

User avatar
azeam
Posts: 194
Joined: Fri Oct 26, 2012 11:13 pm
Contact: Website

Re: Using SSHJ to send SSH commands to Raspberry Pi in Java

Thu Oct 17, 2013 1:23 pm

Are you disconnecting the SSH connection before you send the second command? To send several commands this way you'll either need to disconnect and reconnect or keep the connection open by just closing the session and start a new session without redeclaring SSHClient.

Yaceq
Posts: 11
Joined: Thu Oct 17, 2013 12:18 pm

Re: Using SSHJ to send SSH commands to Raspberry Pi in Java

Thu Oct 17, 2013 1:27 pm

I'd like to keep connection open and just open/close new sessions. And I'm doing it now I think. I just run only once:

Code: Select all

 ssh.addHostKeyVerifier("...");
         ssh.connect("...");
         ssh.authPassword("..", "...");
Later I execute sendTestCommand() only which opens new session and later closes it. But after 2nd usage I get 255 error code.

User avatar
azeam
Posts: 194
Joined: Fri Oct 26, 2012 11:13 pm
Contact: Website

Re: Using SSHJ to send SSH commands to Raspberry Pi in Java

Thu Oct 17, 2013 1:46 pm

That should work. You can verify that the SSH connection is open

Code: Select all

if (ssh.isAuthenticated() && ssh.isConnected()) {
... send command ...
}

Yaceq
Posts: 11
Joined: Thu Oct 17, 2013 12:18 pm

Re: Using SSHJ to send SSH commands to Raspberry Pi in Java

Thu Oct 17, 2013 4:31 pm

I changed my sendTestCommand() function to this:

Code: Select all

public void sendTestCommand() {
		if (ssh.isAuthenticated() && ssh.isConnected()) {
			System.out.println("HERE!");
			try {
				final Session session = ssh.startSession();
				try {
					final Command cmd = session.exec("ls");
					System.out.println(IOUtils.readFully(cmd.getInputStream())
							.toString());
					cmd.join(1, TimeUnit.SECONDS);
					System.out.println("\n** exit status: "
							+ cmd.getExitStatus());
				} finally {
					session.close();
				}
			} catch (IOException e) {
				System.out.println(e.getMessage());
			}
		}
	}
But it's the same... After first execution it prints HERE!, lists all files in home dir, and ends with exit status: 0 but after second it just prints HERE! and exit status: 255.
So it seems it is connected, creates new session successfully but can't execute command on RPi.

User avatar
azeam
Posts: 194
Joined: Fri Oct 26, 2012 11:13 pm
Contact: Website

Re: Using SSHJ to send SSH commands to Raspberry Pi in Java

Thu Oct 17, 2013 5:07 pm

I've now tested the exact code you posted for sendTestCommand() and it works fine for me, getting exit status 0 every time. Try to change the code to something like this

Code: Select all

public class SSH {

   public SSHClient ssh = new SSHClient();

   public SSH() {
         try {
         ssh.addHostKeyVerifier("...");
         ssh.connect("...");
         ssh.authPassword("..", "...");
      } catch (IOException e) {
         System.out.println(e.getMessage());
      }
...

Yaceq
Posts: 11
Joined: Thu Oct 17, 2013 12:18 pm

Re: Using SSHJ to send SSH commands to Raspberry Pi in Java

Thu Oct 17, 2013 7:27 pm

Ok, finally it works! ;)
Thanks!

Return to “Java”