Sending commands to remote server through ssh by Java with JSch

扶醉桌前 提交于 2019-11-27 13:11:13

问题


I'm trying to set up a class so that I can ssh into a remote server (I have the IP, username, and password) and then send a command like "echo "test"" and then receive back the output (e.g., "test"). I'm using JSch to do this but I don't understand how to do it.

import com.jcraft.jsch.*;

public class ConnectSSH {

public int execute (String command) {

    JSch jsch   = new JSch();
    String ip   = "00.00.00.00;
    String user = "root";
    String pass = "password";
    int port    = 22;

    try {                
        Session session = jsch.getSession(user, ip, port);   
        session.setPassword(pass);
        session.connect();

             ...

I'm not sure what to do, I'm stuck after connecting.

Any advice is greatly appreciated.


回答1:


Try this:

JSch jsch=new JSch();
Session session=jsch.getSession(remoteHostUserName, RemoteHostName, 22);
session.setPassword(remoteHostpassword);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();

ChannelExec channel=(ChannelExec) session.openChannel("exec");
BufferedReader in=new BufferedReader(new InputStreamReader(channel.getInputStream()));
channel.setCommand("pwd;");
channel.connect();

String msg=null;
while((msg=in.readLine())!=null){
  System.out.println(msg);
}

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



回答2:


shamnu's answer above was right. I couldn't add a comment to it, so here are a few examples to enhance his answer. One is how to do a remote execution of 'ls -l', another of 'mkdir', and another of a local to remote copy. All done with version 0.1.51 of jsch (http://www.jcraft.com/jsch/).

  public void remoteLs() throws JSchException, IOException {
    JSch js = new JSch();
    Session s = js.getSession("myusername", "myremotemachine.mycompany.com", 22);
    s.setPassword("mypassword");
    Properties config = new Properties();
    config.put("StrictHostKeyChecking", "no");
    s.setConfig(config);
    s.connect();

    Channel c = s.openChannel("exec");
    ChannelExec ce = (ChannelExec) c;

    ce.setCommand("ls -l");
    ce.setErrStream(System.err);

    ce.connect();

    BufferedReader reader = new BufferedReader(new InputStreamReader(ce.getInputStream()));
    String line;
    while ((line = reader.readLine()) != null) {
      System.out.println(line);
    }

    ce.disconnect();
    s.disconnect();

    System.out.println("Exit code: " + ce.getExitStatus());

  }



  public void remoteMkdir() throws JSchException, IOException {
    JSch js = new JSch();
    Session s = js.getSession("myusername", "myremotemachine.mycompany.com", 22);
    s.setPassword("mypassword");
    Properties config = new Properties();
    config.put("StrictHostKeyChecking", "no");
    s.setConfig(config);
    s.connect();

    Channel c = s.openChannel("exec");
    ChannelExec ce = (ChannelExec) c;

    ce.setCommand("mkdir remotetestdir");
    ce.setErrStream(System.err);

    ce.connect();

    BufferedReader reader = new BufferedReader(new InputStreamReader(ce.getInputStream()));
    String line;
    while ((line = reader.readLine()) != null) {
      System.out.println(line);
    }

    ce.disconnect();
    s.disconnect();

    System.out.println("Exit code: " + ce.getExitStatus());

  }

  public void remoteCopy() throws JSchException, IOException, SftpException {
    JSch js = new JSch();
    Session s = js.getSession("myusername", "myremotemachine.mycompany.com", 22);
    s.setPassword("mypassword");
    Properties config = new Properties();
    config.put("StrictHostKeyChecking", "no");
    s.setConfig(config);
    s.connect();

    Channel c = s.openChannel("sftp");
    ChannelSftp ce = (ChannelSftp) c;

    ce.connect();

    ce.put("/home/myuser/test.txt","test.txt");

    ce.disconnect();
    s.disconnect();    
  }



回答3:


I suggest looking at the hidden example on the JCraft website: http://www.jcraft.com/jsch/examples/UserAuthKI.java

Their example prompts for username, hostname, password, so it is ready to test out of the box. I ran it on my network and was able to connect to an AIX server without changing any code.

Note, their example has a problem (this may be why it is hidden).. it does not ever close the channel. If you send 'exit' the server will disconnect you, but the channel object stays open and your Java program never exits. I have provided a fix for that here: Never ending of reading server response using jSch




回答4:


 1. List item

import java.io.InputStream;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class SSHCommandExecutor {

    /**
     * @param args
     */
    public static void main(String[] args) {
        String host="10.75.81.21";
        String user="root";
        String password="Avaya_123";
        String command1="ls -l";
        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");
            ((ChannelExec)channel).setCommand(command1);
            channel.setInputStream(null);
            ((ChannelExec)channel).setErrStream(System.err);

            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));
              }`enter code here`
              if(channel.isClosed()){
                System.out.println("exit-status: "+channel.getExitStatus());
                break;
              }
              try{Thread.sleep(1000);}catch(Exception ee){}
            }
            channel.disconnect();
            session.disconnect();
            System.out.println("DONE");
        }catch(Exception e){
            e.printStackTrace();
        }

    }


 1. List item

}


来源:https://stackoverflow.com/questions/16468475/sending-commands-to-remote-server-through-ssh-by-java-with-jsch

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!