Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import com.jcraft.jsch.*;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.util.Scanner;
- public class Javassh {
- public static void main(String args[]) throws IOException {
- String user = "<YOUR LOGIN>";
- String password = "<YOUR PASSWORD>";
- String host = "<YOUR HOST>";
- int port = 22;
- String remoteFile = "/home/root/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");
- int lport;
- String rhost = "localhost";
- int rport;
- sftpChannel.connect();
- String command = "nc localhost 5000";
- Channel channel = session.openChannel("exec");
- ((ChannelExec) channel).setCommand(command);
- channel.setInputStream(null);
- ((ChannelExec) channel).setErrStream(System.err);
- InputStream in = channel.getInputStream();
- channel.connect();
- byte[] tmp = new byte[1024];
- while (true)
- {
- while (in.available() > 0)
- {
- int i = in.read(tmp, 0, 1024);
- if (i < 0)
- break;
- System.out.print(new String(tmp, 0, i));
- }
- if (channel.isClosed())
- {
- System.out.println("exit-status: " + channel.getExitStatus());
- break;
- }
- try
- {
- Thread.sleep(1000);
- }
- catch (Exception ee)
- {
- }
- }
- channel.disconnect();
- 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();
- }
- }
- }
Add Comment
Please, Sign In to add comment