com.sshtools.j2ssh.SshClient Java Examples

The following examples show how to use com.sshtools.j2ssh.SshClient. 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 qaf with MIT License 6 votes vote down vote up
/**
 * connect to host
 * 
 * @return
 * @throws Exception
 */
private static SshClient connectSsh() throws Exception {
	SshClient ssh = new SshClient();

	HostKeyVerification host = new IgnoreHostKeyVerification();
	String hostStr = getBundle().getString("ssh.host");
	ssh.connect(hostStr, host);
	PasswordAuthenticationClient auth = new PasswordAuthenticationClient();
	auth.setUsername(getBundle().getString("ssh.user"));
	auth.setPassword(getBundle().getString("ssh.pwd"));
	int result = ssh.authenticate(auth);

	System.out.println("Status " + result);
	if ((result == AuthenticationProtocolState.CANCELLED) || (result == AuthenticationProtocolState.FAILED)) {
		throw new Exception("Authentication Error.");
	}
	return ssh;
}
 
Example #2
Source File: SshDatabaseWrapper.java    From ApprovalTests.Java with Apache License 2.0 6 votes vote down vote up
public synchronized Connection makeConnection(String database, DatabaseConfiguration originalConfiguration)
{
  int port = counter++;
  DatabaseConfiguration config = new DatabaseConfiguration(originalConfiguration.getDataSourceName(), originalConfiguration.getDriver(), originalConfiguration.getProtocol(), "localhost", "" + port, database, originalConfiguration.getUserName(), originalConfiguration.getPassword(), originalConfiguration.getType());
  try
  {
      LogFactory.getFactory().setAttribute("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog");
      SshClient ssh = new SshClient();
      ssh.setSocketTimeout(60000);
      ssh.connect(originalConfiguration.getServer(), new IgnoreHostKeyVerification());
      PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();
      pwd.setUsername(originalConfiguration.getUserName());
      pwd.setPassword(originalConfiguration.getPassword());
      ssh.authenticate(pwd);
      ForwardingClient client = ssh.getForwardingClient();
      client.addLocalForwarding(config.getProtocol(), "0.0.0.0", config.getPort(), "localhost", originalConfiguration.getPort());
      client.startLocalForwarding(config.getProtocol());
      return new SshConnection(ssh, config.makeConnection());
  }
  catch (IOException ie)
  {
    throw ObjectUtils.throwAsError(ie);
  }
}
 
Example #3
Source File: SshUtil.java    From qaf with MIT License 5 votes vote down vote up
public static String executeCommand(String command) throws Exception {
	SessionChannelClient session = null;
	String res = "";
	try {
		SshClient ssh = connectSsh();
		// String command = getBundle().getString("ssh.cmd");

		session = ssh.openSessionChannel();
		OutputStream out = new java.io.ByteArrayOutputStream();

		session = ssh.openSessionChannel();
		IOStreamConnector output = new IOStreamConnector();
		output.connect(session.getInputStream(), out);

		if (session.executeCommand(command)) {
			session.getState().waitForState(ChannelState.CHANNEL_CLOSED, 15000);
			res = out.toString();
		} else {
			res = "Unable to execute command " + command;
		}
	} finally {
		try {
			session.close();
		} catch (Exception e) {
		}
	}
	return res;
}
 
Example #4
Source File: SSHUtils.java    From stevia with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Connect. This action simulates all the actions required for a SSH connection
 *
 * @param host  the hostname of the host you want to connect to
 * @param port the port of the host you want to connect to
 * @param username the username required for authentication
 * @param password the password required for authentication
 * @return the ssh client you connected to
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static SshClient connect(String host, int port,String username,String password) throws IOException {
	SSH_LOG.info("Connecting to " + host);
	SshClient ssh = new SshClient();
	ssh.connect(host, port, new IgnoreHostKeyVerification());
	PasswordAuthenticationClient passwordAuthenticationClient = new PasswordAuthenticationClient();
	passwordAuthenticationClient.setUsername(username);
	passwordAuthenticationClient.setPassword(password);
	int result = ssh.authenticate(passwordAuthenticationClient);
	if (result != AuthenticationProtocolState.COMPLETE) {
		throw new IOException("Login to " + host + ":" + port + " "+ username + "/" + password + " failed");
	}
	SSH_LOG.info("Connected " + host);
	return ssh;
}
 
Example #5
Source File: SSHUtils.java    From stevia with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Execute commands.
 *
 * @param host the host name of the server
 * @param port the port number the user want to use for connection
 * @param username the username required for authentication
 * @param password the password required for authentication
 * @param cmds the commands you want to execute remotely
 * @return the string with the parameters you entered 
 * @throws InterruptedException 
 * @throws IOException, InterruptedException
 */
