用j2ssh-core-0.2.9.jar连接远程主机时,第一次会需要用户输入Yes\No\Always来是否接受主机公匙,如果程序在后台运行,无法与用户交互,所以需要ConsoleKnownHostsKeyVerification类,然后在连接时使用SshClient.connect(String hostname, int port,
HostKeyVerification hosts),hosts参数使用此类的对象。
下面是ConsoleKnownHostsKeyVerification类的代码
package test; import java.io.File; import java.io.IOException; import com.sshtools.j2ssh.transport.AbstractKnownHostsKeyVerification; import com.sshtools.j2ssh.transport.InvalidHostFileException; import com.sshtools.j2ssh.transport.publickey.SshPublicKey; public class ConsoleKnownHostsKeyVerification extends AbstractKnownHostsKeyVerification { public ConsoleKnownHostsKeyVerification() throws InvalidHostFileException { super(new File(System.getProperty("user.home"), ".ssh" + File.separator + "known_hosts").getAbsolutePath()); } public ConsoleKnownHostsKeyVerification(String knownhosts) throws InvalidHostFileException { super(knownhosts); } public void onHostKeyMismatch(String host, SshPublicKey pk, SshPublicKey actual) { try { System.out.println("The host key supplied by " + host + " is: " + actual.getFingerprint()); System.out.println("The current allowed key for " + host + " is: " + pk.getFingerprint()); getResponse(host, pk); } catch (Exception e) { e.printStackTrace(); } } public void onUnknownHost(String host, SshPublicKey pk) { try { System.out.println("The host " + host + " is currently unknown to the system"); System.out.println("The host key fingerprint is: " + pk.getFingerprint()); getResponse(host, pk); } catch (Exception e) { e.printStackTrace(); } } /** * 获取用户输入的信息,判断是否接受主机公匙 * <p> * 修改:xxx ,去掉从流中获取信息,直接接受公匙,注释掉的代码为源码 * * @param host * 主机ip * @param pk * 主机公匙 * @throws InvalidHostFileException * @throws IOException */ private void getResponse(String host, SshPublicKey pk) throws InvalidHostFileException, IOException { if (isHostFileWriteable()) { allowHost(host, pk, true); } } }
测试代码如下,主要是测试了下载文件,和最常用的日志查询的命令
package test; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; import com.sshtools.j2ssh.SftpClient; import com.sshtools.j2ssh.SshClient; import com.sshtools.j2ssh.authentication.AuthenticationProtocolState; import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient; import com.sshtools.j2ssh.connection.ChannelOutputStream; import com.sshtools.j2ssh.session.SessionChannelClient; import com.sshtools.j2ssh.sftp.FileAttributes; import com.sshtools.j2ssh.sftp.SftpFile; public class TestSsh { @SuppressWarnings("unchecked") public static void main(String[] args) { SshClient client = new SshClient(); try { ConsoleKnownHostsKeyVerification console = new ConsoleKnownHostsKeyVerification(); client.connect("172.16.20.133", 22,console);//IP和端口 //设置用户名和密码 PasswordAuthenticationClient pwd = new PasswordAuthenticationClient(); pwd.setUsername("root"); pwd.setPassword("111111"); int result = client.authenticate(pwd); if (result == AuthenticationProtocolState.COMPLETE) {//如果连接完成 SftpClient sftp = client.openSftpClient(); List<SftpFile> list = sftp.ls("./Desktop/hehe"); for (SftpFile f : list) { //下载文件 /* FileOutputStream fos = new FileOutputStream(new File("c:/1.txt")); FileAttributes fa =sftp.get(f.getAbsolutePath(),fos); fos.write(fa.toByteArray()); fos.close();*/ //取日志(取2012-09-12 删除用户 的日志) if(f.getFilename().endsWith(".out")||f.getFilename().endsWith(".log")){ SessionChannelClient session = client.openSessionChannel(); if (session.startShell()){ ChannelOutputStream writer = session.getOutputStream(); writer.write("grep -E '2012-09-12 删除用户'\n".getBytes()); writer.flush(); writer.write("exit\n".getBytes()); writer.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(session.getInputStream())); BufferedReader err= new BufferedReader(new InputStreamReader(session.getStderrInputStream())); String line; while ((line = in.readLine()) != null){ System.out.println(line); } System.out.println("------------------------"); while ((line = err.readLine()) != null){ System.out.println(line); } } } } } } catch (IOException e) { e.printStackTrace(); } } }
附件是jar包