javaputtyplink

Java PuTTY open saved session


New to Plink, I am trying to load a saved session from putty using Plink, my session is called "saved session1" and when I load and run the session and connect remotely to the server in PuTTY I am first asked for "login as:" and then for "Password:". Given my "saved session1" with a username "username1" and password "password1". I am basing my code on a previous stackoverflow post at

Java and putty - send commands [duplicate]

I have the code but am unsure how to format the commands, assuming PuTTY and Plink are in the same directory as my java code, and given all the information about the server, my session and login details, how do I use the r.exe(); commands to simply login to the server and print the home directory contents?

import java.io.*;
import java.net.*;

public class javaputty{
    public static void main(String[] args){

        InputStream std; 
        OutputStream out; 
        InputStream err; 

        try {
            String command = "plink -load saved session1";
            String username = "username1";
            String password = "password1";

            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 (10000);

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

Solution

  • If your stored session name contains a space, you have to enclose the name to double-quotes (you better do it always):

    String command = "plink -load \"saved session1\"";
    

    Though you better use a native Java SSH library (e.g. JSch), rather than trying to automate PuTTY/Plink.

    See Sending commands to remote server through ssh by Java with JSch.