本文整理汇总了Java中com.trilead.ssh2.Connection.connect方法的典型用法代码示例。如果您正苦于以下问题:Java Connection.connect方法的具体用法?Java Connection.connect怎么用?Java Connection.connect使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类com.trilead.ssh2.Connection
的用法示例。
在下文中一共展示了Connection.connect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: openTunnel
import com.trilead.ssh2.Connection; //导入方法依赖的package包/类
/***************************************************************************
* Open the SSH tunnel
**************************************************************************/
public void openTunnel() throws IOException
{
if (m_connected)
{
Logger.debug("Closing previous session", Level.COMM, this);
closeTunnel();
}
Logger.debug("Creating SSH connection", Level.COMM, this);
m_connection = new Connection(m_serverInfo.getHost());
Logger.debug("Opening SSH session", Level.COMM, this);
m_connection.connect();
Logger.debug("Authenticating", Level.COMM, this);
Authenticator.authenticate(m_connection, m_serverInfo.getAuthentication());
Logger.debug("Creating port forwarder", Level.COMM, this);
m_localPort = findFreePort(m_localPort + 1);
Logger.debug("localhost:" + m_localPort + " -> " + m_serverInfo.getHost() + ":" + m_serverInfo.getPort(), Level.COMM, this);
m_fwd = m_connection.createLocalPortForwarder(m_localPort, "localhost", m_serverInfo.getPort());
m_serverInfo.setPort(m_localPort);
m_connected = true;
Logger.debug("Tunnel connected", Level.COMM, this);
}
示例2: bySshWithEveryRetryWaitFor
import com.trilead.ssh2.Connection; //导入方法依赖的package包/类
/**
* Connects to sshd on host:port
* Retries while attempts reached with delay
* First with tcp port wait, then with ssh connection wait
*
* @throws IOException if no retries left
*/
public void bySshWithEveryRetryWaitFor(int time, TimeUnit units) throws IOException {
checkState(withEveryRetryWaitFor(time, units), "Port %s is not opened to connect to", hostAndPort.getPort());
for (int i = 1; i <= retries; i++) {
Connection connection = new Connection(hostAndPort.getHostText(), hostAndPort.getPort());
try {
connection.connect(null, 0, sshTimeoutMillis, sshTimeoutMillis);
LOG.info("SSH port is open on {}:{}", hostAndPort.getHostText(), hostAndPort.getPort());
return;
} catch (IOException e) {
LOG.error("Failed to connect to {}:{} (try {}/{}) - {}",
hostAndPort.getHostText(), hostAndPort.getPort(), i, retries, e.getMessage());
if (i == retries) {
throw e;
}
} finally {
connection.close();
}
sleepFor(time, units);
}
}
示例3: testRecRemoteOperatorAuthInfoString
import com.trilead.ssh2.Connection; //导入方法依赖的package包/类
@Test
public final void testRecRemoteOperatorAuthInfoString() throws IOException, RemoteException {
String midwarePath = "/root/nginx/";
AuthInfo authInfo= new RecAuthInfo();
authInfo.setHost("10.1.50.4");
authInfo.setUsername("root");
authInfo.setPassword("cs2csolutions");
Connection conn = new Connection("10.1.50.4");
/* Now connect */
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(
"root", "cs2csolutions");
if (isAuthenticated == false)
throw new RemoteException("Authentication failed.");
RecRemoteOperator rro1 = new RecRemoteOperator(authInfo,midwarePath,conn);
assertTrue(null != rro1);
}
示例4: setUpBeforeClass
import com.trilead.ssh2.Connection; //导入方法依赖的package包/类
/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception {
/* Create a connection instance */
conn = new Connection("10.1.50.4", 22);
/* Connect */
conn.connect();
/* Authenticate. */
boolean isAuthenticated =
conn.authenticateWithPassword("root", "cs2csolutions");
if (isAuthenticated == false)
throw new IOException("Authentication failed.");
logger=new RecLogger(conn, "/usr/local/nginx");
}
示例5: authenticateSshSessionWithPublicKey
import com.trilead.ssh2.Connection; //导入方法依赖的package包/类
/**
* This method will create and authenticate a session using a public key method. The
* certificate that will be used is the Autonomiccs default certificated that is installed by
* default in the Autonomiccs system VM template
*/
protected Session authenticateSshSessionWithPublicKey(Connection sshConnection) throws IOException {
sshConnection.connect(null, CONNECT_TIMEOUT, CONNECT_TIMEOUT);
if (!sshConnection.authenticateWithPublicKey("root", certificate, null)) {
throw new CloudRuntimeException(String.format("Unable to authenticate to (%s)", sshConnection.getHostname()));
}
return sshConnection.openSession();
}
示例6: openConnection
import com.trilead.ssh2.Connection; //导入方法依赖的package包/类
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;
}
示例7: getConnection
import com.trilead.ssh2.Connection; //导入方法依赖的package包/类
public Connection getConnection() throws IOException {
Connection conn = new Connection(this.getIp(), this.getPort());
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(
this.getUsername(), this.getPassword());
if (!isAuthenticated) {
throw new IOException("Authentication failed.");
}
LOG.info("create ssh session success with ip=[" + getIp()
+ "],port=[" + getPort() + "],username=[" + getUsername()
+ "],password=[*******]");
return conn;
}
示例8: connect
import com.trilead.ssh2.Connection; //导入方法依赖的package包/类
public static Connection connect(HostAndPort host, StandardUsernameCredentials credentials) throws IOException {
Connection connection = new Connection(host.getHostText(), host.getPortOrDefault(22));
connection.setTCPNoDelay(true);
connection.connect();
try {
if (credentials instanceof StandardUsernamePasswordCredentials) {
StandardUsernamePasswordCredentials passwordCredentials = (StandardUsernamePasswordCredentials) credentials;
connection.authenticateWithPassword(passwordCredentials.getUsername(), Secret.toString(passwordCredentials.getPassword()));
} else if (credentials instanceof SSHUserPrivateKey) {
SSHUserPrivateKey sshCredentials = (SSHUserPrivateKey) credentials;
checkState(sshCredentials.getPrivateKeys().size() > 0, "no private keys defined");
String username = credentials.getUsername();
String password = Secret.toString(sshCredentials.getPassphrase());
for (String privateKey : sshCredentials.getPrivateKeys()) {
if (connection.authenticateWithPublicKey(username, privateKey.toCharArray(), password)) {
break;
}
}
} else {
connection.authenticateWithNone(credentials.getUsername());
}
checkState(connection.isAuthenticationComplete(), "Authentication failed");
} catch (Throwable ex) {
connection.close();
throw Throwables.propagate(ex);
}
return connection;
}
示例9: connectToSsh
import com.trilead.ssh2.Connection; //导入方法依赖的package包/类
private Connection connectToSsh(Computer computer, PrintStream logger) throws InterruptedException, RequestUnsuccessfulException, AccessDeniedException, ResourceNotFoundException {
// TODO: make configurable?
final long timeout = TimeUnit2.MINUTES.toMillis(5);
final long startTime = System.currentTimeMillis();
while(true) {
try {
long waitTime = System.currentTimeMillis() - startTime;
if ( waitTime > timeout ) {
throw new RuntimeException("Timed out after "+ (waitTime / 1000) + " seconds of waiting for ssh to become available. (maximum timeout configured is "+ (timeout / 1000) + ")" );
}
Droplet instance = computer.updateInstanceDescription();
String host = instance.getIpAddress();
if (Strings.isNullOrEmpty(host) || "0.0.0.0".equals(host)) {
logger.println("No ip address yet, your host is most likely waiting for an ip address.");
throw new IOException("sleep");
}
int port = computer.getSshPort();
logger.println("Connecting to " + host + " on port " + port + ". ");
Connection conn = new Connection(host, port);
conn.connect();
logger.println("Connected via SSH.");
return conn; // successfully connected
} catch (IOException e) {
// keep retrying until SSH comes up
logger.println("Waiting for SSH to come up. Sleeping 5 seconds.");
Thread.sleep(5000);
}
}
}
示例10: creatConnection
import com.trilead.ssh2.Connection; //导入方法依赖的package包/类
public void creatConnection() throws RemoteException {
/* Create a connection instance */
conn = new Connection(authInfo.getHostname());
/* Now connect */
try {
conn.connect();
conn.authenticateWithPassword(
authInfo.getUsername(), authInfo.getPassword());
} catch (IOException e) {
// TODO Auto-generated catch block
throw new RemoteException(e);
}
}
示例11: establishConnection
import com.trilead.ssh2.Connection; //导入方法依赖的package包/类
public static void establishConnection() throws IOException {
/* Create a connection instance */
conn = new Connection(hostname, port);
/* Connect */
conn.connect();
/* Authenticate. */
boolean isAuthenticated =
conn.authenticateWithPassword(username, password);
if (isAuthenticated == false)
throw new IOException("Authentication failed.");
}
示例12: getSession
import com.trilead.ssh2.Connection; //导入方法依赖的package包/类
/** {@inheritDoc} */
@Override
public RemoteSession getSession(URIish uri, CredentialsProvider credentialsProvider, FS fs, int tms) throws TransportException {
try {
int p = uri.getPort();
if (p<0) p = 22;
Connection con = new Connection(uri.getHost(), p);
con.setTCPNoDelay(true);
con.connect(); // TODO: host key check
boolean authenticated;
if (credentialsProvider instanceof SmartCredentialsProvider) {
final SmartCredentialsProvider smart = (SmartCredentialsProvider) credentialsProvider;
StandardUsernameCredentialsCredentialItem
item = new StandardUsernameCredentialsCredentialItem("Credentials for " + uri, false);
authenticated = smart.supports(item)
&& smart.get(uri, item)
&& SSHAuthenticator.newInstance(con, item.getValue(), uri.getUser())
.authenticate(smart.listener);
} else if (credentialsProvider instanceof CredentialsProviderImpl) {
CredentialsProviderImpl sshcp = (CredentialsProviderImpl) credentialsProvider;
authenticated = SSHAuthenticator.newInstance(con, sshcp.cred).authenticate(sshcp.listener);
} else {
authenticated = false;
}
if (!authenticated && con.isAuthenticationComplete())
throw new TransportException("Authentication failure");
return wrap(con);
} catch (UnsupportedCredentialItem | IOException | InterruptedException e) {
throw new TransportException(uri,"Failed to connect",e);
}
}
示例13: main
import com.trilead.ssh2.Connection; //导入方法依赖的package包/类
public static void main(String[] args)
{
String hostname = "127.0.0.1";
String username = "joe";
String password = "joespass";
try
{
/* Create a connection instance */
Connection conn = new Connection(hostname);
/* 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, 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);
}
}
示例14: main
import com.trilead.ssh2.Connection; //导入方法依赖的package包/类
public static void main(String[] args)
{
String hostname = "my-ssh-server";
String username = "joe";
String password = "joespass";
String proxyHost = "192.168.1.1";
int proxyPort = 3128; // default port used by squid
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);
}
}
示例15: SSHConnect
import com.trilead.ssh2.Connection; //导入方法依赖的package包/类
private void SSHConnect(LogWriter log,String realservername, String realserverpassword, int realserverport,
String realUsername, String realPassword,
String realproxyhost,String realproxyusername, String realproxypassword, int realproxyport,
String realkeyFilename, String realkeyPass) throws Exception
{
/* Create a connection instance */
Connection conn = new Connection(realservername,realserverport);
/* We want to connect through a HTTP proxy */
if(useproxy)
{
conn.setProxyData(new HTTPProxyData(realproxyhost, realproxyport));
/* Now connect */
// if the proxy requires basic authentication:
if(!Const.isEmpty(realproxyusername) || !Const.isEmpty(realproxypassword))
{
conn.setProxyData(new HTTPProxyData(realproxyhost, realproxyport, realproxyusername, realproxypassword));
}
}
if(timeout>0)
{
// Use timeout
conn.connect(null,0,timeout*1000);
}else
{
// Cache Host Key
conn.connect();
}
// Authenticate
boolean isAuthenticated = false;
if(publicpublickey)
{
isAuthenticated=conn.authenticateWithPublicKey(realUsername, new File(keyFilename), realkeyPass);
}else
{
isAuthenticated=conn.authenticateWithPassword(realUsername, realserverpassword);
}
if(!isAuthenticated) throw new Exception("Can not connect to ");
sshclient = new SFTPv3Client(conn);
}