{"id":19624,"date":"2022-08-11T13:48:11","date_gmt":"2022-08-11T13:48:11","guid":{"rendered":"https:\/\/www.linuxfordevices.com\/?p=19624"},"modified":"2024-05-23T05:15:46","modified_gmt":"2024-05-23T05:15:46","slug":"execute-linux-commands-python","status":"publish","type":"post","link":"https:\/\/www.linuxfordevices.com\/tutorials\/linux\/execute-linux-commands-python","title":{"rendered":"Executing Linux Commands in Python: A Comprehensive Guide to Run Shell Commands with Python"},"content":{"rendered":"\n<p><a href=\"https:\/\/en.wikipedia.org\/wiki\/Python_(programming_language)\" target=\"_blank\" data-type=\"URL\" data-id=\"https:\/\/en.wikipedia.org\/wiki\/Python_(programming_language)\" rel=\"noreferrer noopener\">Python<\/a> is a trendy &#038; modern programming language. Especially popular among beginners as it is easy to learn. Python is so powerful that we can use it to interact with the operating system. In Linux, python act as an alternative for bash command language for scripting. It comes preinstalled in most of the distributions as it is a dependency on many tools and software. And if not it is effortless to install.<\/p>\n\n\n\n<p>In this tutorial, we will see how to run Linux commands using Python. The idea behind this is to automate tasks and save time. I am using Ubuntu for this tutorial.<\/p>\n\n\n\n<p><strong><em>Also read: <a href=\"https:\/\/www.linuxfordevices.com\/tutorials\/ubuntu\/install-latest-python-debian-ubuntu-source\" data-type=\"post\" data-id=\"1161\">Installing Latest Python on Debian\/Ubuntu using Source<\/a><\/em><\/strong><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Prerequisites<\/h2>\n\n\n\n<p>We will require a python environment. If you are using the latest distribution it is preinstalled. You can check using the following command.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\n\u276f python3 --version\n<\/pre><\/div>\n\n\n<p>To install python run the following command &#8211;<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n\u276f sudo apt install python3 -y\n<\/pre><\/div>\n\n\n<p>Additionally, if you have some knowledge of terminal &amp; some Linux commands that will be great.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">The OS module in Python <img loading=\"lazy\" decoding=\"async\" width=\"500\" height=\"500\" class=\"wp-image-17598\" style=\"width: 35px\" src=\"https:\/\/www.linuxfordevices.com\/wp-content\/uploads\/2022\/06\/1200px-Python-logo-notext.svg-removebg-preview.png\" alt=\"python3\" srcset=\"https:\/\/www.linuxfordevices.com\/wp-content\/uploads\/2022\/06\/1200px-Python-logo-notext.svg-removebg-preview.png 500w, https:\/\/www.linuxfordevices.com\/wp-content\/uploads\/2022\/06\/1200px-Python-logo-notext.svg-removebg-preview-300x300.png 300w, https:\/\/www.linuxfordevices.com\/wp-content\/uploads\/2022\/06\/1200px-Python-logo-notext.svg-removebg-preview-150x150.png 150w\" sizes=\"auto, (max-width: 500px) 100vw, 500px\" \/><\/h2>\n\n\n\n<p>OS library provides operating system-based functions and allows us to interact with the operating system. The package comes with python installation, so no need to install it separately. The library is easy to use and contains both read and write operations.<\/p>\n\n\n\n<p>Let&#8217;s write our first program and get system information &#8211;<\/p>\n\n\n\n<p>Launch your favorite text editor (I am using <strong>gedit<\/strong>) &#8211;<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ngedit system_info.py\n<\/pre><\/div>\n\n\n<p>Copy the below code and save the file &#8211;<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport os\n\nos.uname()\n<\/pre><\/div>\n\n\n<p>You can run the file like the below &#8211;<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\npython3 system_info.py\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"902\" height=\"620\" src=\"https:\/\/www.linuxfordevices.com\/wp-content\/uploads\/2022\/08\/get-system-info-using-python.png\" alt=\"Get System Info Using Python\" class=\"wp-image-20102\" srcset=\"https:\/\/www.linuxfordevices.com\/wp-content\/uploads\/2022\/08\/get-system-info-using-python.png 902w, https:\/\/www.linuxfordevices.com\/wp-content\/uploads\/2022\/08\/get-system-info-using-python-300x206.png 300w, https:\/\/www.linuxfordevices.com\/wp-content\/uploads\/2022\/08\/get-system-info-using-python-768x528.png 768w\" sizes=\"auto, (max-width: 902px) 100vw, 902px\" \/><figcaption class=\"wp-element-caption\">Get System Info<\/figcaption><\/figure>\n\n\n\n<p>The <code>uname()<\/code> method returns information like name, release, and version of the current operating system, etc. This was just an overview of the OS module, now let&#8217;s run the terminal commands.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">os.system()<\/h2>\n\n\n\n<p>The <code>os.system()<\/code> method takes command as a string and executes it in a subshell. The limitations stand the same as the <code>system()<\/code> method in C language. The method is system dependent.<\/p>\n\n\n\n<p>The code should be executed using the terminal as if you run the code in IDLE you get <strong>&#8220;0&#8221;<\/strong> as output and nothing really happens.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"891\" height=\"505\" src=\"https:\/\/www.linuxfordevices.com\/wp-content\/uploads\/2022\/08\/os-module-python.png\" alt=\"Os Module Python\" class=\"wp-image-20106\" srcset=\"https:\/\/www.linuxfordevices.com\/wp-content\/uploads\/2022\/08\/os-module-python.png 891w, https:\/\/www.linuxfordevices.com\/wp-content\/uploads\/2022\/08\/os-module-python-300x170.png 300w, https:\/\/www.linuxfordevices.com\/wp-content\/uploads\/2022\/08\/os-module-python-768x435.png 768w\" sizes=\"auto, (max-width: 891px) 100vw, 891px\" \/><figcaption class=\"wp-element-caption\">No Output<\/figcaption><\/figure>\n\n\n\n<p>Let&#8217;s run our very first command &#8211;<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport os\n\nos.system(&#039;ls&#039;)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"902\" height=\"620\" src=\"https:\/\/www.linuxfordevices.com\/wp-content\/uploads\/2022\/08\/run-linux-comands-using-python.png\" alt=\"Run Linux Comands Using Python\" class=\"wp-image-20108\" srcset=\"https:\/\/www.linuxfordevices.com\/wp-content\/uploads\/2022\/08\/run-linux-comands-using-python.png 902w, https:\/\/www.linuxfordevices.com\/wp-content\/uploads\/2022\/08\/run-linux-comands-using-python-300x206.png 300w, https:\/\/www.linuxfordevices.com\/wp-content\/uploads\/2022\/08\/run-linux-comands-using-python-768x528.png 768w\" sizes=\"auto, (max-width: 902px) 100vw, 902px\" \/><figcaption class=\"wp-element-caption\">list files and folders<\/figcaption><\/figure>\n\n\n\n<p>The <a href=\"https:\/\/www.linuxfordevices.com\/tutorials\/linux\/ls-command-linux-unix\" data-type=\"post\" data-id=\"59\">ls command<\/a> is used to list items in the respective directory.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Accept Linux Command As User Input<\/h2>\n\n\n\n<p>Let&#8217;s take input from users and then concatenate it with our command. <strong>For eg:<\/strong> <a href=\"https:\/\/www.linuxfordevices.com\/tutorials\/linux\/the-mkdir-command-in-linux\" data-type=\"post\" data-id=\"136\">Creating folders<\/a> while taking folder names from the user.<\/p>\n\n\n\n<p><strong>Code<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport os\nname = input(&quot;Enter a folder name : &quot;)\nprint(&quot;\\n&quot;)\nos.system(&#039;mkdir &#039; + name)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"694\" src=\"https:\/\/www.linuxfordevices.com\/wp-content\/uploads\/2022\/08\/create-folders-using-python-1024x694.png\" alt=\"Create Folders Using Python\" class=\"wp-image-20115\" srcset=\"https:\/\/www.linuxfordevices.com\/wp-content\/uploads\/2022\/08\/create-folders-using-python-1024x694.png 1024w, https:\/\/www.linuxfordevices.com\/wp-content\/uploads\/2022\/08\/create-folders-using-python-300x203.png 300w, https:\/\/www.linuxfordevices.com\/wp-content\/uploads\/2022\/08\/create-folders-using-python-768x521.png 768w, https:\/\/www.linuxfordevices.com\/wp-content\/uploads\/2022\/08\/create-folders-using-python.png 1404w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\">Creating Folders<\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Complete Code for Executing Linux Commands Using Python<\/h2>\n\n\n\n<p>I have developed a simple script to give you guys an idea of how you can use python to make your job easy.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport os\n\nwhile (True):\n    print(&quot;1) List Directories&quot;)\n    print(&quot;2) Create a file&quot;)\n    print(&quot;3) Create a directory\/folder&quot;)\n    print(&quot;4) Ping a server&quot;)\n    print(&quot;5) Neofetch&quot;)\n    print(&quot;6) Check Python Version&quot;)\n    print(&quot;7) Check Java Version&quot;)\n    print(&quot;8) Exit&quot;)\n\n    ch = int(input(&quot;Enter Your Choice : &quot;))\n\n    if ch == 1:\n        os.system(&#039;lsd&#039;)\n    elif ch == 2:\n        f_name = input(&quot;Enter file name : &quot;)\n        e_name = input(&quot;Enter file extension : &quot;)\n\n        os.system(&#039;touch &#039; + f_name + &#039;.&#039; + e_name)\n    elif ch == 3:\n        name = input(&quot;Enter folder name : &quot;)\n        os.system(&#039;mkdir &#039; + name)\n\n    elif ch == 4:\n        s = input(&quot;Enter address(Press enter for default - google.com) : &quot;)\n        p = input(&quot;Enter number of packer(press enter for default - 10 : )&quot;)\n        o = input(&quot;Do you want the output in a txt file -- y | n -- :&quot;)\n\n        # p = int(p)\n\n        if (s == &#039;&#039;):\n            s = &#039;google.com&#039;\n        if (p == &#039;&#039;):\n            p = &#039;10&#039;\n\n        if (o == &#039;y&#039;):\n            os.system(&#039;ping &#039; + s + &#039; -c &#039; + p + &#039; &gt; ping-output.txt&#039;)\n        else:\n            os.system(&#039;ping &#039; + s + &#039; -c &#039; + p)\n\n    elif ch == 5:\n        os.system(&#039;neofetch&#039;)\n\n    elif ch == 6:\n        os.system(&#039;python --version&#039;)\n\n    elif ch == 7:\n        os.system(&#039;java --version&#039;)\n\n    elif ch == 8:\n        break\n    else:\n        print(&quot;Invalid Choice&quot;)\n<\/pre><\/div>\n\n\n<p>This will show a menu to the user and the user has to choose any one option. As the script is in a while loop the menu will be presented to the user continuously. You can add more options to the menu.<\/p>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"694\" src=\"https:\/\/www.linuxfordevices.com\/wp-content\/uploads\/2022\/08\/the-script-of-everything-1024x694.png\" alt=\"The Script Of Everything\" class=\"wp-image-20128\" srcset=\"https:\/\/www.linuxfordevices.com\/wp-content\/uploads\/2022\/08\/the-script-of-everything-1024x694.png 1024w, https:\/\/www.linuxfordevices.com\/wp-content\/uploads\/2022\/08\/the-script-of-everything-300x203.png 300w, https:\/\/www.linuxfordevices.com\/wp-content\/uploads\/2022\/08\/the-script-of-everything-768x521.png 768w, https:\/\/www.linuxfordevices.com\/wp-content\/uploads\/2022\/08\/the-script-of-everything.png 1404w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\">The Script Of Everything<\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Wrapping Up!<\/h2>\n\n\n\n<p>This was just a small part of the OS module. It has many more features and methods. You can set the path of the scripts you have developed in the shell configuration file. This will allow you to run the scripts from anywhere. Also, create cron jobs to execute automatically from time to time. Hope this article helped you in some way.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Articles You Might Be Interested In<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/www.linuxfordevices.com\/tutorials\/shell-script\/reverse-shell-in-python\">Coding A Reverse Shell In Python In 10 Lines Or Less<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/www.linuxfordevices.com\/tutorials\/linux\/automatic-updates-cronjob\">How to Configure Automatic Updates using Cronjob?<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/www.linuxfordevices.com\/tutorials\/linux\/run-commands-every-x-seconds\">How To Run Commands in Linux Every X Seconds?<\/a><\/li>\n<\/ul>\n\n\n<div id=\"rank-math-faq\" class=\"rank-math-block\">\n<div class=\"rank-math-list \">\n<div id=\"faq-question-1716441924711\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>Linux Command<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p>A <strong>Linux command<\/strong> is a specific instruction or action given to a computer operating on a Linux system. It is a fundamental component for interacting with the operating system through a command-line interface.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1716441946698\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>Executing Commands in Python<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p><strong>Executing commands in Python<\/strong> allows you to run <strong>Linux commands<\/strong> within a Python script. This can be achieved using the <strong>subprocess<\/strong> module to execute commands in the operating system&#8217;s shell.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1716441982501\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>Output in Python<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p><strong>Output<\/strong> in Python refers to the result or response generated by the execution of a command or code snippet. You can capture and display this <strong>output<\/strong> using Python&#8217;s <strong>subprocess<\/strong> module.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1716441993497\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>Using the Subprocess Module<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p><strong>Using the subprocess module<\/strong> in Python allows you to create new processes, connect to their input\/output\/error pipes, and obtain their return codes. It provides an interface for executing system commands or scripts from within a Python program.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1716442017537\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>Error Handling<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p><strong>Error<\/strong> handling in Python involves managing and addressing any issues or exceptions that occur during the execution of code or commands. You can use <strong>try-except<\/strong> blocks to capture and handle errors effectively.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1716442027083\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>Capturing Command Output<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p><strong>Capturing command output<\/strong> in Python involves storing the result of executing a system command. This can be achieved using the <strong>subprocess<\/strong> module to run commands and capture their output for further processing.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1716442041795\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>Executing Commands Safely<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p>When <strong>executing commands<\/strong> in Python, it is essential to do so safely to prevent any security risks or unintended consequences. Always validate user input and use secure methods to execute <strong>system<\/strong> commands.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1716442181114\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">What should I keep in mind when executing shell commands in Python?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>When executing shell commands in Python, it&#8217;s important to properly handle the stdout and stderr outputs, ensuring that your script behaves as expected.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1716442194158\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">Who can benefit from learning how to execute Linux commands in Python?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Anyone from developers to system administrators can benefit from learning how to execute Linux commands in Python, as it opens up a wide variety of possibilities for automating tasks and managing systems.<\/p>\n\n<\/div>\n<\/div>\n<\/div>\n<\/div>","protected":false},"excerpt":{"rendered":"<p>Python is a trendy &#038; modern programming language. Especially popular among beginners as it is easy to learn. Python is so powerful that we can use it to interact with the operating system. In Linux, python act as an alternative for bash command language for scripting. It comes preinstalled in most of the distributions as [&hellip;]<\/p>\n","protected":false},"author":24,"featured_media":19626,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"set","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[6],"tags":[],"class_list":["post-19624","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-linux"],"_links":{"self":[{"href":"https:\/\/www.linuxfordevices.com\/wp-json\/wp\/v2\/posts\/19624","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.linuxfordevices.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.linuxfordevices.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.linuxfordevices.com\/wp-json\/wp\/v2\/users\/24"}],"replies":[{"embeddable":true,"href":"https:\/\/www.linuxfordevices.com\/wp-json\/wp\/v2\/comments?post=19624"}],"version-history":[{"count":0,"href":"https:\/\/www.linuxfordevices.com\/wp-json\/wp\/v2\/posts\/19624\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.linuxfordevices.com\/wp-json\/wp\/v2\/media\/19626"}],"wp:attachment":[{"href":"https:\/\/www.linuxfordevices.com\/wp-json\/wp\/v2\/media?parent=19624"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.linuxfordevices.com\/wp-json\/wp\/v2\/categories?post=19624"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.linuxfordevices.com\/wp-json\/wp\/v2\/tags?post=19624"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}