Sample (Example) Java code to connect remote box over SSH with key authentication and execute SSH commands and run scripts.. Prgramatically it will connect the remote host and sends commands to execute on server. It behaves like Putty or any other SSH client to connect and execute commands on remote linux box. It shows basic java code to connect with key and execute commoands on server. It can be copied and run to test it. It uses Ganymed SSH-2 library(jar) for Java .
Java Class File Content:
package comz;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
public class ConnectRemoteAndExecute {
public static void main(String args[]) throws IOException, InterruptedException {
new ConnectRemoteAndExecute().connectAndExecute();
}
InputStream inputStream = null;
OutputStream outputStream = null;
InputStream errorInputStream = null;
public void connectAndExecute() throws IOException, InterruptedException {
System.out.println("Trying to connect remote lunux box from java program"
+ " using ganymed-ssh-2 library. Authentication with key ");
String box = "11.232.135.21"; // or box/machine name.
String user = "centos";
File keyFile = new File("C:\\AwsKey\\awskeybombay.pem");
Connection connectionObject = new Connection(box);
connectionObject.connect();
String[] authenticationModes = connectionObject.getRemainingAuthMethods("centos");
System.out.println("The supported authenticationModes are:");
for (String method : authenticationModes) {
System.out.println(method + ": \n");
}
try {
// Authenticate with password.
//authenticateWithPassword(user, "password");
// Authenticate with Key.
System.out.println("Trying to authenticate using Key");
boolean isSuccess = connectionObject.authenticateWithPublicKey("centos", keyFile, "");
System.out.println("isSuccess=" + isSuccess);
if (!isSuccess) {
System.out.println("Authentication Failed using using key");
throw new IOException("Auth failed Exception. ErrorCode:ER00001");
}
System.out.println("Authentication Done successfully using using key");
Session sesiionObj = connectionObject.openSession();
sesiionObj.requestDumbPTY();
sesiionObj.startShell();
System.out.println("Your " + " session Started: " + " \n");
inputStream = sesiionObj.getStdout();
outputStream = sesiionObj.getStdin();
errorInputStream = sesiionObj.getStderr();
ReadInputStream inputStreamReader = new ReadInputStream(this);
inputStreamReader.start();
ReadErrorStream errStreamReader = new ReadErrorStream(this);
errStreamReader.start();
Thread.sleep(100);
writeCmd("pwd");
Thread.sleep(1000);
System.out.println("Sending command sudo su");
writeCmd("sudo su");
Thread.sleep(1000);
System.out.println("Sending command ls -lrt");
writeCmd("ls -lrt" + "");
Thread.sleep(1000);
System.out.println("Sending host name");
writeCmd("hostname -A" + "");
Thread.sleep(1000);
System.out.println("Sending last command pwd");
writeCmd("pwd");
System.out.println("=======End of Execution========");
} finally {
connectionObject.close();
}
}
public synchronized void writeCmd(final String cmd) throws IOException {
outputStream.write(cmd.getBytes());
outputStream.flush();
outputStream.write('\n');
outputStream.flush();
}
}
class ReadInputStream extends Thread {
ConnectRemoteAndExecute connAndExeObj = null;
public ReadInputStream(ConnectRemoteAndExecute conAndExObj) {
connAndExeObj = conAndExObj;
}
List listOfOut = new ArrayList();
public void run() {
int match = 0;
String outStr = "";
int count = 0;
while (true) {
int ic = 0;
try {
ic = connAndExeObj.inputStream.read();
} catch (IOException e1) {
e1.printStackTrace();
}
final char ch = (char) ic;
if (ic == -1) {
System.out.print("breakingg for as -1");
break;
}
System.out.print(ch);
outStr = outStr + ch;
count++;
if (outStr.contains("(yes/no)")) {
try {
connAndExeObj.writeCmd("yes");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
listOfOut.add(outStr);
outStr = "";
count = 0;
}
}
System.out.println("outStr_outputLast=" + outStr);
}
}
class ReadErrorStream extends Thread {
ConnectRemoteAndExecute connAndExecute = null;
public ReadErrorStream(ConnectRemoteAndExecute conAndExe) {
connAndExecute = conAndExe;
}
public void run() {
while (true) {
int ic = 0;
try {
ic = connAndExecute.errorInputStream.read();
} catch (IOException e1) {
e1.printStackTrace();
}
final char ch = (char) ic;
System.out.print(ch);
if (ic == -1) {
System.out.print("ERR broaking now");
break;
}
}
}
}
Note: |
You should be able to connect any remote linux / unix instace
(Example: ec2 redhat centos linux instance using this java code). You
can use the same program if authentication method password also just
need to change one line use. Just use authenticateWithPassword(user,
passwd) method instead of authenticateWithPublicKey("centos",
keyFile, "") method |
|
- If you get connection timeout error. Please check whether
SSH port is open on the firewall or not.
|