繁体   English   中英

使用Java中的Jsch库自动化ssh会话

[英]Automation of ssh session using jsch library in java

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

        }

}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM