使用JSch通过Java通过ssh将命令发送到远程服务器

时间:2013-05-09 18:21:39

标签: ssh jsch

我正在尝试设置一个类,以便我可以ssh到远程服务器(我有IP,用户名和密码),然后发送一个命令,如“echo”test“”然后收回输出(例如,“测试”)。我正在使用JSch来做这件事,但我不明白该怎么做。

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();

             ...

我不知道该怎么办,连接后我被卡住了。

非常感谢任何建议。

4 个答案:

答案 0 :(得分:25)

试试这个:

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();

答案 1 :(得分:9)

shamnu上面的回答是正确的。我无法添加评论,所以这里有几个例子来提高他的答案。一个是如何远程执行' ls -l',另一个' mkdir'以及另一个本地到远程拷贝。全部使用jsch(http://www.jcraft.com/jsch/)版本0.1.51完成。

  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();    
  }

答案 2 :(得分:2)

我建议查看JCraft网站上的隐藏示例:http://www.jcraft.com/jsch/examples/UserAuthKI.java

他们的示例提示输入用户名,主机名和密码,因此可以开箱即用。我在我的网络上运行它,并且能够连接到AIX服务器而无需更改任何代码。

注意,他们的例子有一个问题(这可能就是隐藏它的原因)..它不会关闭频道。如果发送'exit',服务器将断开连接,但通道对象保持打开状态,Java程序永远不会退出。我在这里提供了一个修复程序:Never ending of reading server response using jSch

答案 3 :(得分:-1)

 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

}