ssh2远程连接linux服务器

来源:互联网 发布:扭矩补偿算法 编辑:程序博客网 时间:2024/06/05 09:29

做东西的时候遇到了需要远程连接我们的服务器,首先想到的当然是ssh2协议,在查资料的时候将常见的几种jar包都试了个遍,首先说知名的ganymed-ssh2.jar,接下来我们在述说jsch-0.1.53.jar,最后,在谈一下我们使用的trilead-ssh2-build13.jar.

ganymed-ssh2.jar :

        这个包是纯java代码写得,使用的实例代码如下,

package com.hemin.test;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.util.Scanner;import ch.ethz.ssh2.Connection;import ch.ethz.ssh2.Session;import ch.ethz.ssh2.StreamGobbler;public class SshTest{    public static void main(String[] args)    {       String hostname = "you ip adress";       String username = "root";       String password = "root";              boolean  flag = true;              Scanner in = new Scanner(System.in);              try{           Connection conn = new Connection(hostname);           conn.connect();           boolean isAuthenticated = conn.authenticateWithPassword(username, password);           if (isAuthenticated == false)              throw new IOException("Authentication failed.");           Session sess = conn.openSession();       for(int i = 0;i<100;i++){       sess.execCommand(in.nextLine());       System.out.println("Result::");               InputStream stdout = new StreamGobbler(sess.getStdout());               BufferedReader br = new BufferedReader(new InputStreamReader(stdout));               while (true)               {                  String line = br.readLine();                  if (line == null)                      break;                  System.out.println(line);                  sess.close();                  conn.close();               }       }                                 //System.out.println("ExitCode: " + sess.getExitStatus());                 }       catch (IOException e)       {           e.printStackTrace(System.err);           System.exit(2);       }    }}

在使用的过程中,我们需要通过他来提交spark指令,出现的问题就是指令提交上去之后,spark的任务一直运行,停不下来,因此,只能选择放弃。不得不说,这个包确实很好用,可以使用多线程而实现防putty这个知名软件。有兴趣的可以试试这个。

----------------------------------------------------------------------------
jsch-0.1.53.jar
这个包也是纯jiava的ssh2包,示例代码和上述大同小异,直接上程序
package com.hemin.test;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.util.Properties;import com.jcraft.jsch.ChannelExec;import com.jcraft.jsch.JSch;import com.jcraft.jsch.JSchException;import com.jcraft.jsch.Session;public class sshhelp {    public static String exec(String host,String user,String psw,int port,String command){    String result="";    Session session =null;    ChannelExec openChannel =null;    try {      JSch jsch=new JSch();      session = jsch.getSession(user, host, port);      Properties config = new Properties();      config.put("StrictHostKeyChecking", "no");      session.setConfig(config);      session.setPassword(psw);      session.connect();      openChannel = (ChannelExec) session.openChannel("exec");      openChannel.setCommand(command);      int exitStatus = openChannel.getExitStatus();      System.out.println(exitStatus);      openChannel.connect();              InputStream in = openChannel.getInputStream();              BufferedReader reader = new BufferedReader(new InputStreamReader(in));              String buf = null;            while ((buf = reader.readLine()) != null) {            result+= new String(buf.getBytes("gbk"),"UTF-8")+"    <br>\r\n";              }      } catch (JSchException | IOException e) {      result+=e.getMessage();    }finally{      if(openChannel!=null&&!openChannel.isClosed()){        openChannel.disconnect();      }      if(session!=null&&session.isConnected()){        session.disconnect();      }    }    return result;  }        public static void main(String args[]){    String exec = exec("you ip add", "root", "root", 22, "sleep 20;ls;");    System.out.println(exec);  }}

这个包的问题就是线程不能中断,程序一直在运行,那样的话,我们的任务就无法提交上去,因此也选择了放弃这个包,
----------------------------------------------------------------------
最后,我们选择了trilead-ssh2-build13.jar.
这个包虽然不是最好的,但是是最合适的,功能简单,一条命令,不能读取linux的环境变量,但是,完全符合我们的需要
实例代码如下:

import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import com.trilead.ssh2.Connection;import com.trilead.ssh2.Session;import com.trilead.ssh2.StreamGobbler;/** * This example shows how to consume stdout/stderr output * using two StreamGobblers. This is simpler to program * than the state machine approach (see SingleThreadStdoutStderr.java), * but you cannot control the amount of memory that is * consumed by your application (i.e., in case the other * side sends you lots of data). *  * @author Christian Plattner, plattner@trilead.com * @version $Id: StdoutAndStderr.java,v 1.2 2007/10/15 12:49:57 cplattne Exp $ */public class StdoutAndStderr{public static void main(String[] args){String hostname = "you ip addr";String username = "root";String password = "root";String a=("cd; );try{/* Create a connection instance */Connection conn = new Connection(hostname);/* Now connect */conn.connect();/* Authenticate */boolean isAuthenticated = conn.authenticateWithPassword(username, password);if (isAuthenticated == false)throw new IOException("Authentication failed.");/* Create a session */Session sess = conn.openSession();//sess.execCommand("echo \"Text on STDOUT\"; echo \"Text on STDERR\" >&2");sess.execCommand(a);InputStream stdout = new StreamGobbler(sess.getStdout());InputStream stderr = new StreamGobbler(sess.getStderr());BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stdout));BufferedReader stderrReader = new BufferedReader(new InputStreamReader(stderr));//System.out.println("Here is the output from stdout:");while (true){String line = stdoutReader.readLine();if (line == null)break;System.out.println(line);}//System.out.println("Here is the output from stderr:");while (true){String line = stderrReader.readLine();if (line == null)break;System.out.println(line);}/* Close this session */sess.close();/* Close the connection */conn.close();}catch (IOException e){e.printStackTrace(System.err);System.exit(2);}}}



0 0
原创粉丝点击