与 Java 的 SSH 连接 [英] SSH connection with Java
本文介绍了与 Java 的 SSH 连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用 Java 连接到 SSH 服务器?我不需要/想要一个外壳.我只想连接到 SSH 服务器并获取例如 file.txt
的内容.我该怎么做?
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?
推荐答案
使用 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();
}
}
}
输出:
Establishing Connection...
Connection established.
Crating SFTP Channel.
SFTP Channel created.
This is content from file /home/john/test.txt
这篇关于与 Java 的 SSH 连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文