ch.ethz.ssh2.Connection Java Examples

The following examples show how to use ch.ethz.ssh2.Connection. 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: ScpService.java    From wecube-platform with Apache License 2.0 7 votes vote down vote up
public void getFile(String ip, Integer port, String user, String password, String privateKey, boolean usePassword, String remoteFile, String path) {
    Connection connection = new Connection(ip, port);
    try {
        connection.connect();
        boolean isAuthed = isAuth(ip, port, user, password, privateKey, usePassword);
        if (isAuthed) {
            System.out.println("Authentication is successful!");
            SCPClient scpClient = connection.createSCPClient();
            scpClient.get(remoteFile, path);
        } else {
            System.out.println("Authentication failed!");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        connection.close();
    }
}
 
Example #2
Source File: HostUtils.java    From myrover with Apache License 2.0 6 votes vote down vote up
/**
 * 获取进程使用状态
 * @param conn
 * @param pid 进程ID
 * @return
 */
public static ProcessState getProcessState(Connection conn,String pid){
	String processStr = CtrCommond.doCommond(conn, LinuxCmd.dd.replace("{pid}", pid));
	processStr =  conProcessStr(processStr,pid);
	String[] appStateStr = null;
	if(!StringUtils.isEmpty(processStr)){
		appStateStr = processStr.split(StaticKeys.SPLIT_KG);
		if(appStateStr.length>1){
			ProcessState processState = new ProcessState();
			processState.setCpuPer(appStateStr[0]);
			processState.setMemPer(appStateStr[1]);
			return processState;
		}
	}
	return null;
}
 
Example #3
Source File: ScpService.java    From wecube-platform with Apache License 2.0 6 votes vote down vote up
public void put(String ip, Integer port, String user, String password, String localFile, String remoteTargetDirectory) {
    Connection conn = new Connection(ip, port);
    try {
        conn.connect();
        boolean isconn = conn.authenticateWithPassword(user, password);
        if (isconn) {
            log.info("Connection is OK");
            SCPClient scpClient = conn.createSCPClient();
            log.info("scp local file [{}] to remote target directory [{}]", localFile, remoteTargetDirectory);
            scpClient.put(localFile, remoteTargetDirectory, "7777");
        } else {
            log.info("User or password incorrect");
            throw new WecubeCoreException("User or password incorrect");
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new WecubeCoreException("Run 'scp' command meet error: " + e.getMessage());
    } finally {
        conn.close();
    }
}
 
Example #4
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 #5
Source File: ScpService.java    From wecube-platform with Apache License 2.0 6 votes vote down vote up
public void putFile(String ip, Integer port, String user, String password, String privateKey, boolean usePassword, String localFile, String remoteTargetDirectory) {
    log.info("Start to connect {}:{}", ip, port);
    Connection connection = new Connection(ip, port);
    try {
        connection.connect();
        boolean isAuthed = isAuth(ip, port, user, password, privateKey, usePassword);
        if (isAuthed) {
            SCPClient scpClient = connection.createSCPClient();
            scpClient.put(localFile, remoteTargetDirectory);
        } else {
            System.out.println("Authentication failed!");
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        connection.close();
    }
}
 
Example #6
Source File: SSHUtil.java    From EserKnife with Apache License 2.0 6 votes vote down vote up
/**
 * 将
 *
 * @param ip
 * @param port
 * @param username
 * @param password
 * @param localPath
 * @param remoteDir
 * @return
 */
public static boolean scpFileToRemote(String ip, int port, String username, String password, String localPath, String remoteDir) throws SSHException {
    boolean isSuccess = true;
    Connection connection = new Connection(ip, port);
    try {
        connection.connect();
        boolean isAuthed = connection.authenticateWithPassword(username, password);
        if (!isAuthed) {
            throw new SSHException("auth error.");
        }
        SCPClient scpClient = connection.createSCPClient();
        scpClient.put(localPath, remoteDir, "0644");
    } catch (IOException e) {
        isSuccess = false;
        throw new SSHException("scp file to remote error.", e);
    } finally {
        if (connection != null) {
            connection.close();
        }
    }
    return isSuccess;
}
 
Example #7
Source File: ScpClientUtil.java    From eladmin with Apache License 2.0 6 votes vote down vote up
public void getFile(String remoteFile, String localTargetDirectory) {
	Connection conn = new Connection(ip, port);
	try {
		conn.connect();
		boolean isAuthenticated = conn.authenticateWithPassword(username, password);
		if (!isAuthenticated) {
			System.err.println("authentication failed");
		}
		SCPClient client = new SCPClient(conn);
		client.get(remoteFile, localTargetDirectory);
	} catch (IOException ex) {
		Logger.getLogger(SCPClient.class.getName()).log(Level.SEVERE, null, ex);
	}finally{
		conn.close();
	}
}
 
Example #8
Source File: ScpClientUtil.java    From eladmin with Apache License 2.0 6 votes vote down vote up
public void putFile(String localFile, String remoteFileName, String remoteTargetDirectory, String mode) {
	Connection conn = new Connection(ip, port);
	try {
		conn.connect();
		boolean isAuthenticated = conn.authenticateWithPassword(username, password);
		if (!isAuthenticated) {
			System.err.println("authentication failed");
		}
		SCPClient client = new SCPClient(conn);
		if ((mode == null) || (mode.length() == 0)) {
			mode = "0600";
		}
		if (remoteFileName == null) {
			client.put(localFile, remoteTargetDirectory);
		} else {
			client.put(localFile, remoteFileName, remoteTargetDirectory, mode);
		}
	} catch (IOException ex) {
		Logger.getLogger(ScpClientUtil.class.getName()).log(Level.SEVERE, null, ex);
	}finally{
		conn.close();
	}
}
 
Example #9
Source File: EthzHolder.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
/**
 * create ssh2 connection.
 * 
 * @param host
 * @param user
 * @param pemPrivateKey
 * @return
 * @throws IOException
 */
private final Connection createSsh2Connection(String host, String user, char[] pemPrivateKey,String password) throws IOException {
	hasText(host, "SSH2 command host can't empty.");
	hasText(user, "SSH2 command user can't empty.");
	//notNull(pemPrivateKey, "SSH2 command pemPrivateKey must not be null.");
	isTrueOf(!Collections2.isEmptyArray(pemPrivateKey) || StringUtils.isNotBlank(password), "pemPrivateKey");

	Connection conn = new Connection(host);
	conn.connect();


	if(!Collections2.isEmptyArray(pemPrivateKey)){
		// Authentication with pub-key.
		isTrue(conn.authenticateWithPublicKey(user, pemPrivateKey, null),
				String.format("Failed to SSH2 authenticate with %s@%s privateKey(%s)", user, host, new String(pemPrivateKey)));
	}else {
		isTrue(conn.authenticateWithPassword(user, password),
				String.format("Failed to SSH2 authenticate with %s@%s password(%s)", user, host, password));
	}

	log.debug("SSH2 connected to {}@{}", user, host);
	return conn;
}
 
Example #10
Source File: SUTTest.java    From bestconf with Apache License 2.0 6 votes vote down vote up
public Connection getConnection(){
	int round = 0;
   	while(round<maxRoundConnection){
   		try{
   			connection = new Connection(server);
   			connection.connect();
   			boolean isAuthenticated = connection.authenticateWithPassword(username, password);
   			if (isAuthenticated == false) {
   				throw new IOException("Authentication failed...");
   			}
   			break;
   		}catch (Exception e) {
   			e.printStackTrace();
   			connection.close();
   			connection = null;
   			System.err.println("================= connection is null in round "+round);
   			try {
				Thread.sleep(sshReconnectWatingtime*1000);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
   		}
   		round++;
   	}
	return connection;
}
 
Example #11
Source File: SUTSystemOperation.java    From bestconf with Apache License 2.0 6 votes vote down vote up
public Connection getConnection(){
   	int round = 0;
   	while(round<maxRoundConnection){
   		try{
   			connection = new Connection(server);
   			connection.connect();
   			boolean isAuthenticated = connection.authenticateWithPassword(username, password);
   			if (isAuthenticated == false) {
   				throw new IOException("Authentication failed...");
   			}
   			break;
   		}catch (Exception e) {
   			e.printStackTrace();
   			connection.close();
   			connection = null;
   			System.err.println("================= connection is null in round "+round);
   			try {
				Thread.sleep(sshReconnectWatingtime*1000);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
   		}
   		round++;
   	}
	return connection;
}
 
Example #12
Source File: CtrCommond.java    From myrover with Apache License 2.0 6 votes vote down vote up
/**
 * 获取服务器链接
 * @param hostname
 * @param username
 * @param password
 * @return
 */
public static Connection getConn(String hostName,String userName,int sshPort,String passWord){
       try {
       	Connection conn = new Connection(hostName,sshPort);
   		//连接到主机
		conn.connect();
		//使用用户名和密码校验
        boolean isconn = conn.authenticateWithPassword(userName, passWord);
        if(!isconn){
        	System.out.println("用户名称或者是密码不正确");
        }else{
        	return conn;
        }
	} catch (IOException e) {
		System.out.println("获取服务器链接出现异常:"+e.toString());
		return null;
	}
       return null;
}
 
Example #13
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 #14
Source File: SSHTemplate.java    From cachecloud with Apache License 2.0 6 votes vote down vote up
/**
 * 获取连接并校验
 * @param ip
 * @param port
 * @param username
 * @param password
 * @return Connection
 * @throws Exception
 */
private Connection getConnection(String ip, int port, 
		String username, String password) throws Exception {
	Connection conn = new Connection(ip, port);
    conn.connect(null, CONNCET_TIMEOUT, CONNCET_TIMEOUT);
    boolean isAuthenticated = false;
    if (ConstUtils.SSH_AUTH_TYPE == SshAuthTypeEnum.PASSWORD.getValue()) {
    	isAuthenticated = conn.authenticateWithPassword(username, password);
    } else if (ConstUtils.SSH_AUTH_TYPE == SshAuthTypeEnum.PUBLIC_KEY.getValue()) {
    	isAuthenticated = conn.authenticateWithPublicKey(username, new File(ConstUtils.PUBLIC_KEY_PEM), password);
    } 
    if (isAuthenticated == false) {
    	if (ConstUtils.SSH_AUTH_TYPE == SshAuthTypeEnum.PASSWORD.getValue()) {
    		throw new Exception("SSH authentication failed with [ userName: " + 
            		username + ", password: " + password + "]");
        } else if (ConstUtils.SSH_AUTH_TYPE == SshAuthTypeEnum.PUBLIC_KEY.getValue()) {
        	throw new Exception("SSH authentication failed with [ userName: " + 
            		username + ", pemfile: " + ConstUtils.PUBLIC_KEY_PEM + "]");
        }
        
    }
    return conn;
}
 
Example #15
Source File: SSH2Util.java    From util with Apache License 2.0 6 votes vote down vote up
/**
 * 功能:登录
 * @author 朱志杰 QQ:862990787
 * Sep 2, 2013 9:41:45 AM
 * @param hostname ssh2的hostname
 * @param port 端口 SSH2的默认端口是22
 * @param userName 用户名
 * @param pwd 密码
 * @throws IOException 
 */
public boolean login(String hostname,int port,String userName,String pwd) throws IOException{
	/* Create a connection instance */
	conn = new Connection(hostname,port);
	/* Now connect */
	conn.connect();
	/* Authenticate.
	 * If you get an IOException saying something like
	 * "Authentication method password not supported by the server at this stage."
	 * then please check the FAQ.
	 */
	boolean isAuthenticated = conn.authenticateWithPassword(userName, pwd);
	//sftp
	sftp=new SFTPv3Client(conn);
	return isAuthenticated;
}
 
Example #16
Source File: Test.java    From myrover with Apache License 2.0 6 votes vote down vote up
/**
 * @param args
 */
public static void main(String[] args) {
	// TODO Auto-generated method stub
	Connection conn = CtrCommond.getConn("192.168.1.1", "root", 22, "123456");
	System.out.println("CPU型号信息:"+HostUtils.getCpuModel(conn));
	System.out.println("物理CPU个数:"+HostUtils.getCpuNum(conn));
	System.out.println("每个CPU核数量:"+HostUtils.getCpuPerCores(conn));
	System.out.println("系统运行天数:"+HostUtils.getSystemDays(conn));
	System.out.println("系统版本信息:"+HostUtils.getSystemRelease(conn));
	System.out.println("系统版本详细信息:"+HostUtils.getSystemUname(conn));
	System.out.println("cpu Idle使用率:"+HostUtils.getCpuState(conn).getIdle());
	System.out.println("磁盘已使用G:"+HostUtils.getDfInfo(conn).getUsed());
	System.out.println("磁盘IO状态:"+HostUtils.getDiskIoState(conn).getRkBS());
	System.out.println("内存已使用百分比:"+HostUtils.getMemState(conn).getUsePer());
	System.out.println("网络吞吐率rxbyt:"+HostUtils.getNetIoState(conn).getRxbyt());
	System.out.println("系统一分钟负载:"+HostUtils.getSysLoadState(conn).getOneLoad());
	System.out.println("系统TCP active:"+HostUtils.getTcpState(conn).getActive());
	//System.out.println("进程2696内存使用率:"+HostUtils.getProcessState(conn, "2696").getMemPer());
	System.out.println("系统已加载内核模块:"+HostUtils.getLsmodInfo(conn));
	System.out.println("系统密码文件修改时间:"+HostUtils.getPasswdFileInfo(conn));
	System.out.println("系统rpc服务开放状态:"+HostUtils.getRpcinfo(conn));
	System.out.println("当前系统任务计划:"+HostUtils.getCrontab(conn));
}
 
Example #17
Source File: SSHExecutor.java    From zkdoctor with Apache License 2.0 5 votes vote down vote up
/**
 * 获取ssh连接
 *
 * @param ip       目标服务器ip
 * @param port     目标服务器port
 * @param username 用户名
 * @param password 密码
 * @throws Exception
 */
private Connection getConnection(String ip, int port,
                                 String username, String password) throws Exception {
    Connection conn = new Connection(ip, port);
    conn.connect(null, CONNCET_TIMEOUT, CONNCET_TIMEOUT);
    boolean isAuthenticated = conn.authenticateWithPassword(username, password);
    if (!isAuthenticated) {
        throw new Exception("Get connection failed because SSH authentication failed, username:" + username + ", passsword:" + password);
    }
    return conn;
}
 
Example #18
Source File: SSHExecutor.java    From zkdoctor with Apache License 2.0 5 votes vote down vote up
/**
 * 执行命令
 *
 * @param ip       目标服务器ip
 * @param port     目标服务器port
 * @param username 用户名
 * @param password 密码
 * @param callback 回调接口
 * @throws SSHException
 */
public Result execute(String ip, int port, String username, String password,
                      SSHCallback callback) throws SSHException {
    Connection conn = null;
    try {
        conn = getConnection(ip, port, username, password);
        return callback.call(new SSHSession(conn, HostAndPort.parseString(ip, port)));
    } catch (Exception e) {
        throw new SSHException("SSH error: " + e.getMessage(), e);
    } finally {
        close(conn);
    }
}
 
Example #19
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 #20
Source File: SshUtil.java    From dk-fitting with Apache License 2.0 5 votes vote down vote up
public static String scp(String hostIp, String hostName,
                         String hostPassword, String localFile, String remotePath) throws Exception {
    Connection conn = createConn(hostIp, hostName, hostPassword);

    SCPClient scpClient = new SCPClient(conn);
    scpClient.put(localFile, remotePath, "0777");
    return "upLoad success";
}
 
Example #21
Source File: PooledRemoteCommandExecutor.java    From wecube-platform with Apache License 2.0 5 votes vote down vote up
protected void buildConnection() throws IOException {
    Connection conn = new Connection(getConfig().getRemoteHost(), getConfig().getPort());
    conn.connect();
    boolean isAuthenticated = conn.authenticateWithPassword(getConfig().getUser(), getConfig().getPsword());
    if (!isAuthenticated) {
        if (conn != null) {
            conn.close();
        }

        throw new IOException("authentication failed");
    }

    this.sshConn = conn;
}
 
Example #22
Source File: SSHTemplate.java    From cachecloud with Apache License 2.0 5 votes vote down vote up
/**
* 通过回调执行命令
* @param ip
* @param port
* @param username
* @param password
* @param callback 可以使用Session执行多个命令
* @throws SSHException 
*/
  public Result execute(String ip, int port, String username, String password, 
  		SSHCallback callback) throws SSHException{
      Connection conn = null;
      try {
          conn = getConnection(ip, port, username, password);
          return callback.call(new SSHSession(conn, ip+":"+port));
      } catch (Exception e) {
          throw new SSHException("SSH err: " + e.getMessage(), e);
      } finally {
      	close(conn);
      }
  }
 
Example #23
Source File: SSHUtil.java    From xnx3 with Apache License 2.0 5 votes vote down vote up
/**
   * 登陆
   * @return boolean
   * @throws IOException
   */
  public boolean open(){ 
      conn = new Connection(ip); 
      try {
	conn.connect();
	return conn.authenticateWithPassword(this.username, this.password); 
} catch (IOException e) {
	e.printStackTrace();
}
      return false;
  }
 
Example #24
Source File: HostUtils.java    From myrover with Apache License 2.0 5 votes vote down vote up
/**
 * 获取每个CPU核数量
 * @param conn
 * @return
 */
public static String getCpuPerCores(Connection conn){
	String str =  CtrCommond.doCommond(conn, LinuxCmd.WULI_CPU_CORE_NUM);
	if(!StringUtils.isEmpty(str)){
		return str.substring(str.length()-1);
	}
	return "";
}
 
Example #25
Source File: SSHTemplate.java    From javabase with Apache License 2.0 5 votes vote down vote up
private void close(Connection conn) {
	if (conn != null) {
        try {
        	conn.close();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}
 
Example #26
Source File: SSHTemplate.java    From javabase with Apache License 2.0 5 votes vote down vote up
/**
 * 获取连接并校验
 * @param ip
 * @param port
 * @param username
 * @param password
 * @return Connection
 * @throws Exception
 */
private Connection getConnection(String ip, int port,
					 String username, String password) throws Exception {
	Connection conn = new Connection(ip, port);
    conn.connect(null, CONNCET_TIMEOUT, CONNCET_TIMEOUT);
    boolean isAuthenticated = conn.authenticateWithPassword(username, password);
    if (isAuthenticated == false) {
        throw new Exception("SSH authentication failed with [ userName: " +
        		username + ", password: " + password + "]");
    }
    return conn;
}
 
Example #27
Source File: HostUtils.java    From myrover with Apache License 2.0 5 votes vote down vote up
/**
 * 获取CPU型号信息
 * @param conn
 * @return
 */
public static String getCpuModel(Connection conn){
	String result =  CtrCommond.doCommond(conn, LinuxCmd.CPU_XINGHAO);
	if(!StringUtils.isEmpty(result)){
		return result.trim();
	}else{
		return "";
	}
}
 
Example #28
Source File: SSHTemplate.java    From javabase with Apache License 2.0 5 votes vote down vote up
/**
* 通过回调执行命令
* @param ip
* @param port
* @param username
* @param password
* @param callback 可以使用Session执行多个命令
* @throws SSHException 
*/
  public Result execute(String ip, int port, String username, String password,
				  SSHCallback callback) throws SSHException{
      Connection conn = null;
      try {
          conn = getConnection(ip, port, username, password);
          return callback.call(new SSHSession(conn, ip+":"+port));
      } catch (Exception e) {
          throw new SSHException("SSH err: " + e.getMessage(), e);
      } finally {
      	close(conn);
      }
  }
 
Example #29
Source File: ScpService.java    From wecube-platform with Apache License 2.0 5 votes vote down vote up
public boolean isAuthedWithPublicKey(String ip, Integer port, String user, File privateKey, String password) {
    Connection connection = new Connection(ip, port);
    try {
        return connection.authenticateWithPublicKey(user, privateKey, password);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}
 
Example #30
Source File: SshUtil.java    From dk-fitting with Apache License 2.0 5 votes vote down vote up
static Connection createConn(String hostIp, String hostName,
                             String hostPassword) throws Exception {
    Connection conn = new Connection(hostIp);
    conn.connect();
    boolean isAuthenticated = conn.authenticateWithPassword(hostName, hostPassword);

    if (isAuthenticated == false)
        throw new IOException("Authentication failed.");
    return conn;
}