Jsch – 通过SSH连接发送命令

我想发送一个简单的命令与我的Windows电脑上的Java应用程序,以激活我的树莓派的Python脚本,应该控制我的树莓派的GPIO端口。

我没有真正进入Jsch,我的SSH连接已经工作,但不发送命令。

这是我的实际代码:

package sshtest; import java.io.ByteArrayInputStream; import java.io.InputStream; import com.jcraft.jsch.*; import java.io.InputStream; public class SSHTest { public static void main(String[] args) { String host="DELETED"; String user="pi"; String password="DELETED"; String command =("cd Desktop"); String command2 =("sudo python IO2.py all high"); try{ java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); JSch jsch = new JSch(); Session session=jsch.getSession(user, host, 22); session.setPassword(password); session.setConfig(config); session.connect(); System.out.println("Connected"); Channel channel = session.openChannel("exec"); InputStream is = new ByteArrayInputStream(command.getBytes()); channel.setInputStream(is); InputStream iss = new ByteArrayInputStream(command2.getBytes()); channel.setInputStream(iss); session.disconnect(); }catch(Exception e){ e.printStackTrace(); } } } 

你应该使用ChannelExec.setCommand(java.lang.String)来启动它,等待Channel.isClosed()返回false 。 顺便说一句,JSch有这样一个例子: http : //www.jcraft.com/jsch/examples/Exec.java.html 。