Skip to content

Instantly share code, notes, and snippets.

@nakshay
Created December 17, 2019 08:13
Show Gist options
  • Save nakshay/8d3eb1337c1217095f9eea0e4b54a3a5 to your computer and use it in GitHub Desktop.
Save nakshay/8d3eb1337c1217095f9eea0e4b54a3a5 to your computer and use it in GitHub Desktop.
SSH client in java using Jcraft JSCH library
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class SSHClient {
public static void main(String[] args) {
try {
JSch jsch = new JSch();
String user = "akshay.naik";
String host = "192.***.**.**";
int port = 22;
String privateKey = "C:\\~\\private_key.pem";
jsch.addIdentity(privateKey);
//jsch.addIdentity(privateKey,"securePassword"); if key is protected by passphrase
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();
Channel channel = session.openChannel("shell");
channel.setInputStream(System.in);
//channel.setInputStream(new FileInputStream(new File("D://commands.txt"))); if want to send commands from text file
channel.setOutputStream(System.out);
channel.connect(3 * 1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment