【发布时间】:2015-09-03 19:46:20
【问题描述】:
我正在使用 java 1.7 和 trilead ssh 库在 Linux 环境中执行命令。
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());
}
}
}
我正在 Linux mahcine Redhat 6.4 操作系统中执行程序(作为本地主机,即源和目标相同)并获得以下输出。
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:~ #
我希望输出没有 ^M(换行),以便我可以获取提示的预期输出。谁能告诉我输出中附加 ^M 的原因。我没有在其他机器上得到 ^M。在其他机器中这种情况非常罕见。
我需要在我的操作系统中更改任何配置来解决这个问题吗? 我必须在java中配置什么来克服这个问题吗? 任何帮助表示赞赏..
【问题讨论】:
-
有什么理由不能简单地解析出
^M? -
@Tim 解析是不同的方面,但我想知道这背后的原因。谢谢
-
与stackoverflow.com/questions/5843495/… 类似的答案。 ^M 将是回车符。 System.lineSeparator() 设置为什么?您可以使用 System.out.println("Line sep: " + org.apache.commons.codec.binary.Hex.encodeHexString(System.lineSeparator().getBytes())); 查看 Hex 值
-
请说明在某些情况下附加^M的原因
标签: java linux bash operating-system