Providing input/subcommands to command executed over SSH with JSch - java

I'm trying to manage router via Java application using Jcraft Jsch library.
I'm trying to send Router Config via TFTP server. The problem is in my Java code because this works with PuTTY.
This my Java code:
int port=22;
String name ="R1";
String ip ="192.168.18.100";
String password ="root";
JSch jsch = new JSch();
Session session = jsch.getSession(name, ip, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
System.out.println("Establishing Connection...");
session.connect();
System.out.println("Connection established.");
ChannelExec channelExec = (ChannelExec)session.openChannel("exec");
InputStream in = channelExec.getInputStream();
channelExec.setCommand("enable");
channelExec.setCommand("copy run tftp : ");
//Setting the ip of TFTP server
channelExec.setCommand("192.168.50.1 : ");
// Setting the name of file
channelExec.setCommand("Config.txt ");
channelExec.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
int index = 0;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
System.out.println(line);
}
session.disconnect();
I get
Line has an invalid autocommand '192.168.50.1'
The problem is how can I run those successive commands.

Calling ChannelExec.setCommand multiple times has no effect.
And even if it had, I'd guess that the 192.168.50.1 : and Config.txt are not commands, but inputs to the copy run tftp : command, aren't they?
If that's the case, you need to write them to the command input.
Something like this:
ChannelExec channel = (ChannelExec) session.openChannel("exec");
channelExec.setCommand("copy run tftp : ");
OutputStream out = channelExec.getOutputStream();
channelExec.connect();
out.write(("192.168.50.1 : \n").getBytes());
out.write(("Config.txt \n").getBytes());
out.flush();
In general, it's always better to check if the command has better "API" than feeding the commands to input. Commands usually have command-line arguments/switches that serve the desired purpose better.
A related question: Provide inputs to individual prompts separately with JSch.

Related

Unable to access the cmd prompt in remote machine using openchannel in java

I'm trying to access the cmd prompt in administrator mode and run a batch file in the remote machine,but right now I'm not able to access the cmd prompt through openchannel. Did anybody tried to access it from remote machine in java?
Here is the code
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
session = jsch.getSession(user, ip, 22);
session.setPassword(password);
session.setTimeout(timeOut);
session.setConfig(config);
session.connect();
System.out.println("session connected");
//open command prompt to run the command = "C:\\executeBatchFile.bat" file
Channel channel = (ChannelExec) session.openChannel("exec");
((ChannelExec)channel).setCommand("cmd.exe /c \"echo %cd%\"\\executeBatchFile.bat");
channel.connect();
InputStream outputstream_from_the_channel = channel.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(outputstream_from_the_channel));
String jarOutput;
while ((jarOutput = reader.readLine()) != null)
{
System.out.println("Inside while loop");
System.out.println(jarOutput + "\n");
}
reader.close();
session.disconnect();
Expected behavior :set command should run as an administrator(though I have logged in as admin),come back to the c:drive (cd) and execute the batch file ie; C:executeBatchFile.bat
Actual behaviour : command gives the user path(not as admin) when I print the jarOutput. ie; C:\Users\Admin\executeBatchFile.bat
could you suggest any solution on the same?
This has been resolved using PsExec command instead of JSCH
String pscommand=E:\\Tool\\psexec -u user -p pwd \\\\ip -s -d cmd.exe /c C:\\executescript.bat
process = Runtime.getRuntime().exec(pscommand);
InputStream es = process.getErrorStream();
BufferedReader errReader = new BufferedReader(new InputStreamReader(es));
String line;
// Read STDOUT into a buffer.
while ((line = errReader.readLine()) != null)
{
system.out.println(line);
}
Could any one tell me how to open the cmd prompt in administrator mode(I logged in using admin credentials only but still it does not open in admin mode).Here I need to run the script in administrator.

How to run Jsch multiple commands from shell-channel using String input instead of console

I am writing a program using JSch library, and have to open a shell channel and execute few commands that are stored in String.
I need to feed the input commands from String variable rather than console.
I have come across a post Jsch : Command Output unavailable
In code given, its working fine for commands like pwd,whoami etc, but its going for a hang when i am trying to do a sudo -u hiveuser -i.
Here is the code:
public static void main(String[] args) throws Exception
{
JSch jsch = new JSch();
String host = "my.host.server";
String user = "myLoginId";
String pswd = "myPASSword";
Session session=jsch.getSession(user,host, 22);
session.setPassword(pswd);
session.setConfig("StrictHostKeyChecking", "no");
session.setConfig("PreferredAuthentications","publickey,keyboard-interactive,password");
session.connect();
System.out.println("Connected");
Channel channel = session.openChannel("shell");
OutputStream ops = channel.getOutputStream();
PrintStream ps = new PrintStream(ops);
channel.connect();
ps.println("sudo -iu hiveuser");
ps.println(pswd);
ps.println("hive");
ps.println("desc table myHiveTable;");
ps.flush();
ps.close();
InputStream in = channel.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
System.out.println("Opening...");
String jarOutput;
while ((jarOutput = reader.readLine()) != null)
System.out.println(jarOutput);
reader.close();
channel.disconnect();
session.disconnect();
}
You could try echoing in the password:
echo password | sudo -iu hiveuser --stdin

