本文整理匯總了Java中com.jcraft.jsch.Session.openChannel方法的典型用法代碼示例。如果您正苦於以下問題:Java Session.openChannel方法的具體用法?Java Session.openChannel怎麽用?Java Session.openChannel使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類com.jcraft.jsch.Session
的用法示例。
在下文中一共展示了Session.openChannel方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: fileFetch
import com.jcraft.jsch.Session; //導入方法依賴的package包/類
public static void fileFetch(String host, String user, String keyLocation, String sourceDir, String destDir) {
JSch jsch = new JSch();
Session session = null;
try {
// set up session
session = jsch.getSession(user,host);
// use private key instead of username/password
session.setConfig(
"PreferredAuthentications",
"publickey,gssapi-with-mic,keyboard-interactive,password");
jsch.addIdentity(keyLocation);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
// copy remote log file to localhost.
ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
channelSftp.get(sourceDir, destDir);
channelSftp.exit();
} catch (Exception e) {
e.printStackTrace();
} finally {
session.disconnect();
}
}
示例2: executeCommand
import com.jcraft.jsch.Session; //導入方法依賴的package包/類
/**
* Executes a given command. It opens exec channel for the command and closes
* the channel when it's done.
*
* @param session ssh connection to a remote server
* @param command command to execute
* @return command output string if the command succeeds, or null
*/
private static String executeCommand(Session session, String command) {
if (session == null || !session.isConnected()) {
return null;
}
log.trace("Execute command {} to {}", command, session.getHost());
try {
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
channel.setInputStream(null);
InputStream output = channel.getInputStream();
channel.connect();
String result = CharStreams.toString(new InputStreamReader(output));
channel.disconnect();
log.trace("Result of command {} on {}: {}", command, session.getHost(), result);
return result;
} catch (JSchException | IOException e) {
log.error("Failed to execute command {} on {} due to {}", command, session.getHost(), e.toString());
return null;
}
}
示例3: testTestCommand
import com.jcraft.jsch.Session; //導入方法依賴的package包/類
@Test
public void testTestCommand() throws JSchException, IOException {
JSch jsch = new JSch();
Session session = jsch.getSession("admin", "localhost", properties.getShell().getPort());
jsch.addIdentity("src/test/resources/id_rsa");
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
ChannelShell channel = (ChannelShell) session.openChannel("shell");
PipedInputStream pis = new PipedInputStream();
PipedOutputStream pos = new PipedOutputStream();
channel.setInputStream(new PipedInputStream(pos));
channel.setOutputStream(new PipedOutputStream(pis));
channel.connect();
pos.write("test run bob\r".getBytes(StandardCharsets.UTF_8));
pos.flush();
verifyResponse(pis, "test run bob");
pis.close();
pos.close();
channel.disconnect();
session.disconnect();
}
開發者ID:anand1st,項目名稱:sshd-shell-spring-boot,代碼行數:24,代碼來源:SshdShellAutoConfigurationWithPublicKeyAndBannerImageTest.java
示例4: sshCall
import com.jcraft.jsch.Session; //導入方法依賴的package包/類
protected void sshCall(String username, String password, SshExecutor executor, String channelType) {
try {
JSch jsch = new JSch();
Session session = jsch.getSession(username, props.getShell().getHost(), props.getShell().getPort());
session.setPassword(password);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
Channel channel = session.openChannel(channelType);
PipedInputStream pis = new PipedInputStream();
PipedOutputStream pos = new PipedOutputStream();
channel.setInputStream(new PipedInputStream(pos));
channel.setOutputStream(new PipedOutputStream(pis));
channel.connect();
try {
executor.execute(pis, pos);
} finally {
pis.close();
pos.close();
channel.disconnect();
session.disconnect();
}
} catch(JSchException | IOException ex) {
fail(ex.toString());
}
}
示例5: connectAndExecute
import com.jcraft.jsch.Session; //導入方法依賴的package包/類
public static String connectAndExecute(String user, String host, String password, String command1) {
String CommandOutput = null;
try {
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig(config);
session.connect();
// System.out.println("Connected");
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command1);
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
channel.connect();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0)
break;
// System.out.print(new String(tmp, 0, i));
CommandOutput = new String(tmp, 0, i);
}
if (channel.isClosed()) {
// System.out.println("exit-status: " +
// channel.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
}
}
channel.disconnect();
session.disconnect();
// System.out.println("DONE");
} catch (Exception e) {
e.printStackTrace();
}
return CommandOutput;
}
示例6: init
import com.jcraft.jsch.Session; //導入方法依賴的package包/類
ChannelSftp init(String filename) throws JSchException, UnsupportedEncodingException {
jsch = new JSch();
ConnectionInfo ci = splitStringToConnectionInfo(filename);
Session session = jsch.getSession(ci.username, ci.host, ci.port);
UserInfo ui = new SftpUserInfo(ci.password);
session.setUserInfo(ui);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp c = (ChannelSftp) channel;
logDebug("success: init Sftp");
return c;
}
示例7: scpFileFromRemoteServer
import com.jcraft.jsch.Session; //導入方法依賴的package包/類
/**
*
* Scp file from remote server
*
* @param host
* @param user
* @param password
* @param remoteFile
* @param localFile
* @throws JSchException
* @throws IOException
*/
public void scpFileFromRemoteServer(String host, String user, String password, String remoteFile, String localFile) throws JSchException, IOException {
String prefix = null;
if (new File(localFile).isDirectory()) {
prefix = localFile + File.separator;
}
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22);
// username and password will be given via UserInfo interface.
UserInfo userInfo = new UserInformation(password);
session.setUserInfo(userInfo);
session.connect();
// exec 'scp -f remoteFile' remotely
String command = "scp -f " + remoteFile;
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
// get I/O streams for remote scp
OutputStream out = channel.getOutputStream();
InputStream in = channel.getInputStream();
channel.connect();
byte[] buf = new byte[1024];
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
readRemoteFileAndWriteToLocalFile(localFile, prefix, out, in, buf);
session.disconnect();
}
示例8: deleteFile
import com.jcraft.jsch.Session; //導入方法依賴的package包/類
/**
* @param host
* @param user
* @param pwd
* @param remoteFile
*/
public void deleteFile(String host, String user, String pwd,
String remoteFile) {
try {
JSch ssh = new JSch();
Session session = ssh.getSession(user, host, 22);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPassword(pwd);
session.connect();
Channel channel = session.openChannel("exec");
channel.connect();
String command = "rm -rf " + remoteFile;
System.out.println("command: " + command);
// ((ChannelExec) channel).setCommand(command);
channel.disconnect();
session.disconnect();
} catch (JSchException e) {
System.out.println(e.getMessage().toString());
e.printStackTrace();
}
}
示例9: executeSSH
import com.jcraft.jsch.Session; //導入方法依賴的package包/類
private boolean executeSSH(){
//get deployment descriptor, instead of this hard coded.
// or execute a script on the target machine which download artifact from nexus
String command ="nohup java -jar -Dserver.port=8091 ./work/codebox/chapter6/chapter6.search/target/search-1.0.jar &";
try{
System.out.println("Executing "+ command);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
Session session=jsch.getSession("rajeshrv", "localhost", 22);
session.setPassword("rajeshrv");
session.setConfig(config);
session.connect();
System.out.println("Connected");
ChannelExec channelExec = (ChannelExec)session.openChannel("exec");
InputStream in = channelExec.getInputStream();
channelExec.setCommand(command);
channelExec.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
int index = 0;
while ((line = reader.readLine()) != null) {
System.out.println(++index + " : " + line);
}
channelExec.disconnect();
session.disconnect();
System.out.println("Done!");
}catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}
示例10: executeCommandNoResponse
import com.jcraft.jsch.Session; //導入方法依賴的package包/類
public static void executeCommandNoResponse( Session sessionObj, String command )
throws JSchException, IOException
{
logger.debug( "Starting to execute command [" + maskedPasswordString( command ) + "]" );
if ( sessionObj != null && command != null && !"".equals( command ) )
{
Channel channel = null;
try
{
channel = sessionObj.openChannel( "exec" );
( (ChannelExec) channel ).setCommand( command );
channel.setInputStream( null );
( (ChannelExec) channel ).setErrStream( System.err );
channel.getInputStream();
channel.connect();
/* We do not care about whether the command succeeds or not */
if ( channel.isClosed() && channel.getExitStatus() != 0 )
{
logger.debug( "Command exited with error code " + channel.getExitStatus() );
}
}
catch ( Exception e )
{
logger.error( "Received exception during command execution", e );
}
finally
{
if ( channel != null && channel.isConnected() )
{
channel.disconnect();
}
logger.debug( "End of execution of command [" + maskedPasswordString( command ) + "]" );
}
}
}
示例11: executeCommandNoResponse
import com.jcraft.jsch.Session; //導入方法依賴的package包/類
public static void executeCommandNoResponse( Session sessionObj, String command )
throws JSchException, IOException
{
logger.debug( "Starting to execute command [" + command + "]" );
if ( sessionObj != null && command != null && !"".equals( command ) )
{
Channel channel = null;
try
{
channel = sessionObj.openChannel( "exec" );
( (ChannelExec) channel ).setCommand( command );
channel.setInputStream( null );
( (ChannelExec) channel ).setErrStream( System.err );
channel.getInputStream();
channel.connect();
/* We do not care about whether the command succeeds or not */
if ( channel.isClosed() && channel.getExitStatus() != 0 )
{
logger.debug( "Command exited with error code " + channel.getExitStatus() );
}
}
catch ( Exception e )
{
logger.error( "Received exception during command execution", e );
}
finally
{
if ( channel != null && channel.isConnected() )
{
channel.disconnect();
}
logger.debug( "End of execution of command [" + command + "]" );
}
}
}
示例12: executeCommand
import com.jcraft.jsch.Session; //導入方法依賴的package包/類
public int executeCommand(boolean setPty, String command, CommandResultConsumer consumer) {
Session ssh = SshUtil.getInstance().createSshSession(username, hostname);
int resultCode = 255;
try {
ssh.connect();
LOGGER.debug("Connected to ssh console");
ChannelExec channel = (ChannelExec) ssh.openChannel("exec");
channel.setPty(setPty);
channel.setCommand(command);
channel.setInputStream(null);
channel.setOutputStream(System.err);
LOGGER.debug("Executing command: '{}'", command);
channel.connect();
try {
if (consumer != null) {
consumer.consume(channel.getInputStream());
}
} catch (IOException ex) {
throw new RuntimeException("Unable to read console output", ex);
} finally {
channel.disconnect();
}
resultCode = channel.getExitStatus();
} catch (JSchException x) {
LOGGER.error("Error SSH to " + username + "@" + hostname, x);
} finally {
ssh.disconnect();
}
return resultCode;
}
示例13: executeCmd
import com.jcraft.jsch.Session; //導入方法依賴的package包/類
public StringPair executeCmd(String USERNAME,String PASSWORD,String host,String command)
{
StringPair result = new StringPair();
try
{
JSch jsch = new JSch();
Session session = jsch.getSession(USERNAME, host, port);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(PASSWORD);
session.connect();
ChannelExec channelExec = (ChannelExec)session.openChannel("exec");
InputStream in = channelExec.getInputStream();
channelExec.setCommand(command);
channelExec.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
//while((line = reader.readLine()) != null)
result.hostName = reader.readLine();
result.ip=reader.readLine();
reader.close();
int exitStatus = channelExec.getExitStatus();
channelExec.disconnect();
session.disconnect();
if(exitStatus < 0){
System.out.println("Done, but exit status not set!");
}
else if(exitStatus > 0){
System.out.println("Done, but with error!");
}
else{
System.out.println("Done!");
}
return result;
}
catch(Exception e)
{
System.err.println("Error: " + e);
return result;
}
}
示例14: create
import com.jcraft.jsch.Session; //導入方法依賴的package包/類
@Override
public Channel create(final ChannelSessionKey key) throws Exception {
Session session;
synchronized (sessionMap) {
session = sessionMap.get(key);
if (session == null || !session.isConnected()) {
session = prepareSession(key.remoteSystemConnection);
session.connect();
sessionMap.put(key, session);
LOGGER.debug("session {} created and connected!", key);
}
}
return session.openChannel(key.channelType.getChannelType());
}
示例15: openExecChannel
import com.jcraft.jsch.Session; //導入方法依賴的package包/類
protected Channel openExecChannel(final ProcessContext context, final Session session, final String command) throws JSchException {
ChannelExec channel = (ChannelExec) session.openChannel("exec");
channel.setCommand(command);
session.setTimeout(context.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
if (!context.getProperty(USE_KEEPALIVE_ON_TIMEOUT).asBoolean()) {
session.setServerAliveCountMax(0); // do not send keepalive message on SocketTimeoutException
}
return channel;
}