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.
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:
- Place putty.exe and plink.exe in a place like C:\Windows\
- Put putty.exe and plink.exe in a folder and add that folder to the system environment (recommended method).
- 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).
If you just need SSH check this: Jcraft's jsch: http://www.jcraft.com/jsch/
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