需依赖jcraft和commons.io的jar包。可自行下载或者通过maven下载。
maven pom.xml配置:
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.53</version>
</dependency>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
package cn.linux.ssh.SSHLinux; import java.io.IOException; import java.io.InputStream; import org.apache.commons.io.IOUtils; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; public class Methods { public static String exeCommand(String host, int port, String user, String password, String command) throws JSchException, IOException { JSch jsch = new JSch(); Session session = jsch.getSession(user, host, port); session.setConfig("StrictHostKeyChecking", "no"); // java.util.Properties config = new java.util.Properties(); // config.put("StrictHostKeyChecking", "no"); session.setPassword(password); session.connect(); ChannelExec channelExec = (ChannelExec) session.openChannel("exec"); InputStream in = channelExec.getInputStream(); channelExec.setCommand(command); channelExec.setErrStream(System.err); channelExec.connect(); String out = IOUtils.toString(in, "UTF-8"); channelExec.disconnect(); session.disconnect(); return out; } }
调用:
public static void main( String[] args ) throws JSchException, IOException { // TODO Auto-generated method stub String host = "192.168.1.230"; int port = 22; String user = "qwe"; String password = "12345678"; String command = "adb devices"; String res = Methods.exeCommand(host,port,user,password,command); System.out.println(res.trim()); }
还没有评论,来说两句吧...