精华内容
下载资源
问答
  • java实现SSH协议连接linux

    千次阅读 2020-07-06 19:49:39
    所以采用java代码的方式连接服务器实现自动上传换版本启动的过程。。 首先: 使用ssh协议的jar引进工程pom依赖: <dependency> <groupId>ch.ethz.ganymed</groupId> <artifactId

    初衷:

    在每次部署项目的时候,每次都得打包,使用xshell连接linux服务器,每次在连接的时候都会很慢,还得杀死原先的进程id并删除之前的版本,很烦!!所以采用java代码的方式连接服务器实现自动上传换版本启动的过程。。


    首先:

    使用ssh协议的jar引进工程pom依赖:

            <dependency>
                <groupId>ch.ethz.ganymed</groupId>
                <artifactId>ganymed-ssh2</artifactId>
                <version>build210</version>
            </dependency>

    可能本地中远程仓库中没有改依赖包,解决方法:首先去这个网站(http://www.ganymed.ethz.ch/ssh2/)去下载,然后呢把他添加到自己的本地仓库中,具体操作方法如下:

    首先下载的是一个zip文件,解压文件,里面有一个jar包,然后把该jar包加入到本地仓库中:

    mvn install:install-file -Dfile=D:\software\Maven\ganymed-ssh2-build210\ganymed-ssh2-build210.jar -DgroupId=ch.ethz.ganymed -DartifactId=ganymed-ssh2 -Dversion=build210 -Dpackaging=jar

    然后在添加依赖就ojbk了。

    下面就是代码实现:

    代码实现: 

    1、实体类:

    public class RemoteConnect {
        private String ip;
        private String userName;
        private String password;
    //省略 set
    get
    |

     2、业务代码:

    import ch.ethz.ssh2.Connection;
    import ch.ethz.ssh2.SCPClient;
    import ch.ethz.ssh2.Session;
    import ch.ethz.ssh2.StreamGobbler;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import java.io.*;
    
    public class RemoteSSH {
    
        private static final Logger logger = LoggerFactory.getLogger(RemoteSSH.class);
        private static String DEFAULTCHARTSET = "UTF-8";
        private static Connection conn;
        /**
         * 远程登录linux 服务器
         *
         * @param remoteConnect
         * @return
         */
        public static boolean login(RemoteConnect remoteConnect) {
            boolean flag = false;
            try {
                conn = new Connection(remoteConnect.getIp());
                conn.connect();//连接
                flag = conn.authenticateWithPassword(remoteConnect.getUserName(), remoteConnect.getPassword());
                if (flag) {
                    logger.info("---认证成功-----");
                } else {
                    logger.error("------认证失败-----");
                    conn.close();
                }
    
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            return flag;
        }
    
        /**
         * @param remoteConnect
         * @param keyFile       一个文件对象指向一个文件,该文件包含OpenSSH密钥格式的用户的DSA或RSA私钥(PEM,不能丢失"
         *                      -----BEGIN DSA PRIVATE KEY-----" or "-----BEGIN RSA PRIVATE KEY-----"标签
         * @param keyfilePass   如果秘钥文件加密 需要用该参数解密,如果没有加密可以为null
         * @return Boolean
         * @throws
         * @Title: loginByKey
         * @Description: 秘钥方式  远程登录linux服务器
         */
        public static Boolean loginByFileKey(RemoteConnect remoteConnect, File keyFile, String keyfilePass) {
            boolean flag = false;
            // 输入密钥所在路径
            // File keyfile = new File("C:\\temp\\private");
            try {
                conn = new Connection(remoteConnect.getIp());
                conn.connect();
                // 登录认证
                flag = conn.authenticateWithPublicKey(remoteConnect.getUserName(), keyFile, keyfilePass);
                if (flag) {
                    logger.info("认证成功!");
                } else {
                    logger.info("认证失败!");
                    conn.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return flag;
        }
    
        /**
         * @param remoteConnect
         * @param keys          一个字符[],其中包含用户的DSA或RSA私钥(OpenSSH密匙格式,您不能丢失“
         *                      ----- begin DSA私钥-----”或“-----BEGIN RSA PRIVATE KEY-----“标签。char数组可以包含换行符/换行符。
         * @param keyPass       如果秘钥字符数组加密  需要用该字段解密  否则不需要可以为null
         * @return Boolean
         * @throws
         * @Title: loginByCharsKey
         * @Description: 秘钥方式  远程登录linux服务器
         */
        public static Boolean loginByCharsKey(RemoteConnect remoteConnect, char[] keys, String keyPass) {
    
            boolean flag = false;
            // 输入密钥所在路径
            // File keyfile = new File("C:\\temp\\private");
            try {
                conn = new Connection(remoteConnect.getIp());
                conn.connect();
                // 登录认证
                flag = conn.authenticateWithPublicKey(remoteConnect.getUserName(), keys, keyPass);
                if (flag) {
                    logger.info("认证成功!");
                } else {
                    logger.info("认证失败!");
                    conn.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return flag;
        }
    
        public static String execute(String cmd) {
            String result = "";
            try {
                Session session = conn.openSession();// 打开一个会话
                session.execCommand(cmd);// 执行命令;
                result = processStdout(session.getStdout(), DEFAULTCHARTSET);
                // 如果为得到标准输出为空,说明脚本执行出错了 StringUtils.isBlank(result)
                if (result.equals("")) {
                    result = processStdout(session.getStderr(), DEFAULTCHARTSET);
                }
    //            conn.close();
    //            session.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
    
        }
    
        /**
         * @param in      输入流对象
         * @param charset 编码
         * @return String 以纯文本的格式返回
         * @throws
         * @Title: processStdout
         * @Description: 解析脚本执行的返回结果
         */
        public static String processStdout(InputStream in, String charset) {
            InputStream stdout = new StreamGobbler(in);
            StringBuffer buffer = new StringBuffer();
            try {
                BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
                String line = null;
                while ((line = br.readLine()) != null) {
                    buffer.append(line + "\n");
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return buffer.toString();
        }
    
        /**
         * @param cmd 脚本或者命令
         * @return String 命令执行成功后返回的结果值,如果命令执行失败,返回空字符串,不是null
         * @throws
         * @Title: executeSuccess
         * @Description: 远程执行shell脚本或者命令
         */
        public static String executeSuccess(String cmd) {
            String result = "";
            try {
                Session session = conn.openSession();// 打开一个会话
                session.execCommand(cmd);// 执行命令
                result = processStdout(session.getStdout(), DEFAULTCHARTSET);
                conn.close();
                session.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }
    
        /**
         * @return String
         * @throws
         * @Title: ConnectLinux
         * @Description: 通过用户名和密码关联linux服务器
         */
        public static String connectLinux(String ip, String userName,
                                          String password, String commandStr) {
    
            logger.info("ConnectLinuxCommand  scpGet===" + "ip:" + ip + "  userName:" + userName + "  commandStr:"
                    + commandStr);
    
            String returnStr = "";
    //        boolean result = true;
    
            RemoteConnect remoteConnect = new RemoteConnect();
            remoteConnect.setIp(ip);
            remoteConnect.setUserName(userName);
            remoteConnect.setPassword(password);
            try {
                if (login(remoteConnect)) {
                    returnStr = execute(commandStr);
                    System.out.println(returnStr);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
    
    //        if (returnStr != null && !returnStr.equals("")) {
    //            result = false;
    //        }
            return returnStr;
        }
    
        /**
         * @param ip         (其他服务器)
         * @param userName   用户名(其他服务器)
         * @param password   密码(其他服务器)
         * @param remoteFile 文件位置(其他服务器)
         * @param localDir   本服务器目录
         * @return void
         * @throws IOException
         * @throws
         * @Title: scpGet
         * @Description: 从其他服务器获取文件到本服务器指定目录
         */
        public static void scpGet(String ip, String userName,
                                  String password, String remoteFile, String localDir)
                throws IOException {
    
            logger.info("ConnectLinuxCommand  scpGet===" + "ip:" + ip + "  userName:" + userName + "  remoteFile:"
                    + remoteFile + "  localDir:" + localDir);
            RemoteConnect remoteConnect = new RemoteConnect();
            remoteConnect.setIp(ip);
            remoteConnect.setUserName(userName);
            remoteConnect.setPassword(password);
    
            if (login(remoteConnect)) {
                SCPClient client = new SCPClient(conn);
                client.get(remoteFile, localDir);
                conn.close();
            }
        }
    
        /**
         * @param ip
         * @param userName
         * @param password
         * @param localFile
         * @param remoteDir
         * @return void
         * @throws IOException
         * @throws
         * @Title: scpPut
         * @Description: 将文件复制到其他计算机中
         */
        public static void scpPut(String ip, String userName,
                                  String password, String localFile, String remoteDir)
                throws IOException {
            logger.info("ConnectLinuxCommand  scpPut===" + "ip:" + ip + "  userName:" + userName + "  localFile:"
                    + localFile + "  remoteDir:" + remoteDir);
    
            RemoteConnect remoteConnect = new RemoteConnect();
            remoteConnect.setIp(ip);
            remoteConnect.setUserName(userName);
            remoteConnect.setPassword(password);
    
            if (login(remoteConnect)) {
                //检测指定路径下的jar是否存在
                SCPClient client = new SCPClient(conn);
                client.put(localFile, remoteDir);
                System.out.println("aa");
                conn.close();
            }
        }
    
        //重新打包上传启动功能
        public static String allDeploy(String ip, String userName,
                                       String password) {
            RemoteConnect connect = new RemoteConnect(ip, userName, password);
            if (login(connect)) {
                String commandLine = "ps -ef|grep dailybuild-|grep -v grep|wc -l";
                String execute = execute(commandLine);
                if (execute.equals("1\n")) {
                    String str = "ps -ef|grep dailybuild-|grep -v grep |awk '{print $2}' | xargs kill -9;";
                    String result = execute(str);
    //                String deleteStr = "cd /export;rm -rf dailybuild-0.0.1-SNAPSHOT.jar";
                    String deleteStr = "find / -name dailybuild-0.0.1-SNAPSHOT.jar | xargs rm -rf ";
                    execute(deleteStr);
                    SCPClient client = new SCPClient(conn);
                    try {
                        client.put("D:\\Project\\dailybuildV3_New\\target\\dailybuild-0.0.1-SNAPSHOT.jar", "/export");
                        logger.info("-----上传jar包成功----开始启动----");
                        execute("nohup java -jar /export/dailybuild-0.0.1-SNAPSHOT.jar > /export/dailybuild.log &");
                        String startLog = execute("tail -f /export/dailybuild.log");
                        if (startLog.contains("Started DailyBuildApplication"))
                            logger.info("-----完成启动----");
                        conn.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    String isExist = "find / -name dailybuild-0.0.1-SNAPSHOT.jar";
                    String result = execute(isExist);
                    if (result != "") execute("nohup java -jar " + result + ">/export/dailybuild.log &");
                }
            }
            return "完成";
        }
    
    }

    3、测试代码类:

    public class RemoteTest {
        private static String ip = "10.85.153.27";
        private static String userName = "root";
        private static String password = "#TESTzdh27";
    
        public static void main(String[] args) throws IOException {
    //        RemoteConnect connect = new RemoteConnect("10.85.153.27", "root", "#TESTzdh27");
    //        boolean login = RemoteSSH.login(connect);
    //        System.out.println(login);
    
    //        String commandStr = "smtpnum = 'lsof -i:8091 | wc -l';print $smtpnum";
    //        String result = RemoteSSH.connectLinux("10.85.153.27", "root", "#TESTzdh27", commandStr);
    //        System.out.println(result);
            //下载
    //        RemoteSSH.scpGet(ip, userName, password, "/home/shell/protect.sh", "D:\\java");
    //        RemoteSSH.scpPut(ip,userName,password,"D:\\Project\\dailybuildV3_New\\target\\dailybuild-0.0.1-SNAPSHOT.jar","/home/shell");
            RemoteSSH.allDeploy(ip, userName, password);
        }
    }

     结论:测试没得问题,这种方法呢其实跟我们用xshell直接去连接服务器是一样的,只不过速度相对快一点,java中代码也是跟在客户端敲的代码是一样的,初步目标实现了。

     

    展开全文
  • java实现ssh协议远程通过中间服务器连接跳转第三方服务器,目前只能连接到中间服务器 ,但是连接第三方服务器怎么实现 求解
  • SSH协议连接远程服务器的java实现

    热门讨论 2012-10-09 22:24:48
    SSH协议连接远程服务器的java实现,运行稳定,性能极佳
  • java通过ssh连接服务器执行shell命令详解及实例发布于 2020-5-24|复制链接摘记: java通过ssh连接服务器执行shell命令详解java通过ssh连接服务器执行shell命令:JSch 是SSH2的一个纯Java实现。它允许你连接到一个sshd...

    java通过ssh连接服务器执行shell命令详解及实例

    发布于 2020-5-24|

    复制链接

    摘记: java通过ssh连接服务器执行shell命令详解java通过ssh连接服务器执行shell命令:JSch 是SSH2的一个纯Java实现。它允许你连接到一个sshd 服务器,使用端口转发,X11转发,文件传输等等。你可以将它的功能集成到你自己的 程序中。同时该项目也提供 ..

    java通过ssh连接服务器执行shell命令详解java通过ssh连接服务器执行shell命令: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。示例程序

    ```java

    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 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();

    }

    /**

    * 执行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 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 stdout = shell.getStandardOutput();

    for (String str : stdout) {

    System.out.println(str);

    }

    }

    }

    ```

    MyUserInfo

    ```java

    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()");

    }

    }

    ```

    展开全文
  • jsch使用之Java实现ssh sftp协议传输

    万次阅读 2015-10-27 10:31:32
    JSch 是SSH2的一个纯Java实现。它允许你连接到一个sshd 服务器,使用端口转发,X11转发,文件传输等等。...JSCH是一个纯粹的用java实现SSH功能的java library. 官方地址为:http://www.jcraft.com/jsch/ GitHub 地

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

    JSCH是一个纯粹的用java实现SSH功能的java  library. 官方地址为:http://www.jcraft.com/jsch/

    GitHub 地址为:https://github.com/vngx/vngx-jsch

    mvn 配置如下:

    <dependency><groupId>com.jcraft</groupId><artifactId>jsch</artifactId><version>0.1.46</version></dependency>
    
    demo:

    package com.jiepu.jsch;
    /* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
    /**
     * This program will demonstrate the sftp protocol support.
     *   $ CLASSPATH=.:../build javac Sftp.java
     *   $ CLASSPATH=.:../build java Sftp
     * You will be asked username, host and passwd. 
     * If everything works fine, you will get a prompt 'sftp>'. 
     * 'help' command will show available command.
     * In current implementation, the destination path for 'get' and 'put'
     * commands must be a file, not a directory.
     *
     */
    import com.jcraft.jsch.*;
    import java.awt.*;
    import javax.swing.*;
    
    public class Sftp{
    	
    	//http://www.jcraft.com/jsch/examples/Sftp.java
      public static void main(String[] arg){
    
        try{
          JSch jsch=new JSch();
    
          String host=null;
          if(arg.length>0){
            host=arg[0];
          }
          else{
            host=JOptionPane.showInputDialog("Enter username@hostname",
                                             System.getProperty("user.name")+
                                             "@localhost"); 
          }
          String user=host.substring(0, host.indexOf('@'));
          host=host.substring(host.indexOf('@')+1);
          int port=22;
    
          Session session=jsch.getSession(user, host, port);
    
          // username and password will be given via UserInfo interface.
          UserInfo ui=new MyUserInfo();
          session.setUserInfo(ui);
    
          session.connect();
    
          Channel channel=session.openChannel("sftp");
          channel.connect();
          ChannelSftp c=(ChannelSftp)channel;
    
          java.io.InputStream in=System.in;
          java.io.PrintStream out=System.out;
    
          java.util.Vector cmds=new java.util.Vector();
          byte[] buf=new byte[1024];
          int i;
          String str;
          int level=0;
    
          while(true){
            out.print("sftp> ");
    	cmds.removeAllElements();
            i=in.read(buf, 0, 1024);
    	if(i<=0)break;
    
            i--;
            if(i>0 && buf[i-1]==0x0d)i--;
            //str=new String(buf, 0, i);
            //System.out.println("|"+str+"|");
    	int s=0;
    	for(int ii=0; ii<i; ii++){
              if(buf[ii]==' '){
                if(ii-s>0){ cmds.addElement(new String(buf, s, ii-s)); }
    	    while(ii<i){if(buf[ii]!=' ')break; ii++;}
    	    s=ii;
    	  }
    	}
    	if(s<i){ cmds.addElement(new String(buf, s, i-s)); }
    	if(cmds.size()==0)continue;
    
    	String cmd=(String)cmds.elementAt(0);
    	if(cmd.equals("quit")){
              c.quit();
    	  break;
    	}
    	if(cmd.equals("exit")){
              c.exit();
    	  break;
    	}
     	if(cmd.equals("rekey")){
     	  session.rekey();
     	  continue;
     	}
     	if(cmd.equals("compression")){
              if(cmds.size()<2){
    	    out.println("compression level: "+level);
                continue;
    	  }
    	  try{
    	    level=Integer.parseInt((String)cmds.elementAt(1));
    	    if(level==0){
    	      session.setConfig("compression.s2c", "none");
    	      session.setConfig("compression.c2s", "none");
    	    }
    	    else{
                  session.setConfig("compression.s2c", "zlib@openssh.com,zlib,none");
                  session.setConfig("compression.c2s", "zlib@openssh.com,zlib,none");
    	    }
    	  }
    	  catch(Exception e){}
              session.rekey();
     	  continue;
    	}
    	if(cmd.equals("cd") || cmd.equals("lcd")){
              if(cmds.size()<2) continue;
    	  String path=(String)cmds.elementAt(1);
    	  try{
    	    if(cmd.equals("cd")) c.cd(path);
    	    else c.lcd(path);
    	  }
    	  catch(SftpException e){
    	    System.out.println(e.toString());
    	  }
    	  continue;
    	}
    	if(cmd.equals("rm") || cmd.equals("rmdir") || cmd.equals("mkdir")){
              if(cmds.size()<2) continue;
    	  String path=(String)cmds.elementAt(1);
    	  try{
    	    if(cmd.equals("rm")) c.rm(path);
    	    else if(cmd.equals("rmdir")) c.rmdir(path);
    	    else c.mkdir(path);
    	  }
    	  catch(SftpException e){
    	    System.out.println(e.toString());
    	  }
    	  continue;
    	}
    	if(cmd.equals("chgrp") || cmd.equals("chown") || cmd.equals("chmod")){
              if(cmds.size()!=3) continue;
    	  String path=(String)cmds.elementAt(2);
    	  int foo=0;
    	  if(cmd.equals("chmod")){
                byte[] bar=((String)cmds.elementAt(1)).getBytes();
                int k;
                for(int j=0; j<bar.length; j++){
                  k=bar[j];
    	      if(k<'0'||k>'7'){foo=-1; break;}
      	      foo<<=3;
    	      foo|=(k-'0');
    	    }
    	    if(foo==-1)continue;
    	  }
    	  else{
      	    try{foo=Integer.parseInt((String)cmds.elementAt(1));}
    	    catch(Exception e){continue;}
    	  }
    	  try{
    	    if(cmd.equals("chgrp")){ c.chgrp(foo, path); }
    	    else if(cmd.equals("chown")){ c.chown(foo, path); }
    	    else if(cmd.equals("chmod")){ c.chmod(foo, path); }
    	  }
    	  catch(SftpException e){
    	    System.out.println(e.toString());
    	  }
    	  continue;
    	}
    	if(cmd.equals("pwd") || cmd.equals("lpwd")){
               str=(cmd.equals("pwd")?"Remote":"Local");
    	   str+=" working directory: ";
              if(cmd.equals("pwd")) str+=c.pwd();
    	  else str+=c.lpwd();
    	  out.println(str);
    	  continue;
    	}
    	if(cmd.equals("ls") || cmd.equals("dir")){
    	  String path=".";
    	  if(cmds.size()==2) path=(String)cmds.elementAt(1);
    	  try{
    	    java.util.Vector vv=c.ls(path);
    	    if(vv!=null){
    	      for(int ii=0; ii<vv.size(); ii++){
    //		out.println(vv.elementAt(ii).toString());
    
                    Object obj=vv.elementAt(ii);
                    if(obj instanceof com.jcraft.jsch.ChannelSftp.LsEntry){
                      out.println(((com.jcraft.jsch.ChannelSftp.LsEntry)obj).getLongname());
                    }
    
    	      }
    	    }
    	  }
    	  catch(SftpException e){
    	    System.out.println(e.toString());
    	  }
    	  continue;
    	}
    	if(cmd.equals("lls") || cmd.equals("ldir")){
    	  String path=".";
    	  if(cmds.size()==2) path=(String)cmds.elementAt(1);
    	  try{
    	    java.io.File file=new java.io.File(path);
    	    if(!file.exists()){
    	      out.println(path+": No such file or directory");
                  continue; 
                }
    	    if(file.isDirectory()){
    	      String[] list=file.list();
    	      for(int ii=0; ii<list.length; ii++){
    		out.println(list[ii]);
    	      }
    	      continue;
    	    }
    	    out.println(path);
    	  }
    	  catch(Exception e){
    	    System.out.println(e);
    	  }
    	  continue;
    	}
    	if(cmd.equals("get") || 
    	   cmd.equals("get-resume") || cmd.equals("get-append") || 
    	   cmd.equals("put") || 
    	   cmd.equals("put-resume") || cmd.equals("put-append")
    	   ){
    	  if(cmds.size()!=2 && cmds.size()!=3) continue;
    	  String p1=(String)cmds.elementAt(1);
    //	  String p2=p1;
    	  String p2=".";
    	  if(cmds.size()==3)p2=(String)cmds.elementAt(2);
    	  try{
    	    SftpProgressMonitor monitor=new MyProgressMonitor();
    	    if(cmd.startsWith("get")){
    	      int mode=ChannelSftp.OVERWRITE;
    	      if(cmd.equals("get-resume")){ mode=ChannelSftp.RESUME; }
    	      else if(cmd.equals("get-append")){ mode=ChannelSftp.APPEND; } 
    	      c.get(p1, p2, monitor, mode);
    	    }
    	    else{ 
    	      int mode=ChannelSftp.OVERWRITE;
    	      if(cmd.equals("put-resume")){ mode=ChannelSftp.RESUME; }
    	      else if(cmd.equals("put-append")){ mode=ChannelSftp.APPEND; } 
    	      c.put(p1, p2, monitor, mode); 
    	    }
    	  }
    	  catch(SftpException e){
    	    System.out.println(e.toString());
    	  }
    	  continue;
    	}
    	if(cmd.equals("ln") || cmd.equals("symlink") ||
               cmd.equals("rename") || cmd.equals("hardlink")){
              if(cmds.size()!=3) continue;
    	  String p1=(String)cmds.elementAt(1);
    	  String p2=(String)cmds.elementAt(2);
    	  try{
    	    if(cmd.equals("hardlink")){  c.hardlink(p1, p2); }
    	    else if(cmd.equals("rename")) c.rename(p1, p2);
    	    else c.symlink(p1, p2);
    	  }
    	  catch(SftpException e){
    	    System.out.println(e.toString());
    	  }
    	  continue;
    	}
    	if(cmd.equals("df")){
              if(cmds.size()>2) continue;
              String p1 = cmds.size()==1 ? ".": (String)cmds.elementAt(1);
              SftpStatVFS stat = c.statVFS(p1);
    
              long size = stat.getSize();
              long used = stat.getUsed();
              long avail = stat.getAvailForNonRoot();
              long root_avail = stat.getAvail();
              long capacity = stat.getCapacity();
    
              System.out.println("Size: "+size);
              System.out.println("Used: "+used);
              System.out.println("Avail: "+avail);
              System.out.println("(root): "+root_avail);
              System.out.println("%Capacity: "+capacity);
    
              continue;
            }
    	if(cmd.equals("stat") || cmd.equals("lstat")){
              if(cmds.size()!=2) continue;
    	  String p1=(String)cmds.elementAt(1);
    	  SftpATTRS attrs=null;
    	  try{
    	    if(cmd.equals("stat")) attrs=c.stat(p1);
    	    else attrs=c.lstat(p1);
    	  }
    	  catch(SftpException e){
    	    System.out.println(e.toString());
    	  }
    	  if(attrs!=null){
                out.println(attrs);
    	  }
    	  else{
    	  }
    	  continue;
    	}
    	if(cmd.equals("readlink")){
              if(cmds.size()!=2) continue;
    	  String p1=(String)cmds.elementAt(1);
    	  String filename=null;
    	  try{
    	    filename=c.readlink(p1);
                out.println(filename);
    	  }
    	  catch(SftpException e){
    	    System.out.println(e.toString());
    	  }
    	  continue;
    	}
    	if(cmd.equals("realpath")){
              if(cmds.size()!=2) continue;
    	  String p1=(String)cmds.elementAt(1);
    	  String filename=null;
    	  try{
    	    filename=c.realpath(p1);
                out.println(filename);
    	  }
    	  catch(SftpException e){
    	    System.out.println(e.toString());
    	  }
    	  continue;
    	}
    	if(cmd.equals("version")){
    	  out.println("SFTP protocol version "+c.version());
    	  continue;
    	}
    	if(cmd.equals("help") || cmd.equals("?")){
    	  out.println(help);
    	  continue;
    	}
            out.println("unimplemented command: "+cmd);
          }
          session.disconnect();
        }
        catch(Exception e){
          System.out.println(e);
        }
        System.exit(0);
      }
    
      public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{
        public String getPassword(){ return passwd; }
        public boolean promptYesNo(String str){
          Object[] options={ "yes", "no" };
          int foo=JOptionPane.showOptionDialog(null, 
                 str,
                 "Warning", 
                 JOptionPane.DEFAULT_OPTION, 
                 JOptionPane.WARNING_MESSAGE,
                 null, options, options[0]);
           return foo==0;
        }
      
        String passwd;
        JTextField passwordField=(JTextField)new JPasswordField(20);
    
        public String getPassphrase(){ return null; }
        public boolean promptPassphrase(String message){ return true; }
        public boolean promptPassword(String message){
          Object[] ob={passwordField}; 
          int result=
    	  JOptionPane.showConfirmDialog(null, ob, message,
    					JOptionPane.OK_CANCEL_OPTION);
          if(result==JOptionPane.OK_OPTION){
    	passwd=passwordField.getText();
    	return true;
          }
          else{ return false; }
        }
        public void showMessage(String message){
          JOptionPane.showMessageDialog(null, message);
        }
        final GridBagConstraints gbc = 
          new GridBagConstraints(0,0,1,1,1,1,
                                 GridBagConstraints.NORTHWEST,
                                 GridBagConstraints.NONE,
                                 new Insets(0,0,0,0),0,0);
        private Container panel;
        public String[] promptKeyboardInteractive(String destination,
                                                  String name,
                                                  String instruction,
                                                  String[] prompt,
                                                  boolean[] echo){
          panel = new JPanel();
          panel.setLayout(new GridBagLayout());
    
          gbc.weightx = 1.0;
          gbc.gridwidth = GridBagConstraints.REMAINDER;
          gbc.gridx = 0;
          panel.add(new JLabel(instruction), gbc);
          gbc.gridy++;
    
          gbc.gridwidth = GridBagConstraints.RELATIVE;
    
          JTextField[] texts=new JTextField[prompt.length];
          for(int i=0; i<prompt.length; i++){
            gbc.fill = GridBagConstraints.NONE;
            gbc.gridx = 0;
            gbc.weightx = 1;
            panel.add(new JLabel(prompt[i]),gbc);
    
            gbc.gridx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weighty = 1;
            if(echo[i]){
              texts[i]=new JTextField(20);
            }
            else{
              texts[i]=new JPasswordField(20);
            }
            panel.add(texts[i], gbc);
            gbc.gridy++;
          }
    
          if(JOptionPane.showConfirmDialog(null, panel, 
                                           destination+": "+name,
                                           JOptionPane.OK_CANCEL_OPTION,
                                           JOptionPane.QUESTION_MESSAGE)
             ==JOptionPane.OK_OPTION){
            String[] response=new String[prompt.length];
            for(int i=0; i<prompt.length; i++){
              response[i]=texts[i].getText();
            }
    	return response;
          }
          else{
            return null;  // cancel
          }
        }
      }
    
    /*
      public static class MyProgressMonitor implements com.jcraft.jsch.ProgressMonitor{
        JProgressBar progressBar;
        JFrame frame;
        long count=0;
        long max=0;
    
        public void init(String info, long max){
          this.max=max;
          if(frame==null){
            frame=new JFrame();
    	frame.setSize(200, 20);
            progressBar = new JProgressBar();
          }
          count=0;
    
          frame.setTitle(info);
          progressBar.setMaximum((int)max);
          progressBar.setMinimum((int)0);
          progressBar.setValue((int)count);
          progressBar.setStringPainted(true);
    
          JPanel p=new JPanel();
          p.add(progressBar);
          frame.getContentPane().add(progressBar);
          frame.setVisible(true);
          System.out.println("!info:"+info+", max="+max+" "+progressBar);
        }
        public void count(long count){
          this.count+=count;
          System.out.println("count: "+count);
          progressBar.setValue((int)this.count);
        }
        public void end(){
          System.out.println("end");
          progressBar.setValue((int)this.max);
          frame.setVisible(false);
        }
      }
    */
    
      public static class MyProgressMonitor implements SftpProgressMonitor{
        ProgressMonitor monitor;
        long count=0;
        long max=0;
        public void init(int op, String src, String dest, long max){
          this.max=max;
          monitor=new ProgressMonitor(null, 
                                      ((op==SftpProgressMonitor.PUT)? 
                                       "put" : "get")+": "+src, 
                                      "",  0, (int)max);
          count=0;
          percent=-1;
          monitor.setProgress((int)this.count);
          monitor.setMillisToDecideToPopup(1000);
        }
        private long percent=-1;
        public boolean count(long count){
          this.count+=count;
    
          if(percent>=this.count*100/max){ return true; }
          percent=this.count*100/max;
    
          monitor.setNote("Completed "+this.count+"("+percent+"%) out of "+max+".");     
          monitor.setProgress((int)this.count);
    
          return !(monitor.isCanceled());
        }
        public void end(){
          monitor.close();
        }
      }
    
      private static String help =
    "      Available commands:\n"+
    "      * means unimplemented command.\n"+
    "cd path                       Change remote directory to 'path'\n"+
    "lcd path                      Change local directory to 'path'\n"+
    "chgrp grp path                Change group of file 'path' to 'grp'\n"+
    "chmod mode path               Change permissions of file 'path' to 'mode'\n"+
    "chown own path                Change owner of file 'path' to 'own'\n"+
    "df [path]                     Display statistics for current directory or\n"+
    "                              filesystem containing 'path'\n"+
    "help                          Display this help text\n"+
    "get remote-path [local-path]  Download file\n"+
    "get-resume remote-path [local-path]  Resume to download file.\n"+
    "get-append remote-path [local-path]  Append remote file to local file\n"+
    "hardlink oldpath newpath      Hardlink remote file\n"+
    "*lls [ls-options [path]]      Display local directory listing\n"+
    "ln oldpath newpath            Symlink remote file\n"+
    "*lmkdir path                  Create local directory\n"+
    "lpwd                          Print local working directory\n"+
    "ls [path]                     Display remote directory listing\n"+
    "*lumask umask                 Set local umask to 'umask'\n"+
    "mkdir path                    Create remote directory\n"+
    "put local-path [remote-path]  Upload file\n"+
    "put-resume local-path [remote-path]  Resume to upload file\n"+
    "put-append local-path [remote-path]  Append local file to remote file.\n"+
    "pwd                           Display remote working directory\n"+
    "stat path                     Display info about path\n"+
    "exit                          Quit sftp\n"+
    "quit                          Quit sftp\n"+
    "rename oldpath newpath        Rename remote file\n"+
    "rmdir path                    Remove remote directory\n"+
    "rm path                       Delete remote file\n"+
    "symlink oldpath newpath       Symlink remote file\n"+
    "readlink path                 Check the target of a symbolic link\n"+
    "realpath path                 Canonicalize the path\n"+
    "rekey                         Key re-exchanging\n"+
    "compression level             Packet compression will be enabled\n"+
    "version                       Show SFTP version\n"+
    "?                             Synonym for help";
    }
    package com.jiepu.jsch;
    
    /* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
    /**
     * This program will demonstrate the file transfer from remote to local
     *   $ CLASSPATH=.:../build javac ScpFrom.java
     *   $ CLASSPATH=.:../build java ScpFrom user@remotehost:file1 file2
     * You will be asked passwd. 
     * If everything works fine, a file 'file1' on 'remotehost' will copied to
     * local 'file1'.
     *
     */
    import com.jcraft.jsch.*;
    import java.awt.*;
    import javax.swing.*;
    import java.io.*;
    
    public class ScpFrom {
    	
    	
    	//yunshouhu@192.168.1.140:/home/yunshouhu/info.dat info.dat
    	
    	// yunshouhu@192.168.1.140:/home/yunshouhu/elasticsearch/elasticsearch-1.7.1//NOTICE.txt info.txt
    
    	public static void main(String[] arg) {
    		if (arg.length != 2) {
    			System.err
    					.println("usage: java ScpFrom user@remotehost:file1 file2");
    			System.exit(-1);
    		}
    
    		FileOutputStream fos = null;
    		try {
    
    			String user = arg[0].substring(0, arg[0].indexOf('@'));
    			arg[0] = arg[0].substring(arg[0].indexOf('@') + 1);
    			String host = arg[0].substring(0, arg[0].indexOf(':'));
    			String rfile = arg[0].substring(arg[0].indexOf(':') + 1);
    			String lfile = arg[1];
    
    			String prefix = null;
    			if (new File(lfile).isDirectory()) {
    				prefix = lfile + File.separator;
    			}
    
    			JSch jsch = new JSch();
    			Session session = jsch.getSession(user, host, 22);
    
    			// username and password will be given via UserInfo interface.
    			UserInfo ui = new MyUserInfo();
    			session.setUserInfo(ui);
    			session.connect();
    
    			// exec 'scp -f rfile' remotely
    			String command = "scp -f " + rfile;
    			Channel channel = session.openChannel("exec");
    			((ChannelExec) channel).setCommand(command);
    
    			// get I/O streams for remote scp
    			OutputStream out = channel.getOutputStream();
    			InputStream in = channel.getInputStream();
    
    			channel.connect();
    
    			byte[] buf = new byte[1024];
    
    			// send '\0'
    			buf[0] = 0;
    			out.write(buf, 0, 1);
    			out.flush();
    
    			while (true) {
    				int c = checkAck(in);
    				if (c != 'C') {
    					break;
    				}
    
    				// read '0644 '
    				in.read(buf, 0, 5);
    
    				long filesize = 0L;
    				while (true) {
    					if (in.read(buf, 0, 1) < 0) {
    						// error
    						break;
    					}
    					if (buf[0] == ' ')
    						break;
    					filesize = filesize * 10L + (long) (buf[0] - '0');
    				}
    
    				String file = null;
    				for (int i = 0;; i++) {
    					in.read(buf, i, 1);
    					if (buf[i] == (byte) 0x0a) {
    						file = new String(buf, 0, i);
    						break;
    					}
    				}
    
    				// System.out.println("filesize="+filesize+", file="+file);
    
    				// send '\0'
    				buf[0] = 0;
    				out.write(buf, 0, 1);
    				out.flush();
    
    				// read a content of lfile
    				fos = new FileOutputStream(prefix == null ? lfile : prefix
    						+ file);
    				int foo;
    				while (true) {
    					if (buf.length < filesize)
    						foo = buf.length;
    					else
    						foo = (int) filesize;
    					foo = in.read(buf, 0, foo);
    					if (foo < 0) {
    						// error
    						break;
    					}
    					fos.write(buf, 0, foo);
    					filesize -= foo;
    					if (filesize == 0L)
    						break;
    				}
    				fos.close();
    				fos = null;
    
    				if (checkAck(in) != 0) {
    					System.exit(0);
    				}
    
    				// send '\0'
    				buf[0] = 0;
    				out.write(buf, 0, 1);
    				out.flush();
    			}
    
    			session.disconnect();
    
    			System.exit(0);
    		} catch (Exception e) {
    			System.out.println(e);
    			try {
    				if (fos != null)
    					fos.close();
    			} catch (Exception ee) {
    			}
    		}
    	}
    
    	static int checkAck(InputStream in) throws IOException {
    		int b = in.read();
    		// b may be 0 for success,
    		// 1 for error,
    		// 2 for fatal error,
    		// -1
    		if (b == 0)
    			return b;
    		if (b == -1)
    			return b;
    
    		if (b == 1 || b == 2) {
    			StringBuffer sb = new StringBuffer();
    			int c;
    			do {
    				c = in.read();
    				sb.append((char) c);
    			} while (c != '\n');
    			if (b == 1) { // error
    				System.out.print(sb.toString());
    			}
    			if (b == 2) { // fatal error
    				System.out.print(sb.toString());
    			}
    		}
    		return b;
    	}
    
    	public static class MyUserInfo implements UserInfo, UIKeyboardInteractive {
    		public String getPassword() {
    			return passwd;
    		}
    
    		public boolean promptYesNo(String str) {
    			Object[] options = { "yes", "no" };
    			int foo = JOptionPane.showOptionDialog(null, str, "Warning",
    					JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
    					null, options, options[0]);
    			return foo == 0;
    		}
    
    		String passwd;
    		JTextField passwordField = (JTextField) new JPasswordField(20);
    
    		public String getPassphrase() {
    			return null;
    		}
    
    		public boolean promptPassphrase(String message) {
    			return true;
    		}
    
    		public boolean promptPassword(String message) {
    			Object[] ob = { passwordField };
    			int result = JOptionPane.showConfirmDialog(null, ob, message,
    					JOptionPane.OK_CANCEL_OPTION);
    			if (result == JOptionPane.OK_OPTION) {
    				passwd = passwordField.getText();
    				return true;
    			} else {
    				return false;
    			}
    		}
    
    		public void showMessage(String message) {
    			JOptionPane.showMessageDialog(null, message);
    		}
    
    		final GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 1, 1,
    				GridBagConstraints.NORTHWEST, GridBagConstraints.NONE,
    				new Insets(0, 0, 0, 0), 0, 0);
    		private Container panel;
    
    		public String[] promptKeyboardInteractive(String destination,
    				String name, String instruction, String[] prompt, boolean[] echo) {
    			panel = new JPanel();
    			panel.setLayout(new GridBagLayout());
    
    			gbc.weightx = 1.0;
    			gbc.gridwidth = GridBagConstraints.REMAINDER;
    			gbc.gridx = 0;
    			panel.add(new JLabel(instruction), gbc);
    			gbc.gridy++;
    
    			gbc.gridwidth = GridBagConstraints.RELATIVE;
    
    			JTextField[] texts = new JTextField[prompt.length];
    			for (int i = 0; i < prompt.length; i++) {
    				gbc.fill = GridBagConstraints.NONE;
    				gbc.gridx = 0;
    				gbc.weightx = 1;
    				panel.add(new JLabel(prompt[i]), gbc);
    
    				gbc.gridx = 1;
    				gbc.fill = GridBagConstraints.HORIZONTAL;
    				gbc.weighty = 1;
    				if (echo[i]) {
    					texts[i] = new JTextField(20);
    				} else {
    					texts[i] = new JPasswordField(20);
    				}
    				panel.add(texts[i], gbc);
    				gbc.gridy++;
    			}
    
    			if (JOptionPane.showConfirmDialog(null, panel, destination + ": "
    					+ name, JOptionPane.OK_CANCEL_OPTION,
    					JOptionPane.QUESTION_MESSAGE) == JOptionPane.OK_OPTION) {
    				String[] response = new String[prompt.length];
    				for (int i = 0; i < prompt.length; i++) {
    					response[i] = texts[i].getText();
    				}
    				return response;
    			} else {
    				return null; // cancel
    			}
    		}
    	}
    }
    package com.jiepu.jsch;
    
    /* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
    /**
     * This program will demonstrate how to use "aes128-cbc".
     *
     */
    import com.jcraft.jsch.*;
    
    import java.awt.*;
    
    import javax.swing.*;
    //http://www.jcraft.com/jsch/examples/AES.java
    public class AES{
    	
      public static void main(String[] arg){
    
        try{
          JSch jsch=new JSch();
    
          //jsch.setKnownHosts("/home/foo/.ssh/known_hosts");
    
          String host=null;
          if(arg.length>0){
            host=arg[0];
          }
          else{
            host=JOptionPane.showInputDialog("Enter username@hostname",
                                             System.getProperty("user.name")+
                                             "@localhost"); 
          }
          String user=host.substring(0, host.indexOf('@'));
          host=host.substring(host.indexOf('@')+1);
    
          Session session=jsch.getSession(user, host, 22);
          //session.setPassword("your password");
     
          // username and password will be given via UserInfo interface.
          UserInfo ui=new MyUserInfo("yunshouhu");
          session.setUserInfo(ui);
    
          session.setConfig("cipher.s2c", "aes128-cbc,3des-cbc,blowfish-cbc");
          session.setConfig("cipher.c2s", "aes128-cbc,3des-cbc,blowfish-cbc");
          session.setConfig("CheckCiphers", "aes128-cbc");
    
          session.connect();
    
          Channel channel=session.openChannel("shell");
    
          channel.setInputStream(System.in);
          channel.setOutputStream(System.out);
    
          channel.connect();
        }
        catch(Exception e){
          System.out.println(e);
        }
      }
    
      public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{
    	  
    	 
        public MyUserInfo(String passwd) {
    		super();
    		this.passwd = passwd;
    	}
    	public String getPassword(){ return passwd; }
        public boolean promptYesNo(String str){
         
           return true;
        }
      
        String passwd;
    
        public String getPassphrase(){ return null; }
        public boolean promptPassphrase(String message){ return true; }
        public boolean promptPassword(String message){
          
        	return true;
        }
        public void showMessage(String message){
          JOptionPane.showMessageDialog(null, message);
        }
    
        public String[] promptKeyboardInteractive(String destination,
                                                  String name,
                                                  String instruction,
                                                  String[] prompt,
                                                  boolean[] echo){
    
    
    	return prompt;
      
        }
      }
    }
    

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    	<modelVersion>4.0.0</modelVersion>
    
    	<groupId>com.jiepu</groupId>
    	<artifactId>jsch</artifactId>
    	<version>0.0.1-SNAPSHOT</version>
    	<packaging>jar</packaging>
    
    	<name>jsch</name>
    	<url>http://maven.apache.org</url>
    
    	<properties>
    		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    	</properties>
    
    	<dependencies>
    		<dependency>
    			<groupId>junit</groupId>
    			<artifactId>junit</artifactId>
    			<version>3.8.1</version>
    			<scope>test</scope>
    		</dependency>
    		<dependency>
    			<groupId>com.jcraft</groupId>
    			<artifactId>jsch</artifactId>
    			<version>0.1.53</version>
    		</dependency>
    	</dependencies>
    
    
    	<build>
    
    		<plugins>
    			<plugin>
    				<groupId>org.apache.maven.plugins</groupId>
    				<artifactId>maven-compiler-plugin</artifactId>
    				<configuration>
    					<source>1.7</source>
    					<target>1.7</target>
    				</configuration>
    			</plugin>
    
    		</plugins>
    	</build>
    </project>
    

    源码工程下载:







    展开全文
  • Java通过SSH2协议执行远程Shell脚本(ganymed-ssh2-build210.jar)ganymed-ssh2简介:Ganymed SSH-2 for Java是用纯Java实现SSH-2协议的一个包。在使用它的过程中非常容易,只需要指定合法的用户名口令,或者授权认证...

    Java通过SSH2协议执行远程Shell脚本(ganymed-ssh2-build210.jar)

    ganymed-ssh2简介:

    Ganymed SSH-2 for Java是用纯Java实现SSH-2协议的一个包。在使用它的过程中非常容易,只需要指定合法的用户名口令,

    或者授权认证文件,就可以创建到远程Linux主机的连接,在建立起来的会话中调用该Linux主机上的脚本文件,执行相关操作。

    使用方法:

    将 ganymed-ssh2-build210.jar 加入到项目的lib中。

    简单示例:

    假定我在192.168.0.114的Linux系统的/home/lldu目录下放了一个文件夹test,test文件夹对应测试Java类的包名test,我们在该机器上运用javac ./test/Main.java编译后,再通过调用下面的代码完成远程调用:

    import ch.ethz.ssh2.Connection;

    import ch.ethz.ssh2.ConnectionInfo;

    import ch.ethz.ssh2.Session;

    /**

    *

    * @author lldu

    */

    public class Main {

    public static void main(String[] args) {

    try {

    Connection con = new Connection("192.168.0.114");

    ConnectionInfo info = con.connect();

    boolean result = con.authenticateWithPassword("lldu", "123456");

    Session session = con.openSession();

    session.execCommand("java test.Main");

    } catch (Exception ex) {

    System.out.println(ex.getLocalizedMessage());

    }

    }

    }

    总结使用步骤:

    1.首先构造一个连接器,传入一个需要登陆的ip地址

    Connection conn = new Connection(ipAddr);

    conn.connect(); // 连接

    2.模拟登陆目的服务器 传入用户名和密码 ,

    boolean isAuthenticated = conn.authenticateWithPassword(username, password);它会返回一个布尔值,true 代表成功登陆目的服务器,否则登陆失败

    3.打开一个session,有点象Hibernate的session ,执行你需要的linux 脚本命令 。

    Session sess = conn.openSession();

    sess.execCommand("last");

    4.接收目标服务器上的控制台返回结果,读取br中的内容

    InputStream stdout = new StreamGobbler(sess.getStdout());

    BufferedReader br = new BufferedReader(new InputStreamReader(stdout));

    5.得到脚本运行成功与否的标志 :0-成功 非0-失败

    System.out.println("ExitCode: " + sess.getExitStatus());

    6.关闭session和connection

    sess.close();

    conn.close();

    需要说明的是:

    1.通过第2步认证成功后,当前目录就位于/home/username/目录之下,你可以指定脚本文件所在的绝对路径,或者通过cd导航到脚本文件所在的目录,然后传递执行脚本所需要的参数,完成脚本调用执行。

    2.执行脚本以后,可以获取脚本执行的结果文本,需要对这些文本进行正确编码后返回给客户端,避免乱码产生。

    3.如果你需要执行多个linux控制台脚本,比如第一个脚本的返回结果是第二个脚本的入参,你必须打开多个Session,也就是多次调用

    Session sess = conn.openSession();,使用完毕记得关闭就可以了

    =================================================================================================

    摘录部分源码如下:

    import java.io.BufferedReader;

    import java.io.IOException;

    import java.io.InputStream;

    import java.io.InputStreamReader;

    import org.apache.log4j.Logger;

    import ch.ethz.ssh2.Connection;

    import ch.ethz.ssh2.SCPClient;

    import ch.ethz.ssh2.Session;

    import ch.ethz.ssh2.StreamGobbler;

    public class CommandRunner {

    private static final Logger logger = Logger.getLogger(CommandRunner.class);

    //从其他网络计算机中拿去文件

    public static void scpGet(String host, String username, String password,

    String remoteFile, String localDir) throws IOException {

    if (logger.isDebugEnabled()) {

    logger.debug("spc [" + remoteFile + "] from " + host + " to "

    + localDir);

    }

    Connection conn = getOpenedConnection(host, username, password);

    SCPClient client = new SCPClient(conn);

    client.get(remoteFile, localDir);

    conn.close();

    }

    //将文件拷贝到其他计算机上

    public static void scpPut(String host, String username, String password,

    String localFile, String remoteDir) throws IOException {

    if (logger.isDebugEnabled()) {

    logger.debug("spc [" + localFile + "] to " + host + remoteDir);

    }

    Connection conn = getOpenedConnection(host, username, password);

    SCPClient client = new SCPClient(conn);

    client.put(localFile, remoteDir);

    conn.close();

    }

    //执行SSH命令.

    public static int runSSH(String host, String username, String password,

    String cmd) throws IOException {

    if (logger.isDebugEnabled()) {

    logger.debug("running SSH cmd [" + cmd + "]");

    }

    Connection conn = getOpenedConnection(host, username, password);

    Session sess = conn.openSession();

    sess.execCommand(cmd);

    InputStream stdout = new StreamGobbler(sess.getStdout());

    BufferedReader br = new BufferedReader(new InputStreamReader(stdout));

    while (true) {

    String line = br.readLine();

    if (line == null)

    break;

    if (logger.isDebugEnabled()) {

    logger.debug(line);

    }

    }

    sess.close();

    conn.close();

    return sess.getExitStatus().intValue();

    }

    //获得连接

    private static Connection getOpenedConnection(String host, String username,

    String password) throws IOException {

    if (logger.isDebugEnabled()) {

    logger.debug("connecting to " + host + " with user " + username

    + " and pwd " + password);

    }

    Connection conn = new Connection(host);

    conn.connect(); // make sure the connection is opened

    boolean isAuthenticated = conn.authenticateWithPassword(username,

    password);

    if (isAuthenticated == false)

    throw new IOException("Authentication failed.");

    return conn;

    }

    //执行本地的cmd命令.(DOS命令)

    public static int runLocal(String cmd) throws IOException {

    if (logger.isDebugEnabled()) {

    logger.debug("running local cmd [" + cmd + "]");

    }

    Runtime rt = Runtime.getRuntime();

    Process p = rt.exec(cmd);

    InputStream stdout = new StreamGobbler(p.getInputStream());

    BufferedReader br = new BufferedReader(new InputStreamReader(stdout));

    while (true) {

    String line = br.readLine();

    if (line == null)

    break;

    if (logger.isDebugEnabled()) {

    logger.debug(line);

    }

    }

    return p.exitValue();

    }

    }

    转:http://blog.csdn.net/anljf/article/details/6653404

    展开全文
  • 通过JCraft的JSch的依赖包(jsch-0.1.42.jar下载)实现SSH2协议远程通信,如远程连接到linux服务器进行文件上传下载或数据同步,具体代码示例如下所示importjava.io.File;@b@importjava.io.FileInputStream;@b@import...
  • maverick组件实现JAVA SSH协议初探

    千次阅读 2012-03-16 21:23:00
    最近研究用SSH协议访问远程Linux机器,采用最普通的用户帐号和口令连接方式,端口为默认的22,以及需要执行的shell命令。我google了下用java 实现的SSH实现方式,找到了一款商业软件J2SSH Maverick(看网站介绍,该...
  • 一、前言上一篇中我们已经知道了客户端通过socket来连接服务端,进行了一次数据传输,那如何实现客户端多次发生数据?而服务端接受多个客户端呢?二、发送中文信息在python3中,socket只能发送bytes类型的数据,...
  • 本文将主要讨论使用Java中的jsch与sftp服务器实现ssh免密连接。一、什么是SFTP?SFTP是一个安全文件传送协议,可以为传输文件提供一种安全的加密方法。SFTP 为 SSH的一部份,是一种传输文件到服务器的安全方式。SFTP...
  • java通过ssh连接服务器执行shell命令详解java通过ssh连接服务器执行shell命令:JSch 是SSH2的一个纯Java实现。它允许你连接到一个sshd 服务器,使用端口转发,X11转发,文件传输等等。你可以将它的功能集成到你自己...
  • java通过ssh连接服务器执行shell命令详解java通过ssh连接服务器执行shell命令:JSch 是SSH2的一个纯Java实现。它允许你连接到一个sshd 服务器,使用端口转发,X11转发,文件传输等等。你可以将它的功能集成到你自己...
  • 业务背景:公司想要实现Java代码中操作Linux命令,在页面上点击按钮,选择几个参数就可以操作集群,并且记录日志 想要实现这个功能有几个点需要关注 一.Java代码怎么连接远程的服务器? 大家可能都有一个想法,把...
  • java telnet ssh 实现

    2014-03-05 09:43:25
    java telnet ssh 实现 2011-05-1113:17 911人阅读 评论(1) 收藏 举报  先看看telnet 和ssh的定义:  Telnet协议是TCP/IP协议中的一员,是Internet远程登陆服务的标准协议和主要方式。它为用户提供...
  • JAVA实现与Linux通信(通过SSH协议)

    千次阅读 2011-12-29 18:04:55
    然后要解决SSH连接问题. 在OpenSource项目里找到了Ganymed SSH-2 for Java .下载后有例子,但是没有找到有关交互命令的例子.所以自己探索了一下 在网上看有老外讨论用这个如何改密码,基本上的问题都是因为找不到...
  • 先看看telnet 和ssh的定义:Telnet协议是TCP/IP协议中的一员,是Internet远程登陆服务的标准协议和主要方式。它为用户提供了在本地计算机上完成远程主机工作的能力。在终端使用者的电脑上使用telnet程序,用它连接到...
  • 使用java代码使用sftp和ssh协议实现一台Linux服务器远程操作多台 踩的坑 需求说明 在一台Linux服务器(作为主服务器)上部署java代码,实现一台对多台(子)服务器的交互,完成文件传输和命令的操作(如 查询、进程...
  • Ganymed SSH-2 for Java是用纯Java实现SSH-2协议的一个包。在使用它的过程中非常容易,只需要指定合法的用户名口令, 或者授权认证文件,就可以创建到远程Linux主机的连接,在建立起来的会话中调
  • Ganymed SSH-2 for Java 是什么Ganymed SSH-2 for Java是用纯Java实现SSH-2协议的一个包。可以利用它直接在Java程序中连接SSH服务器。官网地址为 http://www.ganymed.ethz.ch/ssh2/ 可以看到最后的更新日志为2006年...
  • java 领域中, 开源jar 包ganymed-ssh2 对ssh2协议进行了实现, 通过ganymed-ssh2 可实现Linux命令: ssh 和 scp 的功能. ganymed-ssh2 提供了多种认证方式, 可通过用户名密码, 秘钥等方式. 笔者常用的是用户名密码方式...
  • 需求要求每天定时从服务器获取文件解析,使用FTP连接时报错 ...原因是FTPClient不支持通过协议SSH2进行SFTP连接,解决办法是使用com.jcraft.jsch.JSch提供的SSH连接 添加maven依赖: <dependency> <
  • ganymed-ssh2 远程连接java实例代码

    热门讨论 2011-10-22 15:45:02
    Ganymed SSH-2 for Java是用纯Java实现SSH-2协议的一个包。可以利用它直接在Java程序中连接SSH服务器。Ganymed SSH-2支持SSH对话(远程命令执行和shell访问),本地和远程端口转发,本地数据流转发,X11转发和SCP。这些...
  • 本文将主要讨论使用Java中的jsch与sftp服务器实现ssh免密连接。一、什么是SFTP?SFTP是一个安全文件传送协议,可以为传输文件提供一种安全的加密方法。SFTP 为 SSH的一部份,是一种传输文件到服务器的安全方式。SFTP...
  • ganymed-ssh2简介Ganymed SSH-2 for Java是用纯Java实现SSH-2协议的一个包。可以利用它直接在Java程序中连接SSH服务器。使用方法将 ganymed-ssh2-build210.jar 加入到项目的lib中即可举例说明获取linux服务器上某个...
  • JSch是一个SSH2的纯Java实现。它允许你连接到一个SSH服务器,并且可以使用端口转发,X11转发,文件传输等,当然你也可以集成它的功能到你自己的应用程序。本文只介绍如何使用JSch实现的SFTP功能。SFTP是Secure File ...
  • 用于Java的Ganymed SSH-2是一个在纯Java实现SSH-2协议的库,允许用户从Java程序内连接到SSH服务器。 它支持SSH会话,本地和远程端口转发以及本地流转发。 此内部版本更新代码,使其与JDK 6中Thread.interrupt...
  • Ganymed SSH-2 for Java是用纯Java实现SSH-2协议的一个包。可以利用它直接在Java程序中连接SSH服务器。Ganymed SSH-2支持SSH对话(远程命令执行和shell访问),本地和远程端口转发,本地数据流转发,X11转发和SCP。这些...

空空如也

空空如也

1 2 3 4 5 ... 9
收藏数 165
精华内容 66
关键字:

java实现ssh协议连接

java 订阅