public static String executeCommands(String host, int port,String username,String password, String[] cmds) throws IOException, InterruptedException {
	String commandOutput = "";
	SshClient ssh = connect(host, port,username, password);
	SessionChannelClient sessionChannel = ssh.openSessionChannel();

	// make a script out of all the commands
	StringBuilder cmdToExecute = new StringBuilder();
	for (String cmd : cmds) {
		cmdToExecute.append(cmd).append(";");
	}
	// execute the whole thing
	if (sessionChannel.executeCommand(cmdToExecute.toString())) {
		/**
		 * Reading from the session InputStream
		 */
		InputStream in = sessionChannel.getInputStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(in)); // read to buffer from the stream
	    StringBuffer buffer = new StringBuffer();
        String line;
		   while (((line = br.readLine()) !=  null)){ // read from the buffer of the stream the line
                  buffer.append(line); // append the result line to the String buffer.
                  buffer.append("\n");
		   }
		   commandOutput = buffer.toString(); 
		sessionChannel.getState().waitForState(ChannelState.CHANNEL_CLOSED);
		br.close();
		ssh.disconnect();
		return commandOutput;

	} 
	else {
		SSH_LOG.error("The command did not execute");
		ssh.disconnect();
		return commandOutput;
	}
}
 
Example #6
Source File: NetUtils.java    From ApprovalTests.Java with Apache License 2.0 5 votes vote down vote up
public static void sftpUpload(FTPConfig config, File file, String remoteFileName) throws IOException
{
  SshClient ssh = new SshClient();
  SftpClient sftp = sshLogin(config, ssh);
  sftp.mkdirs(remoteFileName.substring(0, remoteFileName.lastIndexOf("/")));
  sftp.put(new FileInputStream(file), remoteFileName);
  sftp.quit();
  ssh.disconnect();
}
 
Example #7
Source File: NetUtils.java    From ApprovalTests.Java with Apache License 2.0 5 votes vote down vote up
private static SftpClient sshLogin(FTPConfig config, SshClient ssh) throws IOException
{
  ssh.setSocketTimeout(60000);
  ssh.connect(config.host, new IgnoreHostKeyVerification());
  PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();
  pwd.setUsername(config.userName);
  pwd.setPassword(config.password);
  ssh.authenticate(pwd);
  SftpClient sftp = ssh.openSftpClient();
  return sftp;
}
 
Example #8
Source File: NetUtils.java    From ApprovalTests.Java with Apache License 2.0 5 votes vote down vote up
public static File sftpDownload(FTPConfig config, File file, String remoteFileName) throws IOException
{
  SshClient ssh = new SshClient();
  SftpClient sftp = sshLogin(config, ssh);
  sftp.get(remoteFileName, new FileOutputStream(file));
  sftp.quit();
  ssh.disconnect();
  return file;
}
 
Example #9
Source File: SshUtil.java    From qaf with MIT License 4 votes vote down vote up
/**
 * Get shell and execute command.
 * 
 * @param cmd
 * @return
 * @throws Exception
 */
public String executeSudoCommand(String command) throws Exception {

	String res = "";
	SessionChannelClient session = null;
	try {
		SshClient ssh = connectSsh();
		session = ssh.openSessionChannel();

		if (session.requestPseudoTerminal("isfw", 80, 24, 0, 0, "")) {
			if (session.startShell()) {
				session.getOutputStream().write((command + "\n").getBytes());

				InputStream in = session.getInputStream();
				byte buffer[] = new byte[255];
				int read;

				while ((read = in.read(buffer)) > 0) {

					res += new String(buffer, 0, read);
					System.out.println("res: " + res);

					if (res.contains("password")) {
						session.getOutputStream().write((getBundle().getString("ssh.pwd") + "\n").getBytes());
						res = command + "\n";
					}

					if (res.contains(command)) {
						if (res.endsWith("]$ ")) {
							break;
						}
						if (command.equalsIgnoreCase("status") && res.endsWith("]$ ")) {
							break;
						}
					}
				}

			} else {
				res = "Unable to start shell.";
			}
		} else {
			res = "Unable to request terminal.";
		}
	} finally {
		try {
			session.close();
		} catch (Exception e) {
		}
	}
	return res;
}
 
Example #10
Source File: SSHUtils.java    From stevia with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/** Disconnect
 * @param ssh
 */
public static void disConnect(SshClient ssh) {
	if(ssh.isConnected()){
		ssh.disconnect();
	}
}
 
Example #11
Source File: FtpSession.java    From iaf with Apache License 2.0 4 votes vote down vote up
private void openSftpClient(String remoteDirectory) throws FtpConnectException {
	try {
		// Set the connection properties and if necessary the proxy properties
		SshConnectionProperties sshProp = new SshConnectionProperties();
		sshProp.setHost(host);
		sshProp.setPort(port);
		if (StringUtils.isNotEmpty(prefCSEncryption))
			sshProp.setPrefCSEncryption(prefCSEncryption);
		if (StringUtils.isNotEmpty(prefSCEncryption))
			sshProp.setPrefCSEncryption(prefSCEncryption);

		if (! StringUtils.isEmpty(proxyHost)) {
			sshProp.setTransportProvider(proxyTransportType);
			sshProp.setProxyHost(proxyHost);
			sshProp.setProxyPort(proxyPort);
			CredentialFactory pcf = new CredentialFactory(getProxyAuthAlias(), proxyUsername, proxyPassword);

			if (! StringUtils.isEmpty(pcf.getUsername())) {
				sshProp.setProxyUsername(pcf.getUsername());
				sshProp.setProxyPassword(pcf.getPassword());
			}
		}

		// make a secure connection with the remote host 
		sshClient = new SshClient();
		if (StringUtils.isNotEmpty(knownHostsPath)) {
			AbstractKnownHostsKeyVerification hv = null;
			if (consoleKnownHostsVerifier) { 
				hv = new ConsoleKnownHostsKeyVerification(knownHostsPath); 
			}
			else {
				hv = new SftpHostVerification(knownHostsPath);
			}
			sshClient.connect(sshProp, hv);
		}
		else {
			sshClient.connect(sshProp, new IgnoreHostKeyVerification());
		}
		
		SshAuthenticationClient sac;
		if (!isKeyboardInteractive()) {
			// pass the authentication information
			sac = getSshAuthentication();
		} else {
			// TODO: detecteren dat sshClient.getAvailableAuthMethods("ftpmsg")
			// wel keyboard-interactive terug geeft, maar geen password en dan deze methode
			// gebruiken
			final CredentialFactory credentialFactory = new CredentialFactory(getAuthAlias(), getUsername(), getPassword());
			KBIAuthenticationClient kbiAuthenticationClient = new KBIAuthenticationClient();
			kbiAuthenticationClient.setUsername(credentialFactory.getUsername());
			kbiAuthenticationClient.setKBIRequestHandler(
				new KBIRequestHandler() {
					@Override
					public void showPrompts(String name, String instruction, KBIPrompt[] prompts) {
						//deze 3 regels in x.zip naar Zenz gemaild, hielp ook niet
						if(prompts==null) {
							return;
						}
						for(int i=0; i<prompts.length; i++) {
							prompts[i].setResponse(credentialFactory.getPassword());
						}
					}
				}
			);
			sac=kbiAuthenticationClient;
		}
		int result = sshClient.authenticate(sac);
		
		if (result != AuthenticationProtocolState.COMPLETE) {
			closeSftpClient();
			throw new IOException("Could not authenticate to sftp server " + result);
		}
		
		// use the connection for sftp
		sftpClient = sshClient.openSftpClient();
		
		if (! StringUtils.isEmpty(remoteDirectory)) {
			sftpClient.cd(remoteDirectory);
		}
	}
	catch(Exception e) {
		closeSftpClient();
		throw new FtpConnectException(e);
	}
}
 
Example #12
Source File: SshConnection.java    From ApprovalTests.Java with Apache License 2.0 4 votes vote down vote up
public SshConnection(SshClient ssh, Connection connection)
{
  this.ssh = ssh;
  this.con = connection;
}
 
Example #13
Source File: SSHUtils.java    From stevia with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * Connect.
 * 
 * @param host	 the host
 * @param username the username
 * @param password the password
 * @return the ssh client
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static SshClient connect(String host, String username,String password) throws IOException {
     return connect(host, SSH_PORT, username, password);
}
 
Example #14
Source File: SSHUtils.java    From stevia with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * Create an SFTP connection to a client
 *
 * @param host the hostname of the client
 * @param port the port the user want to use for connection
 * @param username the username required for authentication
 * @param password the password required for authentication
 * @return the client
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static SftpClient getSftpClient(String host,int port, String username,String password) throws IOException {
	SshClient ssh = connect(host, port,username, password);
	return ssh.openSftpClient();
}