Java and putty - send commands [duplicate]

a 夏天 提交于 2019-11-30 18:46:38

问题


Possible Duplicate:
How to send commands to putty

How can I send commands to the putty using java? I have to use Putty. I mean sending commands to the putty window, e.g. Java should sending "ls -l" to the putty window.


回答1:


To use Putty from Java™ you will need to use Putty's (Command Line) Link PLink. You can get this from Putty's Download page: Putty Download Page

You will need to run putty.exe to configure a session (in the example I made a profile name “profile”). You can then load the session and send/receive information. Don't forget to make sure that you check both the standard and error input streams.

To make sure you can run it from Java™ you may need to do one of three things:

  1. Place putty.exe and plink.exe in a place like C:\Windows\
  2. Put putty.exe and plink.exe in a folder and add that folder to the system environment (recommended method).
  3. Put putty.exe and plink.exe in the same folder as your Java™ application and just make sure that you reference it correctly.

Here is sample code.

try {
    String command = "plink -load profile";

    Runtime r = Runtime.getRuntime ();
    Process p = r.exec (command);
    std = p.getInputStream ();
    out = p.getOutputStream ();
    err = p.getErrorStream ();

    out.write ("ls -l\n".getBytes ());
    out.flush ();

    Thread.sleep (1000);

    int value = 0;
    if (std.available () > 0) {
        System.out.println ("STD:");
        value = std.read ();
        System.out.print ((char) value);

        while (std.available () > 0) {
            value = std.read ();
            System.out.print ((char) value);
        }
    }

    if (err.available () > 0) {
        System.out.println ("ERR:");
        value = err.read ();
        System.out.print ((char) value);

        while (err.available () > 0) {
            value = err.read ();
            System.out.print ((char) value);
        }
    }

    p.destroy ();
}
catch (Exception e) {
    e.printStackTrace ();
}

Hope this helps those who are also interested in a fast way to set up quick Putty in Java. It is also a great way to get serial port communication without need for native drivers and such (though functionality is limited).




回答2:


If you just need SSH check this: Jcraft's jsch: http://www.jcraft.com/jsch/




回答3:


You don't have to use putty. It is much better to use a java library to connect to SSH. See SSH library for Java for a discussion on java libraries for SSH.



来源:https://stackoverflow.com/questions/5817771/java-and-putty-send-commands

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!