Vivek S
Vivek S

Reputation: 53

How to execute Multiple commands

I want to:

  1. Log in to putty using Hostname, username, password and port number. This I have achieved.
  2. Once I logged in, I want to connect to server1. Usually in putty we connect using ssh command (ssh user@server1).
  3. Once I connected to that server.I need to run multiple commands like:

df -kh ps -ef|grep www

  1. And after executing above commands, I need to log out from server1 and need to log in to server2.

How can I do it in JSCH?

JSch jsch=new JSch();

Session session=jsch.getSession(remoteHostUserName, RemoteHostName, remoteHostPortNo);
session.setPassword(remoteHostpassword);

Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);

System.out.println("Please wait...");
session.connect();
System.out.println("Connected "+remoteHostUserName+"@"+RemoteHostName);

ChannelExec channel=(ChannelExec) session.openChannel("shell");
BufferedReader in=new BufferedReader(new InputStreamReader(channel.getInputStream()));

channel.setCommand("df -kh");
channel.setCommand("pwd");
channel.connect();

Upvotes: 2

Views: 3779

Answers (3)

Monis Majeed
Monis Majeed

Reputation: 1378

You can run multiple commands by using below approach

put all the commands in a string separated by ;

"command1;command2...."

Upvotes: 0

FatherMathew
FatherMathew

Reputation: 990

In order to create an interactive session, you can refer the Example class provided jsch developers.

http://www.jcraft.com/jsch/examples/UserAuthKI.java

Create the Channel object as an instance of Shell ie

  Channel channel=session.openChannel("shell");

And then set the Input and Output Streams for that Channel object.

  channel.setInputStream(System.in);
  channel.setOutputStream(System.out);

And then connect the channel.

This way, after each comand execution, the channel won't be closed and the state of the previous command can be persisted.

Using the above code, you can create an interactive session in your console

Upvotes: 0

blafasel
blafasel

Reputation: 1121

Try ChannelShell channel = (ChannelShell) session.openChannel("shell"); setup inputStream and outputStream and subsequently perform the following loop:

  • write into the connected inputStream and flush it
  • read from the connected outputStream

This way you can even construct your second commands based on the outcome of the first one.

Upvotes: 1

Related Questions