java执行命令无返回,Java的执行exec()不返回预期的管道'连接的命令结果

I'm calling command line programs connected by pipes. All this works on Linux for sure.

My method:

protected String execCommand(String command) throws IOException {

String line = null;

if (command.length() > 0) {

Process child = Runtime.getRuntime().exec(command);

InputStream lsOut = child.getInputStream();

InputStreamReader r = new InputStreamReader(lsOut);

BufferedReader in = new BufferedReader(r);

String readline = null;

while ((readline = in.readLine()) != null) {

line = line + readline;

}

}

return line;

}

If I'm calling some cat file | grep asd, I'm getting the expected result. But not all commands works correctly. For example with this:

cat /proc/cpuinfo | wc -l

or this:

cat /proc/cpuinfo | grep "model name" | head -n 1 | awk -F":" '{print substr($2, 2, length($2))}

the method will return null. I'm guessing this problem depends on output formatting commands like head, tail, wc, etc. How I can work around this problem and get the final result of the output?

解决方案

Still didn't found proper solution to execute piped commands with Runtime.exec, but found a workaround. I've simply wrote these scripts to separate bash files. Then Runtime.exec calls these bash scripts and gets expected result.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Java JSch可以连接到远程机器并执行命令,下面是一个示例代码,可以更改用户并执行多条命令: ```java import com.jcraft.jsch.*; public class SSHExample { public static void main(String[] args) { String user = "username"; // 远程机器的用户名 String password = "password"; // 远程机器的密码 String host = "remote_host"; // 远程机器的IP地址或域名 int port = 22; // 远程机器的SSH端口号,默认是22 try { JSch jsch = new JSch(); Session session = jsch.getSession(user, host, port); session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); // 更改用户 String command = "sudo su - otheruser"; // 需要更改的用户 Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); channel.connect(); // 输入密码 String sudoPassword = "otheruser_password"; // 需要输入的密码 channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand("echo \"" + sudoPassword + "\" | sudo -S ls"); channel.connect(); // 执行多条命令 String[] commands = {"cd /path/to/directory", "ls -l", "date"}; for (String cmd : commands) { channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(cmd); channel.setInputStream(null); ((ChannelExec) channel).setErrStream(System.err); channel.connect(); channel.disconnect(); } session.disconnect(); } catch (JSchException e) { e.printStackTrace(); } } } ``` 在这个示例中,我们先通过JSch连接到远程机器,然后使用`sudo su - otheruser`命令切换到需要更改的用户,接着使用`echo`命令管道符号`|`输入密码,最后使用`openChannel`方法打开一个新的`Channel`并执行多条命令
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值