有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Jsch shell/Expecdt4j简单示例?

我正在寻找一个简单的例子,如何在Jsch中使用Expect4j(使用Shell而不是exec) 我指的是如何向服务器发送命令(~8),以及如何打印响应

到目前为止,我有:

  JSch jsch=new JSch();
  String host="www.superserver.uk.com";
  String user="tom1234";
  String passwd="12345a";
  Session session=jsch.getSession(user, host, 22);
  session.setPassword(passwd);
  session.setConfig("StrictHostKeyChecking", "no"); // if yes nothing works, but we're secure!
  session.connect();  
  Channel channel=session.openChannel("shell");//only shell 
  channel.setInputStream(System.in);// enter lrp_list
  channel.setOutputStream(System.out);

我想发送这样的命令:command=(“lrp_list;newgrp xxx;date”);发送(命令); 还有一些例子,我发现只有时间限制的工作;我需要类似于上面代码的东西,即使执行需要15分钟,也能执行一个命令


共 (1) 个答案

  1. # 1 楼答案

    您拥有的代码将Shell的Inputstream/outputStream连接到本地java进程的相同流。要在shell中执行命令,必须在shell的inputstream中提交这些命令(即,不要将其连接到本地输入),如下所示:

    JSch jsch=new JSch();
    String host="www.superserver.uk.com";
    String user="tom1234";
    String passwd="12345a";
    Session session=jsch.getSession(user, host, 22);
    session.setPassword(passwd);
    session.setConfig("StrictHostKeyChecking", "no"); // if yes nothing works, but we're secure!
    session.connect();  
    Channel channel=session.openChannel("shell");//only shell 
    channel.setOutputStream(System.out);
    PrintStream shellStream = new PrintStream(channel.getOutputStream());  // printStream for convenience
    channel.connect();
    shellStream.println("lrp_list");
    shellStream.println("newgrp xxx");
    shellStream.println("date");
    

    然后等到“日期”结果出来,然后关闭频道。(您可能需要先发送“退出”或“注销”。)

    我不知道expect4j,但我假设您可以为它提供一对InputStream和OutputStream,然后在这里使用getInputStream而不是setOutputStream


    好的,找到source for Expect4j.java后,我会这样做:

    JSch jsch=new JSch();
    String host="www.superserver.uk.com";
    String user="tom1234";
    String passwd="12345a";
    Session session=jsch.getSession(user, host, 22);
    session.setPassword(passwd);
    session.setConfig("StrictHostKeyChecking", "no"); // if yes nothing works, but we're secure!
    session.connect();  
    Channel channel=session.openChannel("shell");//only shell 
    Expect4j expect = new Expect4j(channel.getInputStream(), channel.getOutputStream());
    // use expect methods