Search code examples
javasshjschremote-connection

Find remote os name via Jsch in Java


I am using Jsch to connect to a remote machine in my Java Code. I want to execute a command on the remote machine. On windows I need to append "cmd /c" before the command to be executed, but for linux this is not needed. So I want to know which OS I have connected to via Jsch. One way that comes to my mind is run some simple windows specific command, if it works it is windows. If it doesn't it is some other OS. And then I will run my actual command. Is there a way to avoid this? Some other way to execute commands OS independently over SSH via Jsch?


Solution

  • There is no pure scientific way to do this. However you can find a lot of heuristics. Once upon a time we used command pwd as a first command and parsed its output. It prints something reasonable on Unix systems and error message on windows.

    However now I can suggest you to use the following command:

    echo $PATH %PATH%

    This will work on all operating systems. Then you can analyze the path it prints. For example the direction of slashes / or \ can tell you what OS is this.