本文整理匯總了Java中com.jcraft.jsch.ChannelExec類的典型用法代碼示例。如果您正苦於以下問題:Java ChannelExec類的具體用法?Java ChannelExec怎麽用?Java ChannelExec使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
ChannelExec類屬於com.jcraft.jsch包,在下文中一共展示了ChannelExec類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: executeCommand
import com.jcraft.jsch.ChannelExec; //導入依賴的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;
}
}
示例2: connect
import com.jcraft.jsch.ChannelExec; //導入依賴的package包/類
/**
* Connect to a remote host and return a channel (session and jsch are set)
*/
Channel connect(String channleType, String sshCommand) throws Exception {
JSch.setConfig("StrictHostKeyChecking", "no"); // Not recommended, but useful
jsch = new JSch();
// Some "reasonable" defaults
if (Gpr.exists(defaultKnownHosts)) jsch.setKnownHosts(defaultKnownHosts);
for (String identity : defaultKnownIdentity)
if (Gpr.exists(identity)) jsch.addIdentity(identity);
// Create session and connect
if (debug) Gpr.debug("Create conection:\n\tuser: '" + host.getUserName() + "'\n\thost : '" + host.getHostName() + "'\n\tport : " + host.getPort());
session = jsch.getSession(host.getUserName(), host.getHostName(), host.getPort());
session.setUserInfo(new SshUserInfo());
session.connect();
// Create channel
channel = session.openChannel(channleType);
if ((sshCommand != null) && (channel instanceof ChannelExec)) ((ChannelExec) channel).setCommand(sshCommand);
return channel;
}
示例3: executeCommand
import com.jcraft.jsch.ChannelExec; //導入依賴的package包/類
public void executeCommand(final String command) throws IOException { // Cliente SSH final
JSch jsch = new JSch();
Properties props = new Properties();
props.put("StrictHostKeyChecking", "no");
try {
Session session = jsch.getSession(user, host, 22);
session.setConfig(props);
session.setPassword(password);
session.connect();
java.util.logging.Logger.getLogger(RemoteShell.class.getName())
.log(Level.INFO, session.getServerVersion());
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
// Daqui para baixo é somente para imprimir a saida
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));
}
if (channel.isClosed()) {
if (in.available() > 0) {
continue;
}
System.out
.println("exit-status: " + channel.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
}
}
channel.disconnect();
session.disconnect();
} catch (JSchException ex) {
java.util.logging.Logger.getLogger(RemoteShell.class.getName())
.log(Level.SEVERE, null, ex);
}
}
示例4: executeCommandReader
import com.jcraft.jsch.ChannelExec; //導入依賴的package包/類
/**
* Execute an ssh command on the server, without closing the session
* so that a Reader can be returned with streaming data from the server.
*
* @param command the command to execute.
* @return a Reader with streaming data from the server.
* @throws IOException if it is so.
* @throws SshException if there are any ssh problems.
*/
@Override
public synchronized Reader executeCommandReader(String command) throws SshException, IOException {
if (!isConnected()) {
throw new IllegalStateException("Not connected!");
}
try {
Channel channel = connectSession.openChannel("exec");
((ChannelExec)channel).setCommand(command);
InputStreamReader reader = new InputStreamReader(channel.getInputStream(), "utf-8");
channel.connect();
return reader;
} catch (JSchException ex) {
throw new SshException(ex);
}
}
示例5: connectAndExecute
import com.jcraft.jsch.ChannelExec; //導入依賴的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: execute
import com.jcraft.jsch.ChannelExec; //導入依賴的package包/類
@Override
public CliProcess execute(String command)
{
try {
Session session = createSession();
LOGGER.info("Executing on {}@{}:{}: {}", session.getUserName(), session.getHost(), session.getPort(), command);
ChannelExec channel = (ChannelExec) session.openChannel("exec");
channel.setCommand(command);
JSchCliProcess process = new JSchCliProcess(session, channel);
process.connect();
return process;
}
catch (JSchException | IOException exception) {
throw new RuntimeException(exception);
}
}
示例7: sendCommand
import com.jcraft.jsch.ChannelExec; //導入依賴的package包/類
public String sendCommand(String command) throws JSchException, IOException {
StringBuilder outputBuffer = new StringBuilder();
Channel channel = sesConnection.openChannel("exec");
((ChannelExec)channel).setCommand(command);
InputStream commandOutput = channel.getInputStream();
channel.connect();
int readByte = commandOutput.read();
while(readByte != 0xffffffff)
{
outputBuffer.append((char)readByte);
readByte = commandOutput.read();
}
channel.disconnect();
return outputBuffer.toString();
}
示例8: runCommand
import com.jcraft.jsch.ChannelExec; //導入依賴的package包/類
public String runCommand(String command) throws Exception {
Log.i(TAG + " runCommand", command);
StringBuilder outputBuffer = new StringBuilder();
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
channel.connect();
InputStream commandOutput = channel.getInputStream();
int readByte = commandOutput.read();
while (readByte != 0xffffffff) {
outputBuffer.append((char) readByte);
readByte = commandOutput.read();
}
channel.disconnect();
String output = outputBuffer.toString();
Log.i(TAG + " runCommand", command + ", output: " + output);
return output;
}
示例9: createTCPProxy
import com.jcraft.jsch.ChannelExec; //導入依賴的package包/類
private void createTCPProxy() {
try {
final String cleanCommand = String.format("sudo docker ps -a | grep 'hours ago' | awk '{print $1}' | xargs --no-run-if-empty sudo docker rm",
containerName,
this.targetHost,
this.targetPort,
sourceIPs,
ImageRegistry.get().tcpProxy());
LOGGER.info("Establishing SSH shell");
ssh = SshUtil.getInstance()
.createSshSession(TestConfiguration.proxyHostUsername(), getProxyHost());
ssh.connect();
LOGGER.debug("Connected to ssh console");
final ChannelExec cleanChannel = (ChannelExec) ssh.openChannel("exec");
cleanChannel.setPty(true);
cleanChannel.setCommand(cleanCommand);
cleanChannel.setInputStream(null);
cleanChannel.setOutputStream(System.err);
LOGGER.debug("Executing command: '{}'", cleanCommand);
cleanChannel.connect();
cleanChannel.disconnect();
final String command = String.format("sudo docker run -it --name %s --net=host --rm -e AB_OFF=true -e TARGET_HOST=%s -e TARGET_PORT=%s -e TARGET_VIA=%s %s",
containerName,
this.targetHost,
this.targetPort,
sourceIPs,
ImageRegistry.get().tcpProxy());
LOGGER.info("Establishing SSH shell");
ssh = SshUtil.getInstance()
.createSshSession(TestConfiguration.proxyHostUsername(), getProxyHost());
ssh.connect();
LOGGER.debug("Connected to ssh console");
final ChannelExec channel = (ChannelExec) ssh.openChannel("exec");
channel.setPty(true);
channel.setCommand(command);
channel.setInputStream(null);
channel.setOutputStream(System.err);
LOGGER.debug("Executing command: '{}'", command);
channel.connect();
final LineIterator li = IOUtils.lineIterator(new InputStreamReader(channel.getInputStream()));
final Pattern portLine = Pattern.compile(".*Listening on port ([0-9]*).*$");
listenPort = 0;
while (li.hasNext()) {
final String line = li.next();
LOGGER.trace("Shell line: {}", line);
final Matcher m = portLine.matcher(line);
if (m.matches()) {
listenPort = Integer.parseInt(m.group(1));
LOGGER.info("Connection listening on port {}", listenPort);
break;
}
}
channel.disconnect();
} catch (final JSchException | IOException e) {
LOGGER.debug("Error in creating SSH connection to proxy host", e);
throw new IllegalStateException("Cannot open SSH connection", e);
}
}
示例10: scpFileFromRemoteServer
import com.jcraft.jsch.ChannelExec; //導入依賴的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();
}
示例11: testSecureCopyFile
import com.jcraft.jsch.ChannelExec; //導入依賴的package包/類
@Test
public void testSecureCopyFile() throws JSchException, IOException {
final JschBuilder mockJschBuilder = mock(JschBuilder.class);
final JSch mockJsch = mock(JSch.class);
final Session mockSession = mock(Session.class);
final ChannelExec mockChannelExec = mock(ChannelExec.class);
final byte [] bytes = {0};
final ByteArrayOutputStream out = new ByteArrayOutputStream();
when(mockChannelExec.getInputStream()).thenReturn(new TestInputStream());
when(mockChannelExec.getOutputStream()).thenReturn(out);
when(mockSession.openChannel(eq("exec"))).thenReturn(mockChannelExec);
when(mockJsch.getSession(anyString(), anyString(), anyInt())).thenReturn(mockSession);
when(mockJschBuilder.build()).thenReturn(mockJsch);
when(Config.mockSshConfig.getJschBuilder()).thenReturn(mockJschBuilder);
when(Config.mockRemoteCommandExecutorService.executeCommand(any(RemoteExecCommand.class))).thenReturn(mock(RemoteCommandReturnInfo.class));
final String source = BinaryDistributionControlServiceImplTest.class.getClassLoader().getResource("binarydistribution/copy.txt").getPath();
binaryDistributionControlService.secureCopyFile("someHost", source, "./build/tmp");
verify(Config.mockSshConfig).getJschBuilder();
assertEquals("C0644 12 copy.txt\nsome content\0", out.toString(StandardCharsets.UTF_8));
}
示例12: executeSSH
import com.jcraft.jsch.ChannelExec; //導入依賴的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;
}
示例13: executeCommand
import com.jcraft.jsch.ChannelExec; //導入依賴的package包/類
/**
* Convenience method to execute a command on the given remote session, using the given string
* as part of the error if it fails to run.
*
* @param roboRioSession The ssh session of the roboRio
* @param command The command to execute
* @param errorString The error string to put in the exception if an error occurs. The return
* code will be appended to the end
* @throws JSchException If an ssh error occurs
* @throws IOException Thrown if there is an io error, or if the command fails to run
*/
private void executeCommand(Session roboRioSession, String command, String errorString) throws JSchException, IOException {
// Extract the JRE
m_logger.debug("Running command " + command);
ChannelExec channel = (ChannelExec) roboRioSession.openChannel(EXEC_COMMAND);
channel.setCommand(command);
channel.connect();
int sleepCount = 0;
// Sleep for up to 10 seconds while we wait for the command to execute, checking every 100 milliseconds
do {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
m_logger.warn("Interrupted exception while waiting for command " + command + " to finish", e);
}
} while (!channel.isClosed() && sleepCount++ < 100);
int res = channel.getExitStatus();
if (res != SUCCESS) {
m_logger.debug("Error with command " + command);
throw new IOException(errorString + " " + res);
}
channel.disconnect();
}
示例14: streamOutput
import com.jcraft.jsch.ChannelExec; //導入依賴的package包/類
private void streamOutput(ChannelExec channel, InputStream in)
throws IOException
{
byte[] buf = new byte[1024];
while (true)
{
while (in.available() > 1)
{
int bytesRead = in.read(buf);
if (bytesRead < 0 ) break;
this.out.write(buf);
}
if (channel.isClosed()) break;
sleepForOneSecondAndIgnoreInterrupt();
}
}
示例15: executeCommandNoResponse
import com.jcraft.jsch.ChannelExec; //導入依賴的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 ) + "]" );
}
}
}