Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import com.jcraft.jsch.*;
- import java.io.BufferedReader;
- import java.io.DataInputStream;
- import java.io.DataOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- public class SSHClient {
- public static void main(String[] args) throws JSchException, IOException {
- String endLineStr = " # "; // it is dependant to the server
- String host = ""; // host IP
- String user = ""; // username for SSH connection
- String password = ""; // password for SSH connection
- int port = 22; // default SSH port
- JSch shell = new JSch();
- // get a new session
- Session session = shell.getSession(user, host, port);
- // set user password and connect to a channel
- session.setUserInfo(new SSHUserInfo(password));
- session.connect();
- Channel channel = session.openChannel("shell");
- channel.connect();
- ChannelExec channelExec = (ChannelExec)session.openChannel("exec");
- InputStream in = channelExec.getInputStream();
- channelExec.setCommand("ls");
- channelExec.connect();
- BufferedReader reader = new BufferedReader(new InputStreamReader(in));
- String line;
- int index = 0;
- while ((line = reader.readLine()) != null)
- {
- System.out.println(++index + " : " + line);
- }
- int exitStatus = channelExec.getExitStatus();
- channelExec.disconnect();
- session.disconnect();
- if(exitStatus < 0){
- System.out.println("Done, but exit status not set!");
- }
- else if(exitStatus > 0){
- System.out.println("Done, but with error!");
- }
- else{
- System.out.println("Done!");
- }
- // DataInputStream dataIn = new DataInputStream(channel.getInputStream());
- // DataOutputStream dataOut = new DataOutputStream(channel.getOutputStream());
- //
- // // send ls command to the server
- // dataOut.writeBytes("ls");
- // dataOut.flush();
- //
- // // and print the response
- // String line = dataIn.readLine();
- // System.out.println(line);
- // while(!line.endsWith(endLineStr)) {
- // System.out.println(line);
- // line = dataIn.readLine();
- // }
- // dataIn.close();
- // dataOut.close();
- channel.disconnect();
- session.disconnect();
- }
- // this class implements jsch UserInfo interface for passing password to the session
- static class SSHUserInfo implements UserInfo {
- private String password;
- SSHUserInfo(String password) {
- this.password = password;
- }
- public String getPassphrase() {
- return null;
- }
- public String getPassword() {
- return password;
- }
- public boolean promptPassword(String arg0) {
- return true;
- }
- public boolean promptPassphrase(String arg0) {
- return true;
- }
- public boolean promptYesNo(String arg0) {
- return true;
- }
- public void showMessage(String arg0) {
- System.out.println(arg0);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement