【问题标题】:Automation of ssh session using jsch library in java在java中使用jsch库自动化ssh会话
【发布时间】:2014-09-26 12:34:02
【问题描述】:

我正在使用 java 自动化 ssh 会话,使用此代码我能够登录并在屏幕上获得输出,但是在此之后,在我们进入应用程序以在 ssh 会话中运行后,它不需要用户名和密码,因为它需要像 TAB 和 ENTER 和功能键等键盘交互,所以有没有办法发送键盘事件来代替命令,以便自动化成功?

public class jschputty {

public static void main(String args[])
{   
 String host="x.x.x.x";
 String user="username";
 String password="password";
 String command1="ls -ltr\t";

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

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

  channel.setCommand(command);
    channel.connect();
           String msg=null;
           while((msg=in.readLine())!=null){
            System.out.println(msg);
           }                  
                channel.disconnect();
                session.disconnect();
                System.out.println("DONE");
            }catch(Exception e){
                e.printStackTrace();
            }

        }

}

【问题讨论】:

  • 您正在做的是与 SFTP 服务器建立 SFTP 连接。就像您可以使用名为“putty”的客户端应用程序一样。您不会使用此代码以任何方式与 putty 交互。
  • @Gimby - 从技术上讲,是 ssh,而不是 sftp,但你说得对,腻子根本不涉及。

标签: java automation


【解决方案1】:

如果你想将输出发送到远程会话,我建议你写入channel.getOutputStream()返回的OutputStream。

【讨论】:

  • 谢谢,我试图在我的代码中使用它,你能否帮我提供一个示例,关于如何使用它来将其写入输出流,参考我的代码?
  • InputStream in=channel.getInputStream();输出流输出 = channel.getOutputStream();通道.连接(); out.write("ls -lrt\n".getBytes()); out.flush();
  • 这是我尝试过的,但似乎我在这里的 sumthing 错了
  • @XtremeCore - 为什么?您没有提供有关您的实际问题的详细信息。你应该用具体的细节更新你的问题。
猜你喜欢
  • 2012-05-12
  • 1970-01-01
  • 2015-01-24
  • 1970-01-01
  • 1970-01-01
  • 2022-12-22
  • 1970-01-01
  • 2014-08-13
  • 2017-01-07
相关资源
最近更新 更多