I've connected two machines in virtual box. I know that the machines are connected because I was able to detect the os of the target windows machine
Aim: Use one machine to shutdown the target windows machine using a java program which accepts a user input: ip
Problem: When the program executes it skips
runtime.exec("shutdown /m /t0 \\" +ip);
Therefore it does not shutdown the targeted computer.
Question: Why is this happening and how can I solve the issue?
import java.io.IOException;
import java.util.Scanner;
public class RemoteShutdown
{
/*Shutdown user's computer*/
public void shutdown(String ip )
{
Runtime runtime = Runtime.getRuntime();
try
{
runtime.exec("shutdown /s /m \\" +ip);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception
{
Scanner scanner = new Scanner(System.in);
RemoteShutdown shutDown = new RemoteShutdown();
System.out.print("Enter computer IP: ");
String IP = scanner.next().trim();
shutDown.shutdown(IP);
}
}
relative paths are usually a bad idea in runtime.exec
. You have little control of the path; a better option would be to fetch the windows home dir via System.getenv
and craft your own route to C:\Windows\System32, or wherever 'shutdown.exe' lives.
Usually this needs admin access, so what you want may be impossible, or may requiring launching java with admin rights.
Generally, don't use exec, but use ProcessBuilder
. Trying to navigate how args are split is rather confusing with just the basic exec
.
In java, \
in a string is an escape single. "\\"
is a string containing only one backslash , but you want to send 2 backslashes to windows here, so, in java, you'd write "\\\\" + ip
.
exec returns a Process object, and you tell it to combine output and error, and then you can fetch the output and error streams. This helps a lot: In this case, no doubt shutdown.exe
is telling you that the specification of the other computer is erroneous (due to, effectively, a missing backslash), but you never read this data. A web search for 'ProcessBuilder java example read output' will probably get you multiple in-depth posts.
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.