ch.ethz.ssh2.Session Java Examples

The following examples show how to use ch.ethz.ssh2.Session. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SshUtil.java    From dk-fitting with Apache License 2.0 6 votes vote down vote up
public static String exe(String cmd, String hostIp, String hostName,
                             String hostPassword) throws Exception {
        Connection conn = createConn(hostIp, hostName, hostPassword);
        Session sess = conn.openSession();
        sess.requestPTY("vt100", 80, 24, 640, 480, null);
        sess.execCommand(cmd);
        InputStream stdout = new StreamGobbler(sess.getStdout());
        StringBuilder sb = new StringBuilder();
        BufferedReader stdoutReader = new BufferedReader(
                new InputStreamReader(stdout));

        System.out.println("Here is the output from stdout:");
        while (true) {
            String line = stdoutReader.readLine();
            if (line == null)
                break;
            System.out.println(line);
            sb.append(line + "\n");
        }

//      System.out.println("ExitCode: " + sess.getExitStatus());
//		System.out.println("sb.toString() = " + sb.toString());
        sess.close();
        conn.close();
        return sb.toString();
    }
 
Example #2
Source File: RemoteShellTool.java    From Transwarp-Sample-Code with MIT License 6 votes vote down vote up
public String exec(String cmds) {
    InputStream in = null;
    String result = "";
    try {
        if (this.login()) {
            Session session = conn.openSession();
            session.execCommand(cmds);
            in = session.getStdout();
            result = this.processStdout(in, this.charset);
            session.close();
            conn.close();
        }
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    return result;
}
 
Example #3
Source File: SUTTest.java    From bestconf with Apache License 2.0 6 votes vote down vote up
@Override
public void startTest(){
	Session session=null;
	try {
		getConnection();
		if(connection==null)
			throw new IOException("Unable to connect the server!");
	    session = connection.openSession();
		session.execCommand(shellofstartTest);
		System.out.println("Here is some information about the remote host:");
		InputStream stderr = new StreamGobbler(session.getStderr());
		BufferedReader br = new BufferedReader(new InputStreamReader(stderr));
		InputStream stdout = new StreamGobbler(session.getStdout());
		BufferedReader stdbr = new BufferedReader(new InputStreamReader(stdout));
		System.out.println("Test had been started successfully!");
	} catch (IOException e) {
		e.printStackTrace();
		System.exit(-1);
	}finally{
		if(session != null)
    		   session.close();
    	   closeConnection();
	}
}
 
Example #4
Source File: SSH2Util.java    From redis-manager with Apache License 2.0 6 votes vote down vote up
/**
 * 执行Shell脚本或命令
 *
 * @param machine
 * @param commands
 * @return
 */
public static String execute(Machine machine, String commands) throws Exception {
    String result;
    Connection connection = null;
    try {
        connection = getConnection(machine);
        // 打开一个会话
        Session session = connection.openSession();
        session.execCommand(commands);
        InputStream in = session.getStdout();
        result = processStandardOutput(in);
        InputStream errorIn = session.getStderr();
        result += processStandardOutput(errorIn);
    } finally {
        close(connection);
    }
    return result;
}
 
Example #5
Source File: MyScpClient.java    From jstorm with Apache License 2.0 5 votes vote down vote up
/**
     * Download a set of files from the remote server to a local directory.
     *
     * @param remoteFiles          Paths and names of the remote files.
     * @param localTargetDirectory Local directory to put the downloaded files.
     * @throws IOException
     */
    public void get(String remoteFiles[], String localTargetDirectory) throws IOException {
        Session sess = null;

        if ((remoteFiles == null) || (localTargetDirectory == null))
            throw new IllegalArgumentException("Null argument.");

        if (remoteFiles.length == 0)
            return;

//        String cmd = "scp -f -r";
        String cmd = "scp -f ";

        for (int i = 0; i < remoteFiles.length; i++) {
            if (remoteFiles[i] == null)
                throw new IllegalArgumentException("Cannot accept null filename.");

            cmd += (" " + remoteFiles[i]);
        }

        try {
            sess = conn.openSession();
            sess.execCommand(cmd);
            receiveFiles(sess, remoteFiles, localTargetDirectory);
            sess.close();
        } catch (IOException e) {
            if (sess != null)
                sess.close();

            throw (IOException) new IOException("Error during SCP transfer.").initCause(e);
        }
    }
 
Example #6
Source File: EthzHolder.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T execWaitForComplete(String host, String user, char[] pemPrivateKey, String password, String command,
		ProcessFunction<Session, T> processor, long timeoutMs) throws Exception {
	return doExecCommand(host, user, pemPrivateKey, password,command, session -> {
		// Wait for completed by condition.
		session.waitForCondition((CLOSED), timeoutMs);
		return processor.process(session);
	});
}
 
Example #7
Source File: SSHExecutor.java    From zkdoctor with Apache License 2.0 5 votes vote down vote up
/**
 * 执行命令
 */
public Result executeCommand(String cmd, LineProcessor lineProcessor, int timeoutMillis) {
    Session session = null;
    try {
        session = conn.openSession();
        return executeCommand(session, cmd, timeoutMillis, lineProcessor);
    } catch (Exception e) {
        LOGGER.error("SSH ip:{}, cmd:{}.", conn.getHostname(), cmd, e);
        return new Result(e);
    } finally {
        close(session);
    }
}
 
Example #8
Source File: SSHExecutor.java    From PoseidonX with Apache License 2.0 5 votes vote down vote up
/**
 * 执行命令并返回结果,可以执行多次
 *
 * @param cmd           命令
 * @param lineProcessor 回调处理行
 * @return 如果lineProcessor不为null, 那么永远返回Result.true
 */
public Result executeCommand(String cmd, LineProcessor lineProcessor, int timeoutMillis) {
    Session session = null;
    try {
        session = conn.openSession();
        return executeCommand(session, cmd, timeoutMillis, lineProcessor);
    } catch (Exception e) {
        LOGGER.error("execute ip:" + conn.getHostname() + " cmd:" + cmd, e);
        return new Result(e);
    } finally {
        close(session);
    }
}
 
Example #9
Source File: SSHExecutor.java    From PoseidonX with Apache License 2.0 5 votes vote down vote up
/**
 * 关闭session
 *
 * @param session session
 */
private static void close(Session session) {
    if (session != null) {
        try {
            session.close();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }
}
 
Example #10
Source File: MyScpClient.java    From jstorm with Apache License 2.0 5 votes vote down vote up
/**
 * Copy a set of local files to a remote directory, uses the specified mode
 * when creating the files on the remote side.
 *
 * @param localFiles            Paths and names of the local files.
 * @param remoteTargetDirectory Remote target directory.
 * @param mode                  a four digit string (e.g., 0644, see "man chmod", "man open")
 * @throws IOException
 */
public void put(String[] localFiles, String remoteTargetDirectory, String mode) throws IOException {
    Session sess = null;

    if ((localFiles == null) || (remoteTargetDirectory == null) || (mode == null))
        throw new IllegalArgumentException("Null argument.");

    if (mode.length() != 4)
        throw new IllegalArgumentException("Invalid mode.");

    for (int i = 0; i < mode.length(); i++)
        if (Character.isDigit(mode.charAt(i)) == false)
            throw new IllegalArgumentException("Invalid mode.");

    if (localFiles.length == 0)
        return;

    String cmd = "scp -t -d " + remoteTargetDirectory;

    for (int i = 0; i < localFiles.length; i++) {
        if (localFiles[i] == null)
            throw new IllegalArgumentException("Cannot accept null filename.");
    }

    try {
        sess = conn.openSession();
        sess.execCommand(cmd);
        sendFiles(sess, localFiles, mode);
        sess.close();
    } catch (IOException e) {
        if (sess != null)
            sess.close();
        throw (IOException) new IOException("Error during SCP transfer.").initCause(e);
    }
}
 
Example #11
Source File: SshUtil.java    From dk-fitting with Apache License 2.0 5 votes vote down vote up
public static String getHomePath(String cmd, String hostIp, String hostName,
                                     String hostPassword, String hadoopName) throws Exception {
        Connection conn = createConn(hostIp, hostName, hostPassword);
        Session sess = conn.openSession();
        sess.requestPTY("vt100", 80, 24, 640, 480, null);
        sess.execCommand(cmd);
        InputStream stdout = new StreamGobbler(sess.getStdout());
        StringBuilder sb = new StringBuilder();
        BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stdout));

//		System.out.println("Here is the output from stdout:");
        String hadoopNamePath = "";
        while (true) {
            String line = stdoutReader.readLine();
//			System.out.println( trim);
            if (line != null && line.trim().startsWith("export " + hadoopName)) {
                String substring = line.substring(line.lastIndexOf("=") + 1);
                hadoopNamePath = substring;
            }
            if (line == null)
                break;
        }

        //System.out.println("ExitCode: " + sess.getExitStatus());
//		System.out.println("sb.toString() = " + sb.toString());
        sess.close();
        conn.close();
        return hadoopNamePath;
    }
 
