-
-
Save ptrthomas/920f8a42fac4ab0bb121a5ad74b09cdb to your computer and use it in GitHub Desktop.
Example of Jsch usage for SSH
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.OutputStream; | |
import java.io.PrintStream; | |
import java.util.concurrent.TimeUnit; | |
import com.jcraft.jsch.*; | |
public class SSH { | |
public static void main(String[] args) { | |
System.out.println("Begin!"); | |
try { | |
JSch jsch = new JSch(); | |
String user = "ec2-user"; | |
String host = "52.1.161.173"; | |
int port = 22; | |
String privateKey = "HW2KeyPair.pem"; | |
jsch.addIdentity(privateKey); | |
// System.out.println("identity added "); | |
Session session = jsch.getSession(user, host, port); | |
// System.out.println("session created."); | |
java.util.Properties config = new java.util.Properties(); | |
config.put("StrictHostKeyChecking", "no"); | |
session.setConfig(config); | |
session.connect(); | |
// System.out.println("session connected....."); | |
Channel channel = session.openChannel("shell"); | |
OutputStream inputstream_of_channel = channel.getOutputStream(); | |
PrintStream commander = new PrintStream(inputstream_of_channel, | |
true); | |
channel.setOutputStream(System.out, true); | |
((ChannelShell)channel).setPty(true); | |
channel.connect(); | |
// System.out.println("shell channel connected...."); | |
commander.print("pwd\n"); | |
commander.print("whoami\n"); | |
commander.print("exit\n"); | |
commander.close(); | |
do { | |
TimeUnit.SECONDS.sleep(1); | |
} while (!channel.isEOF()); | |
session.disconnect(); | |
} catch (Exception e) { | |
System.err.println(e); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment