use of org.openmuc.j62056.Connection in project ACS by ACS-Community.
the class Executor method remotePortable.
/**
* @return false - if this failed gracefully
* @throws IOException - if this failed severely
*/
private static boolean remotePortable(String username, String password, String command, String endMark, NativeCommand.Listener listener, String host) throws IOException {
if (listener == null) {
// normalization: use a do-nothing implementation
listener = new NativeCommand.ListenerAdapter();
}
try {
remoteFlow.reset(null);
// connect
// --------
Connection conn = new Connection(host);
connections.add(conn);
conn.connect();
remoteFlow.success(RemoteFlow.CONNECT);
// login
// ------
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (isAuthenticated == false)
throw new IOException("Authentication failed");
remoteFlow.success(RemoteFlow.LOG_IN);
// send command
// -------------
Session sess = conn.openSession();
sessions.add(sess);
/* msc 2008-11:
* We're passing the command as an argument to ssh, just like typing
* > ssh 127.0.0.1 "env"
* on the commandline. This opens a non-login shell on the remote host
* which (thank you bash) won't parse the .bash_profile but only the .bashrc!
* Now unfortunately the usual setup for accounts on Alma machines is to
* have the ACS settings defined in .bash_profile. The optimal way around
* this would be to run a real login shell here by allocating a terminal,
* and then deal with all the input output/stuff ourselves. I'm trying here
* to get away with something cheaper: Explicitly source the .bash_profile
* before running the command.
*/
command = ". ~/.bash_profile ; " + command;
log.info("Now sending: '" + command + "'");
sess.execCommand(command);
remoteFlow.success(RemoteFlow.SEND_COMMAND);
// read output, scan for endmark
// ----------------------------
SearchBuffer searchStdout = null;
SearchBuffer searchStderr = null;
if (endMark != null) {
searchStdout = new SearchBuffer(endMark);
searchStderr = new SearchBuffer(endMark);
}
InputStream stdout = sess.getStdout();
InputStream stderr = sess.getStderr();
byte[] buffer = new byte[8192];
while (true) {
if (stdout.available() == 0 && stderr.available() == 0) {
/* Even though currently there is no data available, it may be that new data arrives
* and the session's underlying channel is closed before we call waitForCondition().
* This means that EOF and STDOUT_DATA (or STDERR_DATA, or both) may be set together. */
int conditions = sess.waitForCondition(//
ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA | ChannelCondition.EOF, // allow several seconds
10 * 1000);
if ((conditions & ChannelCondition.TIMEOUT) != 0) {
throw new IOException("Timeout while waiting for data from peer");
}
if ((conditions & ChannelCondition.EOF) != 0) {
/* The remote side won't send us further data ... */
if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) {
/* ... and we have consumed all data in the local arrival window. */
break;
}
}
/* At this point, either STDOUT_DATA or STDERR_DATA, (or both) is set. */
}
/* If you below use "if" instead of "while", then the way the output appears on the local
* stdout and stder streams is more "balanced". Addtionally reducing the buffer size
* will also improve the interleaving, but performance will slightly suffer.
* OKOK, that all matters only if you get HUGE amounts of stdout and stderr data =)
*/
if (stdout.available() > 0) {
int len = stdout.read(buffer);
listener.stdoutWritten(null, new String(buffer, 0, len));
if (searchStdout != null)
if (searchStdout.add(buffer, 0, len)) {
remoteFlow.success(RemoteFlow.COMPLETE);
break;
}
}
if (stderr.available() > 0) {
int len = stderr.read(buffer);
// msc 2008-11: porting to a different ssh library. this should of course
// call stderrWritten() but i don't want to change the original behavior.
listener.stdoutWritten(null, new String(buffer, 0, len));
if (searchStderr != null)
if (searchStderr.add(buffer, 0, len)) {
remoteFlow.success(RemoteFlow.COMPLETE);
break;
}
}
}
return true;
} catch (IOException exc) {
remoteFlow.failure(exc);
/* throw exc; */
return false;
}
}
use of org.openmuc.j62056.Connection in project wildfly by wildfly.
the class AsyncFutureInterceptorFactory method create.
@Override
public Interceptor create(final InterceptorFactoryContext context) {
final SessionBeanComponent component = (SessionBeanComponent) context.getContextData().get(Component.class);
if (component.isSecurityDomainKnown()) {
return new Interceptor() {
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
if (!context.isBlockingCaller()) {
return context.proceed();
}
final InterceptorContext asyncInterceptorContext = context.clone();
asyncInterceptorContext.putPrivateData(InvocationType.class, InvocationType.ASYNC);
final CancellationFlag flag = new CancellationFlag();
final SecurityDomain securityDomain = context.getPrivateData(SecurityDomain.class);
final StartupCountdown.Frame frame = StartupCountdown.current();
final SecurityIdentity currentIdentity = securityDomain == null ? null : securityDomain.getCurrentSecurityIdentity();
final Connection remoteConnection = getConnection();
Callable<Object> invocationTask = () -> {
setConnection(remoteConnection);
StartupCountdown.restore(frame);
try {
return asyncInterceptorContext.proceed();
} finally {
StartupCountdown.restore(null);
clearConnection();
}
};
final AsyncInvocationTask task = new AsyncInvocationTask(flag) {
@Override
protected Object runInvocation() throws Exception {
if (currentIdentity != null) {
return currentIdentity.runAs(invocationTask);
} else {
return invocationTask.call();
}
}
};
asyncInterceptorContext.putPrivateData(CancellationFlag.class, flag);
asyncInterceptorContext.setBlockingCaller(false);
return execute(component, task);
}
};
} else {
return new Interceptor() {
@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
if (!context.isBlockingCaller()) {
return context.proceed();
}
final InterceptorContext asyncInterceptorContext = context.clone();
asyncInterceptorContext.putPrivateData(InvocationType.class, InvocationType.ASYNC);
final CancellationFlag flag = new CancellationFlag();
final SecurityContext securityContext;
if (WildFlySecurityManager.isChecking()) {
securityContext = AccessController.doPrivileged(new PrivilegedAction<SecurityContext>() {
@Override
public SecurityContext run() {
return SecurityContextAssociation.getSecurityContext();
}
});
} else {
securityContext = SecurityContextAssociation.getSecurityContext();
}
// clone the original security context so that changes to the original security context in a separate (caller/unrelated) thread doesn't affect
// the security context associated with the async invocation thread
final SecurityContext clonedSecurityContext;
if (securityContext instanceof JBossSecurityContext) {
clonedSecurityContext = (SecurityContext) ((JBossSecurityContext) securityContext).clone();
} else {
// we can't do anything if it isn't a JBossSecurityContext so just use the original one
clonedSecurityContext = securityContext;
}
final Connection remoteConnection = getConnection();
final StartupCountdown.Frame frame = StartupCountdown.current();
final AsyncInvocationTask task = new AsyncInvocationTask(flag) {
@Override
protected Object runInvocation() throws Exception {
setSecurityContextOnAssociation(clonedSecurityContext);
setConnection(remoteConnection);
StartupCountdown.restore(frame);
try {
return asyncInterceptorContext.proceed();
} finally {
StartupCountdown.restore(null);
try {
clearSecurityContextOnAssociation();
} finally {
clearConnection();
}
}
}
};
asyncInterceptorContext.putPrivateData(CancellationFlag.class, flag);
asyncInterceptorContext.setBlockingCaller(false);
return execute(component, task);
}
};
}
}
use of org.openmuc.j62056.Connection in project intellij-community by JetBrains.
the class SshConnectionUtils method openConnection.
// we need project here since it could occur that the same repository/proxy would be used from different projects with different credentials
// though it is unlikely
public static Connection openConnection(final ConnectionSettings connectionSettings, final SshAuthentication authentication) throws AuthenticationException, IOException {
final int port = connectionSettings.getPort() == -1 ? SSH_DEFAULT_PORT : connectionSettings.getPort();
final Connection connection = new Connection(connectionSettings.getHostName(), port);
final ProxyData proxy = SshProxyFactory.createAndRegister(connectionSettings);
if (proxy != null) {
connection.setProxyData(proxy);
}
connection.connect(null, connectionSettings.getConnectionTimeout(), connectionSettings.getConnectionTimeout());
authentication.authenticate(connection);
//HTTPProxyException
return connection;
}
use of org.openmuc.j62056.Connection in project intellij-community by JetBrains.
the class BasicWithHTTPProxy method main.
public static void main(String[] args) {
String hostname = "my-ssh-server";
String username = "joe";
String password = "joespass";
String proxyHost = "192.168.1.1";
// default port used by squid
int proxyPort = 3128;
try {
/* Create a connection instance */
Connection conn = new Connection(hostname);
/* We want to connect through a HTTP proxy */
conn.setProxyData(new HTTPProxyData(proxyHost, proxyPort));
// if the proxy requires basic authentication:
// conn.setProxyData(new HTTPProxyData(proxyHost, proxyPort, "username", "secret"));
/* Now connect (through the proxy) */
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, password);
if (isAuthenticated == false)
throw new IOException("Authentication failed.");
/* Create a session */
Session sess = conn.openSession();
sess.execCommand("uname -a && date && uptime && who");
System.out.println("Here is some information about the remote host:");
/*
* This basic example does not handle stderr, which is sometimes dangerous
* (please read the FAQ).
*/
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
while (true) {
String line = br.readLine();
if (line == null)
break;
System.out.println(line);
}
/* Show exit status, if available (otherwise "null") */
System.out.println("ExitCode: " + sess.getExitStatus());
/* Close this session */
sess.close();
/* Close the connection */
conn.close();
} catch (IOException e) {
e.printStackTrace(System.err);
System.exit(2);
}
}
use of org.openmuc.j62056.Connection in project intellij-community by JetBrains.
the class PortForwarding method main.
public static void main(String[] args) {
String hostname = "127.0.0.1";
String username = "joe";
// or "~/.ssh/id_dsa"
File keyfile = new File("~/.ssh/id_rsa");
// will be ignored if not needed
String keyfilePass = "joespass";
try {
/* Create a connection instance */
Connection conn = new Connection(hostname);
/* Now connect */
conn.connect();
/* Authenticate */
boolean isAuthenticated = conn.authenticateWithPublicKey(username, keyfile, keyfilePass);
if (isAuthenticated == false)
throw new IOException("Authentication failed.");
/* ===== OK, now let's establish some local port forwardings ===== */
/* Example Port Forwarding: -L 8080:www.icann.org:80 (OpenSSH notation)
*
* This works by allocating a socket to listen on 8080 on the local interface (127.0.0.1).
* Whenever a connection is made to this port (127.0.0.1:8080), the connection is forwarded
* over the secure channel, and a connection is made to www.icann.org:80 from the remote
* machine (i.e., the ssh server).
*
* (the above text is based partially on the OpenSSH man page)
*/
/* You can create as many of them as you want */
LocalPortForwarder lpf1 = conn.createLocalPortForwarder(8080, "www.icann.org", 80);
/* Now simply point your webbrowser to 127.0.0.1:8080 */
/* (on the host where you execute this program) */
/* ===== OK, now let's establish some remote port forwardings ===== */
/* Example Port Forwarding: -R 127.0.0.1:8080:www.ripe.net:80 (OpenSSH notation)
*
* Specifies that the port 127.0.0.1:8080 on the remote server is to be forwarded to the
* given host and port on the local side. This works by allocating a socket to listen to port
* 8080 on the remote side (the ssh server), and whenever a connection is made to this port, the
* connection is forwarded over the secure channel, and a connection is made to
* www.ripe.net:80 by the Trilead SSH-2 library.
*
* (the above text is based partially on the OpenSSH man page)
*/
/* You can create as many of them as you want */
conn.requestRemotePortForwarding("127.0.0.1", 8080, "www.ripe.net", 80);
/* Now, on the ssh server, if you connect to 127.0.0.1:8080, then the connection is forwarded
* through the secure tunnel to the library, which in turn will forward the connection
* to www.ripe.net:80. */
/* Sleep a bit... (30 seconds) */
sleepSomeTime(30000);
/* Stop accepting remote connections that are being forwarded to www.ripe.net:80 */
conn.cancelRemotePortForwarding(8080);
/* Sleep a bit... (20 seconds) */
sleepSomeTime(20000);
/* Stop accepting connections on 127.0.0.1:8080 that are being forwarded to www.icann.org:80 */
lpf1.close();
/* Close the connection */
conn.close();
} catch (IOException e) {
e.printStackTrace(System.err);
System.exit(2);
}
}
Aggregations