Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SSH connection with Java

How can I connect to an SSH server in Java? I don't need/want a shell. I just want to connect to the SSH server and get the content of, say, file.txt. How can I do that?

like image 884
user348041 Avatar asked Jun 18 '10 17:06

user348041


People also ask

Can you SSH with Java?

JSch is the Java implementation of SSH2 that allows us to connect to an SSH server and use port forwarding, X11 forwarding, and file transfer. Also, it is licensed under the BSD style license and provides us with an easy way to establish an SSH connection with Java.

How do I connect to a remote computer using Java?

You could install an SSH server on your remote desktop and you can write a Java program using jcraft and jsch libraries on your local machine to make an SSH connection to your remote desktop.

What is Jcraft JSch?

JSch is a pure Java implementation of SSH2. JSch allows you to connect to an sshd server and use port forwarding, X11 forwarding, file transfer, etc., and you can integrate its functionality into your own Java programs. JSch is licensed under BSD style license.


1 Answers

Use JSch

import com.jcraft.jsch.*;  import java.io.InputStream; import java.io.InputStreamReader; import java.util.Scanner;  /**  * @author World  */ public class SSHReadFile {      public static void main(String args[]) {         String user = "john";         String password = "mypassword";         String host = "192.168.100.23";         int port = 22;         String remoteFile = "/home/john/test.txt";          try {             JSch jsch = new JSch();             Session session = jsch.getSession(user, host, port);             session.setPassword(password);             session.setConfig("StrictHostKeyChecking", "no");             System.out.println("Establishing Connection...");             session.connect();             System.out.println("Connection established.");             System.out.println("Crating SFTP Channel.");             ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");             sftpChannel.connect();             System.out.println("SFTP Channel created.");              InputStream inputStream = sftpChannel.get(remoteFile);              try (Scanner scanner = new Scanner(new InputStreamReader(inputStream))) {                 while (scanner.hasNextLine()) {                     String line = scanner.nextLine();                     System.out.println(line);                 }             }         } catch (JSchException | SftpException e) {             e.printStackTrace();         }     } } 

output:

Establishing Connection... Connection established. Crating SFTP Channel. SFTP Channel created. This is content from file /home/john/test.txt 
like image 83
World Avatar answered Nov 01 '22 01:11

World