简体   繁体   中英

Command fails when executed through Runtime.exec() but works when executed manually at Raspberry Pi (Linux)

When I try to execute a set of commands through Runtime.exec() in Java, some of them don't work. Nevertheless, when I manually execute the same commands in the terminal, they all work fine. I made sure to copy the exact same commands and they only work when executed manually. What can be causing the problem?

Here's my code:

rt = Runtime.getRuntime();
rt.exec("sudo wpa_cli -i " + ifName + " remove_network 0"); //Always removes network 0, in case it already exists
Thread.sleep(250);
rt.exec("sudo wpa_cli -i " + ifName + " add_network 0");
Thread.sleep(250);
rt.exec("sudo wpa_cli -i " + ifName + " set_network 0 ssid '\"" + SSID + "\"'");//This command only works when executed manually
Thread.sleep(250);
rt.exec("sudo wpa_cli -i " + ifName + " set_network 0 psk '\"" + Pass + "\"'");//This command only works when executed manually
Thread.sleep(250);
rt.exec("sudo wpa_cli -i " + ifName + " select_network 0");

The commands where I input the SSID and Password are the ones causing trouble. ifName is the name of the NIC I am using.

Note that I added several Thread.sleep() because I wasn't sure if the commands had time to finish executing before I called the next one (as this is configuring a network and connecting to it, I really didn't know). Maybe they are completely useless, but I added them just in case.

EDIT: I know this is not related to quote duplication because I already tried removing the quotes and the code still doesn't work. I keep getting the same FAIL message from the console.

Thanks @user140547 for all your help!

It ended up working by executing rt.exec(new String[] {"sudo", "wpa_cli", "-i", ifName, "set_network", "0", "psk", "\\""+Pass+"\\""}); . It looks like when executing the command manually you have to put the password in between simple and double quotes, (eg: '"ActualPassword"' ) but when using rt.exec() absolutely no simple quotes should be used and you should, actually, write down the double quotes.

So I guess the question didn't have to do with quote duplication after all, as I ended up having to write the quotes down. I'm still not sure though why this happens.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM