Java에서 Windows, Linux, macOS 터미널 명령을 실행하고 완전한 결과를 반환하는 방법
게시 됨: 2019-02-26 system command
을 실행하는 것은 상대적으로 간단합니다. 일단 실행을 처음 본 후에는 간단합니다.
여기에는 Runtime 클래스와 Process 클래스의 두 가지 Java 클래스 사용이 포함됩니다. 기본적으로 Runtime 클래스의 exec method
를 사용하여 별도의 프로세스로 명령을 실행합니다.
exec 메서드를 호출하면 하위 프로세스를 관리하기 위한 Process 개체가 반환됩니다. 그런 다음 Process
객체의 getInputStream()
및 getErrorStream()
메서드를 사용하여 명령의 일반 출력과 명령의 오류 출력을 읽습니다. 실행된 명령의 출력으로 수행하는 작업은 전적으로 사용자와 생성 중인 애플리케이션에 달려 있습니다.
ProcessBuilder.start()
및 Runtime.exec
메서드는 기본 프로세스를 만들고 프로세스를 제어하고 이에 대한 정보를 얻는 데 사용할 수 있는 Process
의 하위 클래스 인스턴스를 반환합니다.
Process
클래스는 프로세스에서 입력을 수행하고, 프로세스로 출력을 수행하고, 프로세스가 완료되기를 기다리고, 프로세스의 종료 상태를 확인하고, 프로세스를 소멸(종료)하는 메서드를 제공합니다.
프로세스를 생성하는 방법은 기본 윈도우 프로세스, 데몬 프로세스, Microsoft Windows의 Win16/DOS 프로세스 또는 셸 스크립트와 같은 특정 기본 플랫폼의 특수 프로세스에서 제대로 작동하지 않을 수 있습니다.
기본적으로 생성된 하위 프로세스에는 자체 터미널이나 콘솔이 없습니다. 모든 표준 I/O(예: stdin, stdout, stderr) 작업은 부모 프로세스로 리디렉션되며 getOutputStream()
, getInputStream()
및 getErrorStream()
메서드를 사용하여 얻은 스트림을 통해 액세스할 수 있습니다.
상위 프로세스는 이러한 스트림을 사용하여 하위 프로세스에 입력을 제공하고 출력을 얻습니다. 일부 기본 플랫폼은 표준 입력 및 출력 스트림에 대해 제한된 버퍼 크기만 제공하기 때문에 입력 스트림을 즉시 쓰거나 하위 프로세스의 출력 스트림을 읽지 못하면 하위 프로세스가 차단되거나 교착 상태가 될 수도 있습니다.
다음은 참조용으로 두 가지 간단한 Java 예제입니다.
예-1. Java에서 mkdir, ls -ltra 및 ping 실행
- CrunchifyCommandJava.java 파일 생성
-
mkdir /Users/ashah/Desktop/new-folder
실행 -
ls -ltra /Library
실행 -
ping crunchify.com
실행
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
package crunchify . com . tutorials ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; /** * @author Crunchify.com * Execute Linux commands using Java. We are executing mkdir, ls -ltra and ping in this tutorial */ public class CrunchifyCommandJava { public printOutput getStreamWrapper ( InputStream is , String type ) { return new printOutput ( is , type ) ; } public static void main ( String [ ] args ) { Runtime rt = Runtime . getRuntime ( ) ; CrunchifyCommandJava rte = new CrunchifyCommandJava ( ) ; printOutput errorReported , outputMessage ; try { Process proc = rt . exec ( "mkdir /Users/ashah/Desktop/new-folder" ) ; errorReported = rte . getStreamWrapper ( proc . getErrorStream ( ) , "ERROR" ) ; outputMessage = rte . getStreamWrapper ( proc . getInputStream ( ) , "OUTPUT" ) ; errorReported . start ( ) ; outputMessage . start ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } try { Process proc = rt . exec ( "ls -ltra /Library" ) ; errorReported = rte . getStreamWrapper ( proc . getErrorStream ( ) , "ERROR" ) ; outputMessage = rte . getStreamWrapper ( proc . getInputStream ( ) , "OUTPUT" ) ; errorReported . start ( ) ; outputMessage . start ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } try { Process proc = rt . exec ( "ping crunchify.com" ) ; errorReported = rte . getStreamWrapper ( proc . getErrorStream ( ) , "ERROR" ) ; outputMessage = rte . getStreamWrapper ( proc . getInputStream ( ) , "OUTPUT" ) ; errorReported . start ( ) ; outputMessage . start ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } private class printOutput extends Thread { InputStream is = null ; printOutput ( InputStream is , String type ) { this . is = is ; } public void run ( ) { String s = null ; try { BufferedReader br = new BufferedReader ( new InputStreamReader ( is ) ) ; while ( ( s = br . readLine ( ) ) ! = null ) { System . out . println ( s ) ; } } catch ( IOException ioe ) { ioe . printStackTrace ( ) ; } } } } |
시스템 설정에 따라 위의 프로그램에서 경로를 적절하게 변경하십시오.
Eclipse 콘솔 출력:
위의 프로그램을 Java 응용 프로그램으로 실행하면 비슷한 결과를 볼 수 있습니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
mkdir: /Users/ashah/Desktop/new-file-created.txt: File created total 0 drwxr-xr-x 3 root wheel 96 Aug 17 2018 Compositions drwxr-xr-x@ 2 root wheel 64 Aug 17 2018 GPUBundles drwxr-xr-x 2 root wheel 64 Aug 17 2018 SystemProfiler drwxr-xr-x 2 root wheel 64 Aug 17 2018 ColorPickers -rw-r--r-- 1 root wheel 0 Aug 17 2018 .localized drwxr-xr-x 2 root wheel 64 Aug 17 2018 StartupItems drwxr-xr-x 3 root wheel 96 Aug 17 2018 Speech drwxr-xr-x 4 root wheel 128 Aug 17 2018 Ruby drwxr-xr-x@ 2 root wheel 64 Aug 17 2018 CoreAnalytics drwxr-xr-x 3 root wheel 96 Aug 17 2018 DirectoryServices drwxr-xr-x 5 root wheel 160 Aug 17 2018 WebServer drwxr-xr-x 3 root wheel 96 Aug 17 2018 Perl drwxr-xr-x 2 root wheel 64 Aug 17 2018 ScriptingAdditions drwxr-xr-x 2 root wheel 64 Aug 17 2018 Keyboard Layouts drwxr-xr-x 3 root wheel 96 Aug 17 2018 Graphics drwxr-xr-x 3 root wheel 96 Aug 17 2018 Python drwxr-xr-x 8 root wheel 256 Oct 11 16:51 User Pictures drwxr-xr-x 3 root wheel 96 Oct 11 16:51 Screen Savers drwxr-xr-x 51 root wheel 1632 Oct 11 16:51 Desktop Pictures drwxr-xr-x 2 root wheel 64 Oct 18 18:51 Contextual Menu Items drwxr-xr-x 2 root wheel 64 Oct 18 18:51 Components drwxr-xr-x 5 root wheel 160 Oct 21 16:03 OpenDirectory drwxr-xr-x 2 root wheel 64 Oct 23 20:43 Input Methods drwxr-xr-x 4 root wheel 128 Oct 29 23:49 Video drwxr-xr-x 3 root wheel 96 Nov 5 21:20 Messages drwxr-xr-x@ 3 root wheel 96 Nov 12 22:37 MessageTracer drwxr-xr-x 3 root wheel 96 Nov 12 22:55 CoreMediaIO drwxr-xr-x 3 root wheel 96 Nov 29 23:38 Sandbox drwxr-xr-x 3 root wheel 96 Nov 29 23:38 Filesystems drwxr-xr-x 8 root wheel 256 Nov 29 23:40 Image Capture drwxr-xr-x 4 root wheel 128 Nov 29 23:41 Java drwxr-xr-x 4 root wheel 128 Nov 29 23:41 QuickTime drwxr-xr-x 10 root wheel 320 Nov 29 23:45 Scripts drwxrwxr-t 182 root admin 5824 Nov 29 23:47 Fonts drwxr-xr-x 4 root wheel 128 Nov 29 23:49 QuickLook drwxr-xr-x 4 root wheel 128 Nov 29 23:49 Spotlight drwxr-xr-x 37 root wheel 1184 Nov 29 23:50 Modem Scripts drwxr-xr-x 4 root wheel 128 Feb 11 13:00 ColorSync drwxr-xr-x 4 root wheel 128 Feb 11 13:04 Security drwxr-xr-x 8 root wheel 256 Feb 11 13:04 PDF Services drwxr-xr-x 3 root wheel 96 Feb 11 13:05 Catacomb drwxr-xr-x 9 root wheel 288 Feb 11 13:05 Frameworks drwxr-xr-x 3 root wheel 96 Feb 11 13:05 Automator drwxr-xr-x 10 root wheel 320 Feb 11 13:05 Audio drwxr-xr-x 3 root wheel 96 Feb 11 13:05 Tanium drwxr-xr-x+ 68 root wheel 2176 Feb 11 13:05 . drwxr-xr-x 3 root admin 96 Feb 11 13:05 Developer drwxr-xr-x 8 root wheel 256 Feb 11 13:05 Documentation drwxr-xr-x 4 root wheel 128 Feb 11 13:05 DropboxHelperTools drwxrwxr-x 14 root admin 448 Feb 11 13:07 Receipts drwxr-xr-x 4 root wheel 128 Feb 11 13:07 SystemMigration drwxr-xr-x@ 4 root wheel 128 Feb 11 13:10 StagedExtensions drwxr-xr-x 14 root wheel 448 Feb 11 18:26 Widgets drwxr-xr-x 13 root wheel 416 Feb 11 18:26 Extensions drwxr-xr-x 29 root wheel 928 Feb 11 18:35 .. drwxr-xr-x 9 root wheel 288 Feb 17 12:38 Logs drwxrwxrwt 11 root admin 352 Feb 22 13:29 Caches drwxr-xr-x 11 root wheel 352 Feb 22 13:36 LaunchAgents drwxr-xr-x 2 root wheel 64 Feb 22 13:36 PreferencePanes drwxr-xr-x 9 root wheel 288 Feb 22 13:36 Internet Plug-Ins drwxr-xr-t 7 root wheel 224 Feb 22 13:36 PrivilegedHelperTools drwxr-xr-x 18 root wheel 576 Feb 22 13:36 LaunchDaemons drwxr-xr-x 25 root admin 800 Feb 22 16:03 Application Support dr-xr-xr-x 9 root wheel 288 Feb 25 10:24 Printers drwxr-xr-x@ 5 root wheel 160 Feb 25 10:24 Updates drwxr-xr-x 10 root wheel 320 Feb 25 14:12 Keychains drwxr-xr-x 25 root wheel 800 Feb 26 08:07 Managed Preferences drwxr-xr-x 67 root wheel 2144 Feb 26 08:07 Preferences PING crunchify.com (35.197.114.216): 56 data bytes 64 bytes from 35.197.114.216: icmp_seq=0 ttl=54 time=70.275 ms 64 bytes from 35.197.114.216: icmp_seq=1 ttl=54 time=73.876 ms 64 bytes from 35.197.114.216: icmp_seq=2 ttl=54 time=68.134 ms 64 bytes from 35.197.114.216: icmp_seq=3 ttl=54 time=75.951 ms 64 bytes from 35.197.114.216: icmp_seq=4 ttl=54 time=70.205 ms |

예-2.
- CrunchifyRunCommand.java
-
ps -few
명령을 실행하여 시스템에서 실행 중인 모든 프로세스의 목록을 가져옵니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
package crunchify . com . tutorials ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . InputStreamReader ; /** * @author Crunchify.com * Execute ps -few command in Java to get list of all processes */ public class CrunchifyRunCommand { public static void main ( String [ ] args ) { String s = null ; try { // Process provides control of native processes started by ProcessBuilder.start and Runtime.exec. // getRuntime() returns the runtime object associated with the current Java application. Process p = Runtime . getRuntime ( ) . exec ( "ps -few" ) ; BufferedReader stdInput = new BufferedReader ( new InputStreamReader ( p . getInputStream ( ) ) ) ; BufferedReader stdError = new BufferedReader ( new InputStreamReader ( p . getErrorStream ( ) ) ) ; // read the output from the command System . out . println ( "Here is the standard output of the command:\n" ) ; while ( ( s = stdInput . readLine ( ) ) ! = null ) { System . out . println ( s ) ; } // read any errors from the attempted command System . out . println ( "Here is the standard error of the command (if any):\n" ) ; while ( ( s = stdError . readLine ( ) ) ! = null ) { System . out . println ( s ) ; } System . exit ( 0 ) ; } catch ( IOException e ) { System . out . println ( "exception happened - here's what I know: " ) ; e . printStackTrace ( ) ; System . exit ( - 1 ) ; } } } |
Eclipse 콘솔 출력:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
Here is the standard output of the command : UID PID PPID C STIME TTY TIME CMD 0 1 0 0 Fri09PM ? ? 7 : 14.76 / sbin / launchd 0 44 1 0 Fri09PM ? ? 0 : 09.67 / usr / sbin / syslogd 0 45 1 0 Fri09PM ? ? 0 : 12.95 / usr / libexec / UserEventAgent ( System ) 0 49 1 0 Fri09PM ? ? 0 : 04.41 / System / Library / PrivateFrameworks / Uninstall . framework / Resources / uninstalld 0 50 1 0 Fri09PM ? ? 0 : 26.75 / usr / libexec / kextd 0 51 1 0 Fri09PM ? ? 2 : 00.76 / System / Library / Frameworks / CoreServices . framework / Versions / A / Frameworks / FSEvents . framework / Versions / A / Support / fseventsd 0 53 1 0 Fri09PM ? ? 4 : 16.25 / usr / local / jamf / bin / jamf launchDaemon - enforceRestrictions - monitorNetworkStateChanges 0 54 1 0 Fri09PM ? ? 0 : 01.29 / System / Library / PrivateFrameworks / MediaRemote . framework / Support / mediaremoted 55 57 1 0 Fri09PM ? ? 0 : 01.23 / System / Library / CoreServices / appleeventsd -- server 0 58 1 0 Fri09PM ? ? 4 : 21.14 / usr / sbin / systemstats -- daemon 0 60 1 0 Fri09PM ? ? 0 : 41.10 / usr / libexec / configd 0 61 1 0 Fri09PM ? ? 1 : 03.98 / System / Library / CoreServices / powerd . bundle / powerd 0 62 1 0 Fri09PM ? ? 0 : 00.89 / Library / Application Support / JAMF / Jamf . app / Contents / MacOS / JamfDaemon . app / Contents / MacOS / JamfDaemon 0 65 1 0 Fri09PM ? ? 0 : 43.84 / usr / libexec / logd 0 66 1 0 Fri09PM ? ? 0 : 00.02 / usr / libexec / keybagd - t 15 0 73 1 0 Fri09PM ? ? 3 : 26.45 / System / Library / Frameworks / CoreServices . framework / Frameworks / Metadata . framework / Support / mds 240 74 1 0 Fri09PM ? ? 0 : 00.11 / System / Library / CoreServices / iconservicesd 0 75 1 0 Fri09PM ? ? 0 : 03.39 / usr / libexec / diskarbitrationd 0 79 1 0 Fri09PM ? ? 0 : 00.73 / System / Library / CoreServices / backupd . bundle / Contents / Resources / backupd - helper - launchd 0 80 1 0 Fri09PM ? ? 0 : 03.84 / usr / libexec / coreduetd 0 84 1 0 Fri09PM ? ? 2 : 30.59 / usr / libexec / opendirectoryd 0 85 1 0 Fri09PM ? ? 0 : 17.45 / System / Library / PrivateFrameworks / ApplePushService . framework / apsd 0 86 1 0 Fri09PM ? ? 0 : 00.67 / System / Library / PrivateFrameworks / Noticeboard . framework / Versions / A / Resources / nbstated 0 87 1 0 Fri09PM ? ? 0 : 16.91 / System / Library / CoreServices / launchservicesd 266 88 1 0 Fri09PM ? ? 0 : 06.48 / usr / libexec / timed 0 89 1 0 Fri09PM ? ? 0 : 25.37 / usr / sbin / securityd - i 213 90 1 0 Fri09PM ? ? 0 : 01.16 / System / Library / PrivateFrameworks / MobileDevice . framework / Versions / A / Resources / usbmuxd - launchd 205 92 1 0 Fri09PM ? ? 0 : 59.64 / usr / libexec / locationd 0 94 1 0 Fri09PM ? ? 0 : 00.08 autofsd 244 95 1 0 Fri09PM ? ? 0 : 03.06 / usr / libexec / displaypolicyd - k 1 0 98 1 0 Fri09PM ? ? 0 : 11.56 / usr / libexec / dasd 0 99 1 0 Fri09PM ? ? 0 : 00.71 / System / Library / PrivateFrameworks / Heimdal . framework / Helpers / kdc 0 103 1 0 Fri09PM ? ? 0 : 00.87 / Library / Tanium / TaniumClient / TaniumClient - d 110048994 104 1 0 Fri09PM ? ? 0 : 34.02 / System / Library / CoreServices / loginwindow . app / Contents / MacOS / loginwindow console 0 105 1 0 Fri09PM ? ? 0 : 00.76 / System / Library / CoreServices / logind 0 106 1 0 Fri09PM ? ? 0 : 00.66 / System / Library / PrivateFrameworks / GenerationalStorage . framework / Versions / A / Support / revisiond 0 107 1 0 Fri09PM ? ? 0 : 00.03 / usr / sbin / KernelEventAgent 0 109 1 0 Fri09PM ? ? 1 : 58.55 / usr / sbin / bluetoothd 261 110 1 0 Fri09PM ? ? 13 : 48.55 / usr / libexec / hidd 0 112 1 0 Fri09PM ? ? 0 : 06.37 / usr / libexec / corebrightnessd -- launchd 0 113 1 0 Fri09PM ? ? 0 : 04.23 / usr / libexec / AirPlayXPCHelper 0 114 1 0 Fri09PM ? ? 1 : 07.01 / usr / sbin / notifyd 241 116 1 0 Fri09PM ? ? 0 : 11.70 / usr / sbin / distnoted daemon 0 119 1 0 Fri09PM ? ? 0 : 03.99 / usr / libexec / amfid 0 123 1 0 Fri09PM ? ? 0 : 09.47 / usr / libexec / syspolicyd 0 124 1 0 Fri09PM ? ? 0 : 05.81 / System / Library / Frameworks / Security . framework / Versions / A / XPCServices / authd . xpc / Contents / MacOS / authd 0 142 1 0 Fri09PM ? ? 1 : 31.63 / usr / sbin / cfprefsd daemon 0 143 1 0 Fri09PM ? ? 0 : 23.54 / System / Library / CoreServices / coreservicesd 0 166 1 0 Fri09PM ? ? 0 : 21.34 / System / Library / PrivateFrameworks / CoreDuetContext . framework / Resources / contextstored |
이것은 내 MacBook Pro에서 실행되는 일부 프로세스입니다. 꽤 많이 있지만 아주 일부만 붙였습니다.
이 튜토리얼이 간단한 Java 프로그램을 사용하여 모든 Linux, macOS 터미널 명령을 실행하는 데 도움이 되기를 바랍니다. 질문이 있으면 알려주세요.