zoukankan      html  css  js  c++  java
  • java程序连接Liunx服务器并且执行命令

    JSch 介绍

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

    1.导入jar包

    <dependency>
        <groupId>com.jcraft</groupId>
        <artifactId>jsch</artifactId>
        <version>0.1.54</version>
    </dependency>

    2.JAVA程序连接SSH实例

    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;
    import com.jcraft.jsch.UserInfo;
    
    /**
     * 
     * @desc SSHConnectionTest.java 
     *
     * @author xianlei
     * @date 2018年3月29日下午5:53:24
     */
    public class SSHConnectionTest {
          //远程主机的ip地址
        private String ip;
        //远程主机登录用户名
        private String username;
        //远程主机的登录密码
        private String password;
        //设置ssh连接的远程端口
        public static final int DEFAULT_SSH_PORT = 22;  
        //保存输出内容的容器
        private ArrayList<String> stdout;
        
        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()");  
            }
            
        }
    
        /**
         * 初始化登录信息
         * @param ip
         * @param username
         * @param password
         */
        public SSHConnectionTest(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.setConfig("StrictHostKeyChecking", "no");  
                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) {  
            String password = "";
            String username = "root";
            String ip = "";
            SSHConnectionTest shell = new SSHConnectionTest(ip, username, password);
            
            //启动redis服务命令
            shell.execute("cd /usr/local/redis && ./redis-server redis.conf &");
            //关闭redis服务命令
    //      shell.execute("cd /usr/local/redis && ./redis-cli shutdown");
    
            ArrayList<String> stdout = shell.getStandardOutput();
            for (String str : stdout) {  
                System.out.println(str);  
            }  
        }  
    }
  • 相关阅读:
    CSS实现雨滴动画效果
    大型网站架构系列:电商网站架构案例
    CSS 不定宽高的垂直水平居中方式总汇
    js中尺寸类样式
    Tiling
    排序二叉树
    算术表达式的转换
    Area
    catch that cow
    R中双表操作学习[转载]
  • 原文地址:https://www.cnblogs.com/xianlei/p/8671375.html
Copyright © 2011-2022 走看看