本文整理汇总了Java中com.trilead.ssh2.Connection.close方法的典型用法代码示例。如果您正苦于以下问题:Java Connection.close方法的具体用法?Java Connection.close怎么用?Java Connection.close使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类com.trilead.ssh2.Connection
的用法示例。
在下文中一共展示了Connection.close方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: 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);
}
}
示例2: executeCommandOnHostViaSsh
import com.trilead.ssh2.Connection; //导入方法依赖的package包/类
/**
* It executes a given command to the host with a given IP address. Waits 15
* minutes after the command execution, avoiding to close the session before
* it sends successfully the command.
*/
public void executeCommandOnHostViaSsh(String hostIp, String command) {
Connection sshConnectionWithHost = getSshConnectionWithHost(hostIp);
try {
Session sshSession = authenticateSshSessionWithPublicKey(sshConnectionWithHost);
sshSession.execCommand(command);
waitUntilCommandFinishes(hostIp, command, sshSession);
sshSession.close();
} catch (IOException e) {
logger.info("Unable to execute command: " + command, e);
}
sshConnectionWithHost.close();
}
示例3: bootstrap
import com.trilead.ssh2.Connection; //导入方法依赖的package包/类
private int bootstrap(Connection bootstrapConn, EC2Computer computer, PrintStream logger) throws IOException, InterruptedException, AmazonClientException {
logger.println("bootstrap()" );
boolean closeBootstrap = true;
try {
int tries = 20;
boolean isAuthenticated = false;
logger.println("Getting keypair..." );
KeyPair key = computer.getCloud().getKeyPair();
logger.println("Using key: " + key.getKeyName() + "\n" + key.getKeyFingerprint() + "\n" + key.getKeyMaterial().substring(0, 160) );
while (tries-- > 0) {
logger.println("Authenticating as " + computer.getRemoteAdmin());
isAuthenticated = bootstrapConn.authenticateWithPublicKey(computer.getRemoteAdmin(), key.getKeyMaterial().toCharArray(), "");
if (isAuthenticated) {
break;
}
logger.println("Authentication failed. Trying again...");
Thread.sleep(10000);
}
if (!isAuthenticated) {
logger.println("Authentication failed");
return FAILED;
}
closeBootstrap = false;
return SAMEUSER;
} finally {
if (closeBootstrap)
bootstrapConn.close();
}
}
示例4: closeRegisteredConnections
import com.trilead.ssh2.Connection; //导入方法依赖的package包/类
/**
* Closes all the registered connections.
*/
private static synchronized void closeRegisteredConnections() {
for (Connection connection : activeConnections) {
LOGGER.log(Level.INFO, "Forcing connection to {0}:{1} closed.",
new Object[]{connection.getHostname(), connection.getPort()});
// force closed just in case
connection.close();
}
activeConnections.clear();
}
示例5: 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;
}
示例6: bootstrap
import com.trilead.ssh2.Connection; //导入方法依赖的package包/类
private int bootstrap(Connection bootstrapConn, Computer computer, PrintStream logger) throws IOException, InterruptedException {
logger.println("bootstrap()" );
boolean closeBootstrap = true;
if (bootstrapConn.isAuthenticationComplete()) {
return SAMEUSER;
}
try {
int tries = 20;
boolean isAuthenticated = false;
while (tries-- > 0) {
logger.println("Authenticating as " + computer.getRemoteAdmin());
isAuthenticated = bootstrapConn.authenticateWithPublicKey(computer.getRemoteAdmin(), computer.getNode().getPrivateKey().toCharArray(), "");
if (isAuthenticated) {
break;
}
logger.println("Authentication failed. Trying again...");
Thread.sleep(10000);
}
if (!isAuthenticated) {
logger.println("Authentication failed");
return FAILED;
}
closeBootstrap = false;
return SAMEUSER;
} catch (Exception e) {
e.printStackTrace(logger);
return FAILED;
} finally {
if (closeBootstrap)
bootstrapConn.close();
}
}
示例7: 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);
}
}
示例8: 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);
}
}
示例9: main
import com.trilead.ssh2.Connection; //导入方法依赖的package包/类
public static void main(String[] args) {
// Parameters
List<String> argsList = Arrays.asList(args);
Iterator<String> iter = argsList.iterator();
while (iter.hasNext()) {
String arg = iter.next();
if (arg.equals("-h")) {
host = iter.next();
}
if (arg.equals("-p")) {
password = iter.next();
}
if (arg.equals("-u")) {
url = iter.next();
}
}
if (host == null || host.equals("")) {
s_logger.info("Did not receive a host back from test, ignoring ssh test");
System.exit(2);
}
if (password == null) {
s_logger.info("Did not receive a password back from test, ignoring ssh test");
System.exit(2);
}
try {
s_logger.info("Attempting to SSH into host " + host);
Connection conn = new Connection(host);
conn.connect(null, 60000, 60000);
s_logger.info("User + ssHed successfully into host " + host);
boolean isAuthenticated = conn.authenticateWithPassword("root", password);
if (isAuthenticated == false) {
s_logger.info("Authentication failed for root with password" + password);
System.exit(2);
}
String linuxCommand = "wget " + url;
Session sess = conn.openSession();
sess.execCommand(linuxCommand);
sess.close();
conn.close();
} catch (Exception e) {
s_logger.error("SSH test fail with error", e);
System.exit(2);
}
}
示例10: run
import com.trilead.ssh2.Connection; //导入方法依赖的package包/类
@Override
public void run() {
NDC.push("Following thread has started" + Thread.currentThread().getName());
int retry = 0;
//Start copying files between machines in the network
s_logger.info("The size of the array is " + this.virtualMachines.size());
while (true) {
try {
if (retry > 0) {
s_logger.info("Retry attempt : " + retry + " ...sleeping 120 seconds before next attempt");
Thread.sleep(120000);
}
for (VirtualMachine vm : this.virtualMachines) {
s_logger.info("Attempting to SSH into linux host " + this.publicIp + " with retry attempt: " + retry);
Connection conn = new Connection(this.publicIp);
conn.connect(null, 600000, 600000);
s_logger.info("SSHed successfully into linux host " + this.publicIp);
boolean isAuthenticated = conn.authenticateWithPassword("root", "password");
if (isAuthenticated == false) {
s_logger.info("Authentication failed");
}
//execute copy command
Session sess = conn.openSession();
String fileName;
Random ran = new Random();
fileName = Math.abs(ran.nextInt()) + "-file";
String copyCommand = new String("./scpScript " + vm.getPrivateIp() + " " + fileName);
s_logger.info("Executing " + copyCommand);
sess.execCommand(copyCommand);
Thread.sleep(120000);
sess.close();
//execute wget command
sess = conn.openSession();
String downloadCommand =
new String("wget http://172.16.0.220/scripts/checkDiskSpace.sh; chmod +x *sh; ./checkDiskSpace.sh; rm -rf checkDiskSpace.sh");
s_logger.info("Executing " + downloadCommand);
sess.execCommand(downloadCommand);
Thread.sleep(120000);
sess.close();
//close the connection
conn.close();
}
} catch (Exception ex) {
s_logger.error(ex);
retry++;
if (retry == retryNum) {
s_logger.info("Performance Guest Network test failed with error " + ex.getMessage());
}
}
}
}
示例11: OpenConnection
import com.trilead.ssh2.Connection; //导入方法依赖的package包/类
public static Connection OpenConnection( String serveur, int port, String username, String password,
boolean useKey, String keyFilename, String passPhrase, int timeOut, VariableSpace space, String proxyhost,
int proxyport, String proxyusername, String proxypassword ) throws KettleException {
Connection conn = null;
char[] content = null;
boolean isAuthenticated = false;
try {
// perform some checks
if ( useKey ) {
if ( Utils.isEmpty( keyFilename ) ) {
throw new KettleException( BaseMessages.getString( SSHMeta.PKG, "SSH.Error.PrivateKeyFileMissing" ) );
}
FileObject keyFileObject = KettleVFS.getFileObject( keyFilename );
if ( !keyFileObject.exists() ) {
throw new KettleException( BaseMessages.getString( SSHMeta.PKG, "SSH.Error.PrivateKeyNotExist", keyFilename ) );
}
FileContent keyFileContent = keyFileObject.getContent();
CharArrayWriter charArrayWriter = new CharArrayWriter( (int) keyFileContent.getSize() );
try ( InputStream in = keyFileContent.getInputStream() ) {
IOUtils.copy( in, charArrayWriter );
}
content = charArrayWriter.toCharArray();
}
// Create a new connection
conn = createConnection( serveur, port );
/* We want to connect through a HTTP proxy */
if ( !Utils.isEmpty( proxyhost ) ) {
/* Now connect */
// if the proxy requires basic authentication:
if ( !Utils.isEmpty( proxyusername ) ) {
conn.setProxyData( new HTTPProxyData( proxyhost, proxyport, proxyusername, proxypassword ) );
} else {
conn.setProxyData( new HTTPProxyData( proxyhost, proxyport ) );
}
}
// and connect
if ( timeOut == 0 ) {
conn.connect();
} else {
conn.connect( null, 0, timeOut * 1000 );
}
// authenticate
if ( useKey ) {
isAuthenticated =
conn.authenticateWithPublicKey( username, content, space.environmentSubstitute( passPhrase ) );
} else {
isAuthenticated = conn.authenticateWithPassword( username, password );
}
if ( isAuthenticated == false ) {
throw new KettleException( BaseMessages.getString( SSHMeta.PKG, "SSH.Error.AuthenticationFailed", username ) );
}
} catch ( Exception e ) {
// Something wrong happened
// do not forget to disconnect if connected
if ( conn != null ) {
conn.close();
}
throw new KettleException( BaseMessages.getString( SSHMeta.PKG, "SSH.Error.ErrorConnecting", serveur, username ), e );
}
return conn;
}
示例12: sendFileToHost
import com.trilead.ssh2.Connection; //导入方法依赖的package包/类
/**
* Copy a local file to a remote directory, uses mode 0600 when creating the
* file on the remote side.
*
* @param localfilePath
* The file that will be sent to the host
* @param remotePath
* Remote target directory. Use an empty string to specify the
* default directory.
* @param address
* The Management IP address from machine that will be connected.
* @throws IOException
*/
public void sendFileToHost(File localfilePath, String remoteFileName, String remotePath, String address) {
Connection sshConnectionWithHost = getSshConnectionWithHost(address);
try {
authenticateSshSessionWithPublicKey(sshConnectionWithHost);
SCPClient scp = new SCPClient(sshConnectionWithHost);
scp.put(localfilePath.getAbsolutePath(), remoteFileName, remotePath, "0755");
} catch (IOException e) {
logger.error(String.format("Error while sending file [%s] to host [%s]", localfilePath, address), e);
}
sshConnectionWithHost.close();
}
示例13: main
import com.trilead.ssh2.Connection; //导入方法依赖的package包/类
public static void main(String[] args)
{
String hostname = "127.0.0.1";
String username = "joe";
File keyfile = new File("~/.ssh/id_rsa"); // or "~/.ssh/id_dsa"
String keyfilePass = "joespass"; // will be ignored if not needed
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.");
/* Create a session */
Session sess = conn.openSession();
sess.execCommand("uname -a && date && uptime && who");
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
System.out.println("Here is some information about the remote host:");
while (true)
{
String line = br.readLine();
if (line == null)
break;
System.out.println(line);
}
/* 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) throws IOException
{
String hostname = "somehost";
String username = "joe";
String password = "joespass";
File knownHosts = new File("~/.ssh/known_hosts");
try
{
/* Load known_hosts file into in-memory database */
if (knownHosts.exists())
database.addHostkeys(knownHosts);
/* Create a connection instance */
Connection conn = new Connection(hostname);
/* Now connect and use the SimpleVerifier */
conn.connect(new SimpleVerifier(database));
/* Authenticate */
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");
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
System.out.println("Here is some information about the remote host:");
while (true)
{
String line = br.readLine();
if (line == null)
break;
System.out.println(line);
}
/* Close this session */
sess.close();
/* Close the connection */
conn.close();
}
catch (IOException e)
{
e.printStackTrace(System.err);
System.exit(2);
}
}