'Echo' linux command is not working through Java Code

I am trying to execute a simple linux command to append some text to a file in remote server through my java code. But it isn't working. When I run the same command in the linux box it works fine.
try {
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
Session sessionwrite = jsch.getSession(user2, host2, 22);
sessionwrite.setPassword(password2);
sessionwrite.setConfig(config);
sessionwrite.connect();
System.out.println("Connected");
Channel channel = sessionwrite.openChannel("exec");
BufferedReader in = new BufferedReader(new InputStreamReader(
channel.getInputStream()));
String command = "echo \"hello\" >> welcome.txt";
((ChannelExec) channel).setCommand(command);
System.out.println("done");
}
Channel channel = sessionwrite.openChannel("exec");
BufferedReader in = new BufferedReader(new InputStreamReader(
channel.getInputStream()));
String command = "echo \"hello\" >> welcome.txt";
((ChannelExec) channel).setCommand(command);
System.out.println("done");
You're missing the call to channel.connect(). connect() is the method which actually sends the request to the remote server to invoke the command. You should also call channel.disconnect() when finished with the channel to terminate it. Your code might look something like this:
Channel channel = sessionwrite.openChannel("exec");
BufferedReader in = new BufferedReader(new InputStreamReader(
channel.getInputStream()));
String command = "echo \"hello\" >> welcome.txt";
((ChannelExec) channel).setCommand(command);
channel.connect();
channel.disconnect();
System.out.println("done");
I'll add that, in this particular example, there's no reason to open an input stream on the exec channel's standard input, so you could leave that line out.

JSCH execute command on windows machine and take the output

Here i am executing command on remote windows server from my local windows machine with below code . But i am getting error as
"Unable to execute command or shell on remote system: Failed to
Execute process."
can anybody help me here to come out of this problem?
String user = username;
String pass = password;
String host = ip;
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPassword(pass);
session.connect();
Channel channel = session.openChannel("exec");
channel.connect();
((ChannelExec)channel).setCommand("cmd.exe /c \"echo %cd%\"");
InputStream outputstream_from_the_channel = channel.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(outputstream_from_the_channel));
String jarOutput;
System.out.println("1");
while ((jarOutput = reader.readLine()) != null) {
System.out.println("Inside while loop");
System.out.println(jarOutput + "\n");
}
System.out.println("2");
reader.close();
You need to install cygwin on the host (String host = ip) windows to use jsch.
Follow this site: https://dbaportal.eu/2015/03/05/installing-openssh-cygwin-1-7-35-on-windows-2012-r2/

SSH Output always empty

I've been trying to figure out this problem for hours now and I cant seem to figure it out. I'm trying to use JSch to SSH to a Linux computer from an Android phone. The commands always work fine but the output of the channel is usually empty. Sometimes it displays the output but most of the time it doesn't. Here's the code that I found online.
String userName = "user";
String password = "test123";
String connectionIP = "192.168.1.13";
JSch jsch = new JSch();
Session session;
session = jsch.getSession(userName, connectionIP, 22);
session.setPassword(password);
// Avoid asking for key confirmation
Properties prop = new Properties();
prop.put("StrictHostKeyChecking", "no");
session.setConfig(prop);
session.connect();
// SSH Channel
ChannelExec channelssh = (ChannelExec) session.openChannel("exec");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
channelssh.setOutputStream(baos);
// Execute command
channelssh.setCommand("ls");
channelssh.connect();
channelssh.disconnect();
RESULT = baos.toString();
RESULT is usually empty. If I change the command to mkdir or something of that nature the files show up on the Linux computer which leads me to believe that the command part is working correctly. The problem seems to lie within the ByteArrayOutputStream. I've also tested the connectionip, username and password on a different computer through Terminal so I know the credentials are correct. I've Googled this problem to death, any input would help me out significantly!
Found the answer I was reading the wrong stream. Heres the proper code for others with this problem.
InputStream inputStream = channelssh.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null)
{
stringBuilder.append(line);
stringBuilder.append('\n');
}
return stringBuilder.toString();
The exec-channel will be run on the other thread, so you need to wait for its termination before invoking Channel#disconnect().

Categories