Example #12
Source File: MyScpClient.java    From jstorm with Apache License 2.0 5 votes vote down vote up
/**
 * Create a remote file and copy the contents of the passed byte array into it.
 * The method use the specified mode when creating the file on the remote side.
 *
 * @param data                  the data to be copied into the remote file.
 * @param remoteFileName        The name of the file which will be created in the remote target directory.
 * @param remoteTargetDirectory Remote target directory.
 * @param mode                  a four digit string (e.g., 0644, see "man chmod", "man open")
 * @throws IOException
 */
public void put(byte[] data, String remoteFileName, String remoteTargetDirectory, String mode) throws IOException {
    Session sess = null;

    if ((remoteFileName == null) || (remoteTargetDirectory == null) || (mode == null))
        throw new IllegalArgumentException("Null argument.");

    if (mode.length() != 4)
        throw new IllegalArgumentException("Invalid mode.");

    for (int i = 0; i < mode.length(); i++)
        if (Character.isDigit(mode.charAt(i)) == false)
            throw new IllegalArgumentException("Invalid mode.");

    String cmd = "scp -t -d " + remoteTargetDirectory;

    try {
        sess = conn.openSession();
        sess.execCommand(cmd);
        sendBytes(sess, data, remoteFileName, mode);
        sess.close();
    } catch (IOException e) {
        if (sess != null)
            sess.close();
        throw (IOException) new IOException("Error during SCP transfer.").initCause(e);
    }
}
 
