与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.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.io.*;
/**
*
* @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 out= null;
out= sftpChannel.get(remoteFile);
BufferedReader br = new BufferedReader(new InputStreamReader(out));
String line;
while ((line = br.readLine()) != null)
System.out.println(line);
br.close();
}
catch(Exception e){System.err.print(e);}
}
}
输出:
Establishing Connection...
Connection established.
Crating SFTP Channel.
SFTP Channel created.
This is content from file /home/john/test.txt
这篇关于与Java的SSH连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文