[英]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. 当我尝试通过Java中的
Runtime.exec()
执行一组命令时,其中一些命令不起作用。 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. 我输入SSID和密码的命令会引起麻烦。
ifName
is the name of the NIC I am using. ifName
是我正在使用的NIC的名称。
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). 请注意,我添加了几个
Thread.sleep()
因为不确定在调用下一个命令之前命令是否有时间完成(因为这是配置网络并连接到它,我真的不知道)。 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. 我不断从控制台收到相同的
FAIL
消息。
Thanks @user140547 for all your help! 感谢@ user140547的所有帮助!
It ended up working by executing rt.exec(new String[] {"sudo", "wpa_cli", "-i", ifName, "set_network", "0", "psk", "\\""+Pass+"\\""});
通过执行
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. 看起来当手动执行命令时,您必须将密码放在单引号和双引号之间(例如:
'"ActualPassword"'
),但是当使用rt.exec()
绝对不应该使用简单的引号,而实际上,写下双引号。
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.
我仍然不确定为什么会这样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.