简体   繁体   中英

Determine OS from a single command line operation

Introduction:

I have a 'magic' tool that can perform a command line operation on a machine if I provide the IP. The tool knows the OS that machine is using and executes the command on cmd/shell based on whether it is windows/linux and returns the output of the command back blindly.

C:> tool.exe 172.140.56.2 "ipconfig"

Assumptions:

  1. One OS per machine. Tool has no problem executing the command (whether it fails or not is a different problem)
  2. The OS is either windows or linux always.
  3. I determine the OS based on the command result

Problem:

Using this power of being able to execute a command, I want to determine the OS

My Solution:

Execute ipconfig command. If result is

-bash: ipconfig: command not found

It is linux.

Else if it is like this:

Windows IP Configuration
Ethernet adapter Local Area Connection:
...

then Windows.

Question:

I wanted to know if this is a foolproof way of doing this. I want a command which would not fail under certain scenarios. (say cygwin installed on windows allowing linux commands to succeed. Or ipconfig succeeding on linux under some special scneario.)

I can process the command output with some parser, if that helps in any way.

Just to clear any confusion. It can be ANY command. I ust used ipconfig in my example.

If I understood your problem correctly, then uname is the ideal command. If it's any Unix-system (including OSX), it'll return the correct variable, and if it's Windows it'll return command not found or similar.

Safest way to determine Linux/version is

cat /etc/*release

Sample output.

DISTRIB_ID=LinuxMint
DISTRIB_RELEASE=17
DISTRIB_CODENAME=qiana
DISTRIB_DESCRIPTION="Linux Mint 17 Qiana"
NAME="Ubuntu"
VERSION="14.04.1 LTS, Trusty Tahr"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 14.04.1 LTS"
VERSION_ID="14.04"
HOME_URL="http://www.ubuntu.com/"
SUPPORT_URL="http://help.ubuntu.com/"
BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"

Another command that should work is set , which displays name and value of each environment variable. Any shell on Linux supports it (although output is different between csh and bash ). Output from a Windows system would have PROCESSOR_ARCHITECTURE and other standard variables in it (see https://ss64.com/nt/syntax-variables.html ), which are very unlikely to be set in Linux.

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