java通过ssh连接服务器执行shell命令

来源:互联网 发布:黑马程序员html 编辑:程序博客网 时间:2024/05/22 14:44
/***@author StormMa*@date 2017-01-11*@describe login linux server by ssh*/
  • 1
  • 2
  • 3
  • 4
  • 5

生命不息,奋斗不止!


JSch 是SSH2的一个纯Java实现。它允许你连接到一个sshd 服务器,使用端口转发,X11转发,文件传输等等。你可以将它的功能集成到你自己的 程序中。同时该项目也提供一个J2ME版本用来在手机上直连SSHD服务器。

SSH是Secure Shell的缩写,一种建立在应用层和传输层基础上的安全协议。SSH在连接和传送过程中会加密所有数据,可以用来在不同系统或者服务器之间进行安全连接。SSH提供两种的安全验证方式:基于密码的认证和基于密匙的认证。其中,基于密码的认证比较简单,只要知道远程主机的用户名和密码,就可以进行登录。基于密匙的认证比较麻烦,而且连接比较耗时,这里不详细介绍。 
有很多基于SSH协议的客户端,例如:PuTTY、OpenSSH、Xshell 4等,可以远程连接几乎所有UNIX平台。同时,可以通过Linux命令行ssh uername@host连接到某主机。 
在项目中,如何利用代码实现SSH,远程执行Shell脚本呢?JSch是Java Secure Channel的缩写,是一个SSH2功能的纯Java实现,具体信息可以参考JSch官网。它允许你连接到一个SSH服务器,并且可以使用端口转发,X11转发,文件传输等,同时你也可以集成它的功能到你自己的应用程序。在使用前,需要下载并导入JSch包:jsch-0.1.50.jar。

示例程序

package com.stormma.demo;import java.io.BufferedReader;import java.io.InputStreamReader;import java.util.ArrayList;import com.jcraft.jsch.Channel;import com.jcraft.jsch.ChannelExec;import com.jcraft.jsch.JSch;import com.jcraft.jsch.JSchException;import com.jcraft.jsch.Session;public class Shell {    //远程主机的ip地址    private String ip;    //远程主机登录用户名    private String username;    //远程主机的登录密码    private String password;    //设置ssh连接的远程端口    public static final int DEFAULT_SSH_PORT = 22;      //保存输出内容的容器    private ArrayList<String> stdout;    /**     * 初始化登录信息     * @param ip     * @param username     * @param password     */    public Shell(final String ip, final String username, final String password) {         this.ip = ip;         this.username = username;         this.password = password;         stdout = new ArrayList<String>();    }    /**     * 执行shell命令     * @param command     * @return     */    public int execute(final String command) {        int returnCode = 0;        JSch jsch = new JSch();        MyUserInfo userInfo = new MyUserInfo();        try {            //创建session并且打开连接,因为创建session之后要主动打开连接            Session session = jsch.getSession(username, ip, DEFAULT_SSH_PORT);            session.setPassword(password);            session.setUserInfo(userInfo);            session.connect();            //打开通道,设置通道类型,和执行的命令            Channel channel = session.openChannel("exec");            ChannelExec channelExec = (ChannelExec)channel;            channelExec.setCommand(command);            channelExec.setInputStream(null);            BufferedReader input = new BufferedReader(new InputStreamReader                    (channelExec.getInputStream()));            channelExec.connect();            System.out.println("The remote command is :" + command);            //接收远程服务器执行命令的结果            String line;            while ((line = input.readLine()) != null) {                  stdout.add(line);              }              input.close();              // 得到returnCode            if (channelExec.isClosed()) {                  returnCode = channelExec.getExitStatus();              }              // 关闭通道            channelExec.disconnect();            //关闭session            session.disconnect();        } catch (JSchException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (Exception e) {            e.printStackTrace();        }        return returnCode;    }    /**     * get stdout     * @return     */    public ArrayList<String> getStandardOutput() {        return stdout;    }    public static void main(final String [] args) {          Shell shell = new Shell("xxx.xxx.xxx.xxx", "username", "password");        shell.execute("uname -s -r -v");        ArrayList<String> stdout = shell.getStandardOutput();        for (String str : stdout) {              System.out.println(str);          }      }  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109

MyUserInfo

package com.stormma.demo;import com.jcraft.jsch.UserInfo;public class MyUserInfo implements UserInfo {    @Override    public String getPassphrase() {        // TODO Auto-generated method stub        System.out.println("MyUserInfo.getPassphrase()");        return null;    }    @Override    public String getPassword() {        // TODO Auto-generated method stub        System.out.println("MyUserInfo.getPassword()");        return null;    }    @Override    public boolean promptPassphrase(String arg0) {        // TODO Auto-generated method stub        System.out.println("MyUserInfo.promptPassphrase()");        System.out.println(arg0);        return false;    }    @Override    public boolean promptPassword(String arg0) {        // TODO Auto-generated method stub        System.out.println("MyUserInfo.promptPassword()");          System.out.println(arg0);        return false;    }    @Override    public boolean promptYesNo(String arg0) {        // TODO Auto-generated method stub'         System.out.println("MyUserInfo.promptYesNo()");           System.out.println(arg0);           if (arg0.contains("The authenticity of host")) {               return true;           }          return true;    }    @Override    public void showMessage(String arg0) {        // TODO Auto-generated method stub        System.out.println("MyUserInfo.showMessage()");      }}
阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 饮水机净水桶安装示意图 净水机压力桶不进水 净水机桶 净水桶怎么清洗 安吉尔净水桶 饮水机净水桶 净水机有桶好还是无桶好 饮水机用净水桶 净水桶有用吗 净水机压力桶工作原理 脱水桶 净水桶好还是桶装水好 净水桶长青苔 桶式净水器 净水湾净水机 斯密斯净水机 海尔净水机价格表 单级反渗透净水设备 净水材料 净水过滤芯 颐芯牌净水机多少钱一台 鸿芯净水机 杨枝净水赞全文 变压器净油器 高夫净透控油爽肤水 植村秀净透焕颜洁颜油 植村秀净透洁颜油 旁氏男士净效控油洁面乳 贝德玛净妍控油洁肤液 深层净透卸妆油 丝塔芙净颜控油泡沫洁面乳 高夫净透控油火山泥洁面乳 净油机 果蔬净洗剂 净现值 净现值计算公式 净现值公式 净现值法 财务净现值 净现值率 投资净现值