`
zxw882011_98
  • 浏览: 10301 次
  • 性别: Icon_minigender_2
  • 来自: 上海
社区版块
存档分类
最新评论

java 通过SSH方式连接AIX服务器

阅读更多
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import com.sshtools.j2ssh.SshClient;
import com.sshtools.j2ssh.authentication.AuthenticationProtocolState;
import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient;
import com.sshtools.j2ssh.session.PseudoTerminal;
import com.sshtools.j2ssh.session.SessionChannelClient;
import com.sshtools.j2ssh.transport.InvalidHostFileException;

/**
* 通过SSH协议连接远程服务器,并且发送命令获取执行结果。
* <p>
* 备注:此类引用j2ssh-core-0.2.9.jar包连接远程服务器,并且发送命令获取执行结果,
* <p>
* 执行结果已经特殊处理,不适合所有命令, 默认获取echo命令的执行结果,若有其它需求,请自添加代码。
*
* @author xxx
*
*/
public class SshClientTools {
    private String hostip = null;
    private int port;
    private String userName = null;
    private String password = null;
    private SshClient ssh = null;
    private SessionChannelClient session = null;

    public void setPort(int port) {
        this.port = port;
    }

    public int getPort() {
        return port;
    }

    public void setHostip(String hostip) {
        this.hostip = hostip;
    }

    public String getHostip() {
        return hostip;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserName() {
        return userName;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPassword() {
        return password;
    }

    /**
     * 构造函数,初始化远程主机ip,端口,用户名,密码信息。
     *
     * @param host
     *            主机ip地址
     * @param port
     *            ssh协议的端口号(如22)
     * @param userName
     *            用户名
     * @param passwd
     *            密码
     * @throws Exception
     */
    public SshClientTools(String host, int port, String userName, String passwd)
            throws Exception {
        if (host == null || host.length() == 0)
            throw new Exception("lose the host.");
        if (userName == null || userName.length() == 0)
            throw new Exception("lose the LoginName.");
        if (passwd == null || passwd.length() == 0)
            throw new Exception("lose the password.");

        this.setHostip(host);
        this.setPort(port);
        this.setUserName(userName);
        this.setPassword(passwd);
        this.ssh = new SshClient();
    }

    /**
     * 连接主机
     *
     * @author xxx
     * @return true or false
     * @throws Exception
     */
    private boolean connect() throws Exception {
        if (ssh == null)
            throw new Exception("SshClient is null.");

        PasswordAuthenticationClient authentication = new PasswordAuthenticationClient();
        authentication.setUsername(this.userName);
        authentication.setPassword(this.password);
        ConsoleKnownHostsKeyVerification console;
        try {
            // console对象默认选择Always接受host key
            console = new ConsoleKnownHostsKeyVerification();
            ssh.connect(this.hostip, 22, console);
            if (ssh.authenticate(authentication) == AuthenticationProtocolState.COMPLETE)
                return true;
            else
                return false;
        } catch (InvalidHostFileException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 功能:发送命令之后,从流中读取信息获取命令的执行结果。
     * <p>
     * 本函数设计只发送echo命令,若发送执行结果为多行的命令将无法获取正确的执行结果,如:ls、 top等。
     *
     * <p>
     * 以下到“备注”是登录信息举例:为能够在注释中显示,在@和\前添加了转移符
     * <p>
     * Last login: Mon Jan 30 02:12:27 2012
     * <p>
     * echo $PS1
     * <p>
     * exit
     * <p>
     * [root\@localhost ~]# echo $PS1
     * <p>
     * [\\u@\\h \\W]\\$
     * <p>
     * [root\@localhost ~]# exit
     * <p>
     * logout
     * <p>
     * 备注:因为流中包含上次登录信息、上次执行的命令和本次执行的命令及结果,
     * <p>
     * 在获取本次命令的执行结果时,按行读取流中所有信息存入集合,然后取集合中的数据 ( 当集合
     * >=6时,取集合size()-3位置的数据),因为本函数默认会发送exit命令退出登录,所以集合中必须至少有6行结果(两条命令和两条执行结果,
     * 登录提示信息和空行,另外可能还包含上次登录时执行的命令),如果集合大小小于6认为读取失败将返回null。
     *
     * @author xxx
     * @param strCommand
     *            echo命令,通过echo来查询需要的信息。
     * @return 返回执行结果或null
     * @throws Exception
     */
    public String executeCommand(String strCommand) throws Exception {
        ArrayList<String> array_result = new ArrayList<String>();
        if (ssh == null)
            throw new Exception("SshClient is null.");
        if (!ssh.isConnected()) {
            this.connect();
        }
        if (!ssh.isConnected())
            return null;

        session = ssh.openSessionChannel();
        if (session.requestPseudoTerminal("dumb", PseudoTerminal.ECHO, 0, 0, 0,
                null)) {
            if (session.startShell()) {
                // 发送命令
                OutputStream writer = session.getOutputStream();
                writer.write(strCommand.getBytes());
                writer.write("\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;
                System.out.println("session.getInputStream info ...");
                while ((line = in.readLine()) != null) {
                    System.out.println(line);
                    array_result.add(line);
                }
                System.out.println("session.getStderrInputStream info ...");
                while ((line = err.readLine()) != null) {
                    System.out.println(line);
                }
                if (session != null) {
                    session.close();
                }
                if (ssh != null)
                    ssh.disconnect();
            }
        }
        if (array_result.size() >= 6)
            return array_result.get(array_result.size() - 3);
        else
            return null;
    }

    public static void main(String args[]) {
        try {
            SshClientTools ssh = new SshClientTools("192.168.91.3", 22, "root",
                    "anders");
            System.out.println(ssh.executeCommand("echo $PS1"));
            System.out.println(ssh.executeCommand("echo $HOME"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
分享到:
评论

相关推荐

    Aix服务器安装(包括Oracle9)

    【AIX服务器安装】 AIX(Advanced Interactive eXecutive)是IBM开发的一款UNIX操作系统,主要应用于IBM的Power架构服务器。在没有显卡的情况下安装AIX,通常需要借助远程控制工具,如Secure Shell (SSH) 或 Telnet...

    ssh_java实现_ibm

    JSch是一个纯Java实现的SSH2库,允许Java应用程序连接到支持SSH协议的服务器,进行命令执行、文件传输等功能。它支持公钥/私钥认证、密码认证等多种认证方式,并且能够处理端口转发和X11转发等高级特性。 SSH Lite...

    AIX\AU14上.pdf

    - **远程访问**:讲解如何通过SSH等协议远程连接到AIX系统。 - **任务自动化**:利用脚本语言(如Shell脚本)自动化常规管理任务,提高工作效率。 ### 商标声明 教材中明确指出了一些重要的商标信息,比如IBM、Java...

    AIX简要中文资料AIX简要中文资料

    此外,AIX还支持通过SSH进行远程管理。 6. **性能优化**:AIX的性能调优工具,如top、prstat、vmstat等,可以帮助管理员监控系统资源的使用情况,调整工作负载以优化性能。 7. **高可用性**:AIX支持逻辑分区...

    工行B2C接口 JAVA

    而在Linux环境下,开发可能需要更多依赖命令行工具,如使用Git进行版本控制,使用Jenkins进行持续集成,通过SSH远程登录服务器进行部署,应用服务器可能选择的是Apache Tomcat或JBoss。 文件“java_aix+linux”可能...

    AIX培训教材

    同时,AIX支持加密文件系统(EFS)和Secure Shell(SSH),保障数据安全和远程访问的安全性。 ### 6. 开发与调试 AIX提供完整的开发环境,支持C、C++、Java等编程语言。其集成开发环境(IDE)如VisualAge for C++...

    xs-box-client 是一个将局域网个人电脑、服务器代理到公网的内网穿透工具,支持tcp流量转发,可支持任何tcp上层协议

    xs-box-client 是一个将局域网个人电脑、服务器代理到公网的内网穿透工具,支持tcp流量转发,可支持任何tcp上层协议(访问内网网站、本地支付接口调试、ssh访问、远程桌面...)。可以让外网直接访问本地网站 ...

    华为服务器客服电话_漏洞扫描设备参数.pdf

    在系统功能方面,华为服务器的漏洞扫描设备要求能够对系统漏洞、网站漏洞和无线安全漏洞进行全面扫描,并在扫描完成后生成详细的安全评估报告,通过电子邮件、FTP等方式发送。设备应支持多种告警方式,如短信、邮件...

    文思面试题(java)

    7. **DWR(Direct Web Remoting)**:DWR允许JavaScript与服务器端Java代码进行交互,实现Ajax功能。要能解释DWR的工作原理,并提供在项目中使用DWR的实例。 8. **版本控制**:理解Git、SVN等版本控制系统的重要性...

    weblogic在Unix、Linux下的安装配置

    2. **控制台模式(基于文本方式的交互)**:在没有图形界面或通过SSH远程访问时,使用命令行进行安装。 3. **无人守护安装模式**:非交互式的命令行执行方式,常用于自动化部署。 三、安装过程 在图形模式下,安装...

    JProbe的安装指南

    3. 通过SSH登录服务器,以root用户身份切换到安装文件所在目录,并赋予文件执行权限。 4. 运行安装命令,遵循提示完成安装。 在安装过程中,务必仔细阅读英文安装指南,以获取更详细的平台和硬件需求信息。安装完成...

    weblogic 11g静默安装以及saltstack自动化安装

    **WebLogic Server** 是一款由Oracle公司开发的企业级应用服务器,它提供了丰富的功能来支持Java EE应用程序的运行。在实际部署场景中,特别是在大规模部署或更新时,静默安装模式变得尤为重要。静默安装允许管理员...

    MySQL中文参考手册

    + 4.12.5 用 SSH 从 Win32 连接一个远程MySQL + 4.12.6 MySQL-Win32与Unix MySQL 比较 o 4.13 OS/2 注意事项 o 4.14 TcX 二进制代码 o 4.15 安装后期(post-installation)的设置与测试 + 4.15.1 运行mysql_...

    MYSQL

    4.12.1 在 Win32 上安装 MySQL 4.12.2 在 Win95 /Win98上启动 MySQL 4.12.3 在 NT 上启动 MySQL 4.12.4 在 Win32 上运行 MySQL 4.12.5 用 SSH 从 Win32 连接一个远程MySQL 4.12.6 MySQL-Win...

    CarlosOnWeb-SampleContract.zip_Windows编程_Windows_Unix_

    此外,SSH(Secure Shell)协议使得在Windows上远程管理和控制Unix系统成为可能,而Samba则允许Windows系统与Unix/Linux系统共享文件和打印服务。 压缩包中的"CarlosOnWeb-SampleContract.doc"文件很可能是合同模板...

    MySQL中文参考手册.chm

    Win32 上安装 MySQL 4.12.2 在 Win95 /Win98上启动 MySQL 4.12.3 在 NT 上启动 MySQL 4.12.4 在 Win32 上运行 MySQL 4.12.5 用 SSH 从 Win32 连接一个远程MySQL 4.12.6 MySQL-Win32与Unix ...

Global site tag (gtag.js) - Google Analytics