12

我正在尝试设置一个类,以便我可以通过 ssh 连接到远程服务器(我有 IP、用户名和密码),然后发送类似的命令echo "test",然后接收回输出(例如,“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;

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

    ...

连接后卡住了

4

4 回答 4

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();
于 2013-06-14T06:39:50.223 回答
9

shamnu 上面的回答是正确的。我无法对其添加评论,因此这里有一些示例可以增强他的答案。一个是如何远程执行“ls -l”,另一个是“mkdir”,另一个是本地到远程复制。全部使用 0.1.51 版的 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();    
  }
于 2014-10-10T19:08:24.813 回答
2

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

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

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

于 2013-05-10T14:06:14.470 回答
-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

}
于 2016-02-24T11:13:00.633 回答