如何使用Java从一台机器到另一台机器执行ssh

时间:2014-03-17 11:57:35

标签: java ssh jsch

使用putty我可以从一台机器到另一台机器进行ssh,然后从另一台机器进行。像链式进程一样。我想在我的程序中复制相同的内容。到目前为止,我能够ssh到第一台机器。从那台机器我如何ssh到后续的机器。我也想执行一些命令,如'pwd'或'ls'。

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.io.*;

public class SSH {

   public static void main(String args[]) {

     String user = "******";
     String password = "******";
     String host = "******";
     int port=22;

     String remoteFile="something.txt";

     try {
        JSch jsch = new JSch();
        Session session = jsch.getSession(user, host, port);
        session.setPassword(password);
        java.util.Properties config = new java.util.Properties(); 
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
        sftpChannel.connect();
        System.out.println("connected to first server....");
        InputStream out= null;
        out= sftpChannel.get(remoteFile);
        BufferedReader br = new BufferedReader(new InputStreamReader(out));
        String line;
        while ((line = br.readLine()) != null)
           System.out.println(line);
        br.close();

        /********* Here i want to ssh to another machine from the already connected one ******/

    String command = "pwd" ; //executing correctly with o/p
    Channel channel = session.openChannel("exec");
    ((ChannelExec) channel).setCommand(command);
    channel.setInputStream(null);
    InputStream in = channel.getInputStream();
    channel.connect();
    byte[] tmp=new byte[1024];
    while(true){
      while(in.available()>0){
        int i=in.read(tmp, 0, 1024);
        if(i<0)break;
        System.out.print(new String(tmp, 0, i));
      }
      if(channel.isClosed()){
        System.out.println("exit-status: "+channel.getExitStatus());
        break;
      }

    }
    channel.disconnect();

    Channel channel1 = session.openChannel("exec");
    ((ChannelExec) channel1).setCommand("ssh username@hostname" + "&&" + "password");//not    executing
    channel1.setInputStream(null);
    in = channel1.getInputStream();
    channel1.connect();
    channel1.disconnect();



    Channel channel2 = session.openChannel("exec");

    ((ChannelExec) channel2).setCommand("ls"); //to verify if ssh to 2nd machine has happened.not working
     channel2.setInputStream(null);
     in = channel2.getInputStream();
    channel2.connect();
   // byte[] tmp=new byte[1024];
    while(true){
      while(in.available()>0){
        int i=in.read(tmp, 0, 1024);
        if(i<0)break;
        System.out.print(new String(tmp, 0, i));
      }
      if(channel.isClosed()){
        System.out.println("exit-status: "+channel2.getExitStatus());
        break;
      }

    }
    channel2.disconnect();
    session.disconnect();
     } catch(Exception e) { System.err.print(e); }
   }

}

2 个答案:

答案 0 :(得分:0)

session.connect();之后使用代码执行linux服务器中的命令

                            session.connect();
            command = "pwd;" + "ssh username@hostname" + "&&" + "password" ; // u can give your own commands

            Channel channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(command);
            channel.setInputStream(null);
            InputStream in = channel.getInputStream();
            channel.connect();
            byte[] tmp = new byte[1024];
            while (true) {
                while (in.available() > 0) {
                    int i = in.read(tmp, 0, 1024);
                    if (i > 0) {

                        output = new String(tmp, 0, i); // name a variable of your own

                    } else {

                        break;

                    }

                    System.out.println(output);

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

确保断开频道。这样你就可以创建一个新的频道并执行下一个命令。

答案 1 :(得分:0)

我试过这个,它对我有用。但我不确定这是否是正确的程序。

`public class SSH {

public static void main(String[] args) {
    String server1="server1";
    String server2="server2";
    String user1="user1";
    String user2="user2";
    String password1="pswd1";
    String password2="pswd2";

    String command1="ls -ltr";

    try{

        java.util.Properties config = new java.util.Properties(); 
        config.put("StrictHostKeyChecking", "no");
        JSch jsch = new JSch();
        Session session1=jsch.getSession(user1, server1, 22);
        session1.setPassword(password1);
        session1.setConfig(config);
        session1.connect();
        System.out.println("Connected session1");



        Session session2=jsch.getSession(user2,server2);
        session2.setPassword(password2);
        session2.setConfig(config);
        session2.connect();
        System.out.println("Connected session2");


        Channel channel=session1.openChannel("exec");   
        ((ChannelExec)channel).setCommand(command1);
        channel.setInputStream(null);
        InputStream in=channel.getInputStream();
        ((ChannelExec)channel).setErrStream(System.err);   
        channel.connect();

        Channel channel1=session2.openChannel("exec");  
        ((ChannelExec)channel1).setCommand(command1);
        channel1.setInputStream(null);
        InputStream in1=channel1.getInputStream();
        ((ChannelExec)channel1).setErrStream(System.err);   
        channel1.connect();

        byte[] tmp=new byte[1024];
        while(true){
            while(in.available()>0){
                int i=in.read(tmp, 0, 1024);
                if(i<0)break;
                System.out.print(new String(tmp, 0, i));
            }
            if(channel.isClosed()){
                System.out.println("exit-status: "+channel.getExitStatus());
                break;
            }
            try{Thread.sleep(1000);}catch(Exception ee){}
        }
        while(true){
            while(in1.available()>0){
                int i=in1.read(tmp, 0, 1024);
                if(i<0)break;
                System.out.print(new String(tmp, 0, i));
            }
            if(channel1.isClosed()){
                System.out.println("exit-status: "+channel1.getExitStatus());
                break;
            }

            try{Thread.sleep(1000);}catch(Exception ee){}
        }
        channel.disconnect();
        session2.disconnect();
        session1.disconnect();
        System.out.println("DONE");
    }catch(Exception e){
        e.printStackTrace();
    }

}

}`