Example #13
Source File: SSHExecutor.java    From zkdoctor with Apache License 2.0 5 votes vote down vote up
/**
 * 关闭session
 *
 * @param session session
 */
private static void close(Session session) {
    if (session != null) {
        try {
            session.close();
        } catch (Exception e) {
            LOGGER.error("Close session failed.", e);
        }
    }
}
 
Example #14
Source File: SSHTemplate.java    From javabase with Apache License 2.0 5 votes vote down vote up
private static void close(Session session) {
	if (session != null) {
        try {
        	session.close();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}
 
Example #15
Source File: SSHTemplate.java    From javabase with Apache License 2.0 5 votes vote down vote up
/**
 	 * 执行命令并返回结果,可以执行多次
 	 * @param cmd
 	 * @param lineProcessor 回调处理行
 	 * @return 如果lineProcessor不为null,那么永远返回Result.true
 	 */
 	public Result executeCommand(String cmd, LineProcessor lineProcessor, int timoutMillis) {
 		Session session = null;
 		try {
 			session = conn.openSession();
 			return executeCommand(session, cmd, timoutMillis, lineProcessor);
} catch (Exception e) {
	logger.error("execute ip:"+conn.getHostname()+" cmd:"+cmd, e);
	return new Result(e);
} finally {
	close(session);
}
 	}
 
Example #16
Source File: SSHTemplate.java    From cachecloud with Apache License 2.0 5 votes vote down vote up
private static void close(Session session) {
	if (session != null) {
        try {
        	session.close();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}
 
Example #17
Source File: SSHTemplate.java    From cachecloud with Apache License 2.0 5 votes vote down vote up
/**
 	 * 执行命令并返回结果,可以执行多次
 	 * @param cmd
 	 * @param lineProcessor 回调处理行
 	 * @return 如果lineProcessor不为null,那么永远返回Result.true
 	 */
 	public Result executeCommand(String cmd, LineProcessor lineProcessor, int timoutMillis) {
 		Session session = null;
 		try {
 			session = conn.openSession();
 			return executeCommand(session, cmd, timoutMillis, lineProcessor);
} catch (Exception e) {
	logger.error("execute ip:"+conn.getHostname()+" cmd:"+cmd, e);
	return new Result(e);
} finally {
	close(session);
}
 	}
 
Example #18
Source File: Tools.java    From fastdfs-zyc with GNU General Public License v2.0 5 votes vote down vote up
public static List<String> exeRemoteConsole(String hostname, String username, String password, String cmd) {
        List<String> result = new ArrayList<String>();
        //指明连接主机的IP地址
        Connection conn = new Connection(hostname);
        Session ssh = null;
        try {
            //连接到主机
            conn.connect();
            //使用用户名和密码校验
            boolean isconn = conn.authenticateWithPassword(username, password);
            if (!isconn) {
                logger.error("用户名称或者是密码不正确");
            } else {
                logger.info("已经连接OK");
                ssh = conn.openSession();
                //使用多个命令用分号隔开
//              ssh.execCommand("pwd;cd /tmp;mkdir shb;ls;ps -ef|grep weblogic");
                ssh.execCommand(cmd);
                //只允许使用一行命令,即ssh对象只能使用一次execCommand这个方法,多次使用则会出现异常
//              ssh.execCommand("mkdir hb");
                //将屏幕上的文字全部打印出来
                InputStream is = new StreamGobbler(ssh.getStdout());
                BufferedReader brs = new BufferedReader(new InputStreamReader(is));
                for (String line = brs.readLine(); line != null; line = brs.readLine()) {
                    result.add(line);
                }
            }
            //连接的Session和Connection对象都需要关闭
            if (ssh != null) {
                ssh.close();
            }
            conn.close();
        } catch (IOException e) {
            logger.error("", e);
        }
        return result;
    }
 
Example #19
Source File: PooledRemoteCommandExecutor.java    From wecube-platform with Apache License 2.0 4 votes vote down vote up
private Session getSession() {
    return sshSession;
}
 
Example #20
Source File: MyScpClient.java    From jstorm with Apache License 2.0 4 votes vote down vote up
private void sendBytes(Session sess, byte[] data, String fileName, String mode) throws IOException {
    OutputStream os = sess.getStdin();
    InputStream is = new BufferedInputStream(sess.getStdout(), 512);

    readResponse(is);

    String cline = "C" + mode + " " + data.length + " " + fileName + "\n";

    os.write(cline.getBytes());
    os.flush();

    readResponse(is);

    os.write(data, 0, data.length);
    os.write(0);
    os.flush();

    readResponse(is);

    os.write("E\n".getBytes());
    os.flush();
}
 
Example #21
Source File: CtrCommond.java    From myrover with Apache License 2.0 4 votes vote down vote up
/**
 * 远程执行命令
 * @param ip
 * @param user
 * @param pwd
 * @param cmd
 * @return
 */
public static String doCommond(Connection conn,String cmd){
	String result = "";
       try {
           if(conn==null){
           	System.out.println("请先链接服务器");
           }else{
               Session sess = conn.openSession();
               sess.execCommand(cmd);
               InputStream stdout = new StreamGobbler(sess.getStdout());
   			BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stdout));
   			while(true){
   				String line = stdoutReader.readLine();
   				if (line == null)
   					break;
   				result+=line+StaticKeys.SPLIT_BR;
   			}
   			//连接的Session和Connection对象都需要关闭 
   			stdoutReader.close();
               sess.close();
           }
       } catch (IOException e) {
       	System.out.println("执行linux命令错误:"+e.toString());
       }
       if(result.endsWith(StaticKeys.SPLIT_BR)){
       	result =  result.substring(0, result.length()-StaticKeys.SPLIT_BR.length());
       }
       
       if(!StringUtils.isEmpty(result)){
       	if(cmd.contains("DEV")||cmd.contains("iostat")){
       		if(result.contains("</br></br>")){
       			result = result.substring(result.lastIndexOf("</br></br>")+10);
       		}
           }
       	if(cmd.contains("mpstat")){
       		if(result.contains("</br></br>")){
       			result = result.substring(result.lastIndexOf("</br></br>")+10);
       			int s = result.indexOf("</br>")+5;
       			s = result.indexOf("</br>",s);
       			result = result.substring(0,s);
       		}
           }
       }
       return result;
}
 
Example #22
Source File: MysqlUtil.java    From newblog with Apache License 2.0 4 votes vote down vote up
/**
     * export database;
     */
    public void exportDataBase() {
        logger.info("start backup database");
        String username = Config.getProperty("jdbc.username_dev");
        String password = Config.getProperty("jdbc.password_dev");
        String database = Config.getProperty("jdbc.database");
        String host = Config.getProperty("jdbc.host_dev");
        String os = System.getProperty("os.name");
        String file_path = null;
//        if (os.toLowerCase().startsWith("win")) {       //根据系统类型
//            file_path = System.getProperty("user.dir") + "\\sql\\";
//        } else {
//            file_path = System.getProperty("user.dir") + "/sql/";//保存的路径
//        }
        file_path = System.getProperty("myblog.path") + "sql";
        String file_name = "/myblog" + DateTime.now().toString("yyyyMMddHHmmss") + ".sql";
        String file = file_path + file_name;
        logger.info("file_path and file_name: " + file);
        //server
        String s_host = Config.getProperty("server.host");
        Integer s_port = Config.getIntProperty("server.port");
        String s_username = Config.getProperty("server.username");
        String s_password = Config.getProperty("server.password");
        try {
            StringBuffer sb = new StringBuffer();
            sb.append(Common.MYSQL_DUMP).append(" -u ").append(username).append(" -p").append(password).append(" -h ").append(host).append(" ").append(database).append(" >").append(file);
            String sql = sb.toString();
            logger.info(sql);
            //connect to server
            Connection connection = new Connection(s_host, s_port);
            connection.connect();
            boolean isAuth = connection.authenticateWithPassword(s_username, s_password);
            if (!isAuth) {
                logger.error("server login error");
            }
            Session session = connection.openSession();
            session.execCommand(sql);
            InputStream stdout = new StreamGobbler(session.getStdout());
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
            while (true) {
                String line = br.readLine();
                if (line == null)
                    break;
                System.out.println(line);
            }
            session.close();
            connection.close();
            stdout.close();
            br.close();
            logger.info("backup finish");
            logger.info(sb.toString());
        } catch (Exception e) {
            logger.error("error", e);
        }
    }
 
Example #23
Source File: RemoteDestroableProcess.java    From super-cloudops with Apache License 2.0 4 votes vote down vote up
public RemoteDestroableProcess(String processId, DestroableCommand command, Session session) {
	super(processId, command);
	notNull(session, "Command remote process session can't null.");
	this.session = session;
}