`

Java ssh 访问windows/Linux

 
阅读更多

工作中遇到的问题:

Java code运行在一台机器上,需要远程到linux的机器同时执行多种命令。原来采用的方法是直接调用ssh命令或者调用plink的命令。

google下java的其他ssh方法,发现有个包。

具体介绍如下:

Ganymed SSH2 for Java is a library which implements the SSH-2 protocol in pure Java.It allows one to connect to SSH servers from within Java programs. It supports SSH sessions(remote command execution and shell access),local and remote port forwarding, local stream forwarding, X11 forwarding, SCP and SFTP.There are no dependencies on any JCE provider, as all crypto functionality is included.

Ganymed SSH2 for Java was first developed for the Ganymed replication project and acouple of other projects at the IKS group at ETH Zurich.

Website: http://www.cleondris.ch/opensource/ssh2/.

给个链接:http://www.cleondris.ch/opensource/ssh2/javadoc/

更多关于ssh协议的介绍可以查看http://www.ietf.org/rfc/rfc4251.txt

包中主要的类:

Package ch.ethz.ssh2

Interface Summary
ChannelCondition Contains constants that can be used to specify what conditions to wait for on a SSH-2 channel (e.g., represented by aSession).
ConnectionMonitor ConnectionMonitor is used to get notified when the underlying socket of a connection is closed.
InteractiveCallback An InteractiveCallback is used to respond to challenges sent by the server if authentication mode "keyboard-interactive" is selected.
ProxyData An abstract marker interface implemented by all proxy data implementations.
ServerHostKeyVerifier A callback interface used to implement a client specific method of checking server host keys.

 

Class Summary
Connection Connection is used to establish an encrypted TCP/IP connection to a SSH-2 server.
ConnectionInfo In most cases you probably do not need the information contained in here.
DHGexParameters DHGexParameters object can be used to specify parameters for the diffie-hellman group exchange.
HTTPProxyData HTTPProxyData object is used to specify the needed connection data to connect through a HTTP proxy.
KnownHosts The KnownHosts class is a handy tool to verify received server hostkeys based on the information inknown_hosts files (the ones used by OpenSSH).
LocalPortForwarder LocalPortForwarder forwards TCP/IP connections to a local port via the secure tunnel to another host (which may or may not be identical to the remote SSH-2 server).
LocalStreamForwarder LocalStreamForwarder forwards an Input- and Outputstream pair via the secure tunnel to another host (which may or may not be identical to the remote SSH-2 server).
SCPClient A very basic SCPClient that can be used to copy files from/to the SSH-2 server.
Session Session is a remote execution of a program.
SFTPv3Client SFTPv3Client represents a SFTP (protocol version 3) client connection tunnelled over a SSH-2 connection.
SFTPv3DirectoryEntry SFTPv3DirectoryEntry as returned by SFTPv3Client.ls(String).
SFTPv3FileAttributes SFTPv3FileAttributes object represents detail information about a file on the server.
SFTPv3FileHandle SFTPv3FileHandle.
StreamGobbler StreamGobbler is an InputStream that uses an internal worker thread to constantly consume input from another InputStream.

 

Exception Summary
HTTPProxyException May be thrown upon connect() if a HTTP proxy is being used.
SFTPException Used in combination with the SFTPv3Client.

 

给个例子:

(1) SSH到Linux机器

package ssh;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.*;
public class Basic {
    public static void main(String[] args)
    {
        String hostname ="9.12.175.30";
        String username="root";
        String password="password";
        try{
            //建立连接
            Connection conn= new Connection(hostname);
            System.out.println("set up connections");
            conn.connect();
            //利用用户名和密码进行授权
            boolean isAuthenticated = conn.authenticateWithPassword(username, password);
            if(isAuthenticated ==false)
            {
                throw new IOException("Authorication failed");
            }
            //打开会话
            Session sess = conn.openSession();
            System.out.println("Execute command:/usr/bin/perl /test/discover.pl /test/meps_linux.txt");
            //执行命令
            sess.execCommand("/usr/bin/perl /test/discover.pl /test/meps_linux.txt");
            System.out.println("The execute command output is:");
            InputStream stdout = new StreamGobbler(sess.getStdout());
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
            while(true)
            {
                String line = br.readLine();
                if(line==null) break;
                System.out.println(line);
            }
            System.out.println("Exit code "+sess.getExitStatus());
            sess.close();
            conn.close();
            System.out.println("Connection closed");
        }catch(IOException e)
        {
            System.out.println("can not access the remote machine");
        }
    }

}

(2) SSH到windows机器:

windows由于没有默认的ssh server,因此在允许ssh之前需要先安装ssh server。

下载freeSSHd

http://www.freesshd.com/?ctt=download

安装
直接执行freeSSHd.exe就可以进行安装了(用户一定要有管理员权限),安装过程中freeSSHd会问你

Private keys should be created. Should I do it now?


这是问你是否需要现在创建私钥,回答是

Do you want to run FreeSSHd as a system service?


这是问你是否希望把freeSSHd作为系统服务启动,回答是之后就安装完成了

配置用户名和密码:

用putty测试连接。

Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\WINDOWS\system32>

例子一中需要两行代码进行修改:

String hostname ="localhost";

sess.execCommand("cmd");

输出结果:

set up connections
Begin execute remote commands
The execute command output is:
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

 

如果要在cmd中执行其他命令,如perl

则使用:

sess.execCommand("cmd.exe /c \"perl -V\"");

 

cmd /c dir 是执行完dir命令后关闭命令窗口。

cmd /k dir 是执行完dir命令后不关闭命令窗口。

cmd /c start dir 会打开一个新窗口后执行dir指令,原窗口会关闭。

cmd /k start dir 会打开一个新窗口后执行dir指令,原窗口不会关闭。

可以用cmd /?查看帮助信息。

 

说白了感觉java的ssh就是一个client

分享到:
评论

相关推荐

    SSH System Administration Tool:用于Unix,Linux管理和监视的SSH Java客户端GUI-开源

    Raanan Zion https://au.linkedin.com/pub/raanan-zion/88/7b9/255 ssh用于Unix,Linux和MS Windows系统管理和监视的Java接口。 自动执行防火墙规则检查; 将结果导出到Excel。 允许您同时在多个服务器上运行多个...

    JAVA上百实例源码以及开源项目源代码

     Java访问权限控制,为Java操作文件、写入文件分配合适的权限,定义写到文件的信息、定义文件,输出到c:/hello.txt、写信息到文件、关闭输出流。 Java绘制图片火焰效果 1个目标文件 摘要:Java源码,图形操作,火焰...

    JAVA上百实例源码以及开源项目

     Java访问权限控制,为Java操作文件、写入文件分配合适的权限,定义写到文件的信息、定义文件,输出到c:/hello.txt、写信息到文件、关闭输出流。 Java绘制图片火焰效果 1个目标文件 摘要:Java源码,图形操作,火焰...

    java开源包4

    JCom (Java-COM Bridge) 可以让 Java 程序轻松访问 Windows 平台上的 COM 组件。 JARP JARP是为petri 网提供的一个Java编辑器,基于ARP分析器。可以将网络图导出为 GIF, JPEG, PNG, PPM, ARP and PNML (XML based)...

    java开源包101

    JCom (Java-COM Bridge) 可以让 Java 程序轻松访问 Windows 平台上的 COM 组件。 JARP JARP是为petri 网提供的一个Java编辑器,基于ARP分析器。可以将网络图导出为 GIF, JPEG, PNG, PPM, ARP and PNML (XML based)...

    java开源包11

    JCom (Java-COM Bridge) 可以让 Java 程序轻松访问 Windows 平台上的 COM 组件。 JARP JARP是为petri 网提供的一个Java编辑器,基于ARP分析器。可以将网络图导出为 GIF, JPEG, PNG, PPM, ARP and PNML (XML based)...

    java开源包6

    JCom (Java-COM Bridge) 可以让 Java 程序轻松访问 Windows 平台上的 COM 组件。 JARP JARP是为petri 网提供的一个Java编辑器,基于ARP分析器。可以将网络图导出为 GIF, JPEG, PNG, PPM, ARP and PNML (XML based)...

    java开源包9

    JCom (Java-COM Bridge) 可以让 Java 程序轻松访问 Windows 平台上的 COM 组件。 JARP JARP是为petri 网提供的一个Java编辑器,基于ARP分析器。可以将网络图导出为 GIF, JPEG, PNG, PPM, ARP and PNML (XML based)...

    java开源包5

    JCom (Java-COM Bridge) 可以让 Java 程序轻松访问 Windows 平台上的 COM 组件。 JARP JARP是为petri 网提供的一个Java编辑器,基于ARP分析器。可以将网络图导出为 GIF, JPEG, PNG, PPM, ARP and PNML (XML based)...

    java开源包8

    JCom (Java-COM Bridge) 可以让 Java 程序轻松访问 Windows 平台上的 COM 组件。 JARP JARP是为petri 网提供的一个Java编辑器,基于ARP分析器。可以将网络图导出为 GIF, JPEG, PNG, PPM, ARP and PNML (XML based)...

    java开源包10

    JCom (Java-COM Bridge) 可以让 Java 程序轻松访问 Windows 平台上的 COM 组件。 JARP JARP是为petri 网提供的一个Java编辑器,基于ARP分析器。可以将网络图导出为 GIF, JPEG, PNG, PPM, ARP and PNML (XML based)...

    java开源包3

    JCom (Java-COM Bridge) 可以让 Java 程序轻松访问 Windows 平台上的 COM 组件。 JARP JARP是为petri 网提供的一个Java编辑器,基于ARP分析器。可以将网络图导出为 GIF, JPEG, PNG, PPM, ARP and PNML (XML based)...

    java开源包1

    JCom (Java-COM Bridge) 可以让 Java 程序轻松访问 Windows 平台上的 COM 组件。 JARP JARP是为petri 网提供的一个Java编辑器,基于ARP分析器。可以将网络图导出为 GIF, JPEG, PNG, PPM, ARP and PNML (XML based)...

    onewolf:大山_一匹狼

    这个项目的版本库是 Git格式 ,在 Windows、Linux、Mac OS X 平台都有客户端工具可以访问。虽然版本库只提供Git一种格式, 但是你还是可以用其他用其他工具访问,如 svn 和 hg 。 版本库地址 支持三种访问协议: ...

    RED HAT LINUX 6大全

    本书全面系统地介绍了Red Hat Linux 6。全书共分为五个部分,包括35章和四个附录。第一部分为Red Hat Linux的介绍和安装;第二部分为服务配置;第三部分为系统管理;第四部分为Linux编程;第五部分为附录。本书内容...

    Xshell-Linux远程登录-免费的服务器连接工具 (永久使用版)

    Xshell可以在Windows界面下用来访问远端不同系统下的服务器,从而比较好的达到远程控制终端的目的。除此之外,其还有丰富的外观配色方案以及样式选择。 功能如下: 1. 有效保护信息安全性 Xshell支持各种安全功能,...

    java开源包2

    JCom (Java-COM Bridge) 可以让 Java 程序轻松访问 Windows 平台上的 COM 组件。 JARP JARP是为petri 网提供的一个Java编辑器,基于ARP分析器。可以将网络图导出为 GIF, JPEG, PNG, PPM, ARP and PNML (XML based)...

    java开源包7

    JCom (Java-COM Bridge) 可以让 Java 程序轻松访问 Windows 平台上的 COM 组件。 JARP JARP是为petri 网提供的一个Java编辑器,基于ARP分析器。可以将网络图导出为 GIF, JPEG, PNG, PPM, ARP and PNML (XML based)...

    Java资源包01

    JCom (Java-COM Bridge) 可以让 Java 程序轻松访问 Windows 平台上的 COM 组件。 JARP JARP是为petri 网提供的一个Java编辑器,基于ARP分析器。可以将网络图导出为 GIF, JPEG, PNG, PPM, ARP and PNML (XML based)...

Global site tag (gtag.js) - Google Analytics