I am using java 1.7 and trilead ssh library to execute the commands in Linux environment.
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.trilead.ssh2.ChannelCondition;
import com.trilead.ssh2.Connection;
import com.trilead.ssh2.Session;
public class TestSSH
{
private static final String ipAddress = "ipaddress";
private static final String username = "username";
private static final String password = "password";
private static final int port = 22;
private static Connection connection;
private static Session mySession;
private static OutputStream inStream;
private static InputStream outStream;
private static InputStream errStream;
public static void main(String[] args)
throws IOException
{
String prompt = initPrompt();
}
private static String initPrompt()
throws IOException
{
boolean isAuthenticated = false;
String myPrompt = "";
connection = new Connection(ipAddress, port);
connection.connect(null, 30 * 1000, 0);
isAuthenticated =
connection.authenticateWithPassword(username, password);
if (!isAuthenticated)
{
System.exit(1);
}
System.out.println(" Authenticated !....");
mySession = connection.openSession();
mySession.requestPTY("dumb", 256, 24, 0, 0, null);
mySession.startShell();
inStream = mySession.getStdin();
outStream = mySession.getStdout();
errStream = mySession.getStdout();
try
{
writeInput(inStream, "ls -ltr /;echo [[COMMAND_EXIT_CODE=$?]];");
flushOutput(inStream);
int len = outStream.read(buffer);
StringBuilder outputString = new StringBuilder();
if (len > 0)
{
outputString.append(new String(buffer, 0, len, "utf-8"));
output.append(outputString.toString());
}
}
}
I am executing the the program in the Linux mahcine Redhat 6.4 OS( as localhost i.e source and destination are same) and the getting the below output.
output:
com.xxx.yyy output: ^M
Last login: Fri Jun 12 09:19:03 2015 from x.x.x.x^M^M
prompt-1:~ # ^M
SC-1:~ # echo COMMAND^M
COMMAND^M
prompt-1:~ #
Fri Jun 12 09:19:03 2015 from x.x.x.x^M^M
prompt-1:~ # ^M
prompt-1:~ # echo COMMAND^M
COMMAND^M
prompt-1:~ #
I am expecting the output as without ^M(line feed) so that i can fetch the prompt expected output. Can anybody tell me the reason why ^M is appended in the output. I am not getting ^M in other machines. In other machines the occurence is very rare.
Is there any configuration i needs to be change in my OS to overcome this issue? Is there any thing i have to configure in java to overcome this? Any help is appreciated..