Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

Python

¿Cómo importar commands?

import commands

Examples

from commands import *

def run_command(cmd):
print 'Running: "%s"' % cmd
status, text = getstatusoutput(cmd)
exit_code = status >> 8 # high byte
signal_num = status % 256 # low byte
print 'Status: x%04x' % status
print 'Signal: x%02x (%d)' % (signal_num, signal_num)
print 'Exit : x%02x (%d)' % (exit_code, exit_code)
print 'Core? : %s' % bool(signal_num & (1 << 8)) # high bit
print 'Output:'
print text
print

run_command('ls -l *.py')
run_command('ls -l *.notthere')
run_command('./dumpscore')
run_command('echo "WAITING TO BE KILLED"; read input')

from commands import *

text = getoutput('ls -l *.py')


print 'ls -l *.py:'
print text

print

text = getoutput('ls -l *.notthere')


print 'ls -l *.py:'
print text
from commands import *

status = getstatus('commands_getstatus.py')
print 'commands_getstatus.py:', status
status = getstatus('notthere.py')
print 'notthere.py:', status
status = getstatus('$filename')
print '$filename:', status

Otra forma de ejecutar comandos


import os
os.system("ls -l")

import subprocess
test = subprocess.Popen(["ping","-W","2","-c", "1", "192.168.1.70"], stdout=subprocess.PIPE)
output = test.communicate()[0]

from subprocess import call


call(["ls", "-l"])

sshproc = subprocess.Popen([command],
shell=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)

stdout_value, stderr_value = sshproc.communicate('through stdin to stdout')


print repr(stdout_value)
print repr(stderr_value)

import subprocess
try:
#prints results
result = subprocess.check_output("echo %USERNAME%", stderr=subprocess.STDOUT, shell=True)
print result
#causes error
result = subprocess.check_output("copy testfds", stderr=subprocess.STDOUT, shell=True)
except subprocess.CalledProcessError, ex:
print "--------error------"
print ex.cmd
print ex.message
print ex.returncode
print ex.output

subprocess_os_system.py
import subprocess

completed = subprocess.run(['ls', '-1'])

print('returncode:', completed.returncode)

import subprocess

try:

subprocess.run(['false'], check=True)

except subprocess.CalledProcessError as err:

print('ERROR:', err)

import subprocess

completed = subprocess.run('echo $HOME', shell=True)

print('returncode:', completed.returncode)

import subprocess

completed = subprocess.run(
['ls', '-1'],

stdout=subprocess.PIPE,

print('returncode:', completed.returncode)

print('Have {} bytes in stdout:\n{}'.format(

len(completed.stdout),

completed.stdout.decode('utf-8'))

import subprocess
subprocess.call(["iw", "phy", "phy0", "interface", "add", "mon0", "type", "monitor"])
subprocess.call(["ifconfig", "mon0", "up"])
subprocess.call(["airodump-ng", "-w", "mon0"])
or

import subprocess
subprocess.run(["iw", "phy", "phy0", "interface", "add", "mon0", "type", "monitor"])
subprocess.run(["ifconfig", "mon0", "up"])
subprocess.run(["airodump-ng", "-w", "mon0"])

How To Execute Shell Command with Python


Posted on 02/11/2017 by İsmail Baydan

Python provides a lot of modules for different operating system related operations. Running
external command or shell command is very popular Python developers. We can call Linux or
Windows commands from python code or script and use output.

Import os Module
We can use system() function inorder to run shell command in Linux and
Windows operating systems. system() is provided by os Module. So we will
load this module like below.

1 import os

Run Command with system Function


After loading os module we can use system() function by providing the
external command we want to run. In this example we will run ls command
which will list current working directory content.

1 import os

2 os.system('ls')

Run Command with system Function

Import subprocess Module


Another alternative for running external shell command is subprocess module.
This module provides process related functions. We will use call() function
but first we need to load subprocess module.
1 import subprocess

Run Command with call Function


We will use call() function which will create a separate process and run
provided command in this process. In this example we will create a process
for ls command. We should provide the exact path of the binary we want to
call.

1 import subprocess

2 subprocess.call("/bin/ls")

Run Command with call Function

Provide Parameters To The Command


We may need to provide parameters to the command we will call. We will
provide a list where this list includes command or binary we will call and
parameters as list items. In this example we will call ls for path /etc/ with -
lparameter.

LEARN MORE Python Subprocess and Popen with Examples


1 subprocess.call(['/bin/ls','-l','/etc'])

Provide Parameters To The Command

Save Command Output To A Variable


We may need to save the command output to a variable or a file. We will put
the output variable named olike below. We will use read() function
of popen()returned object.

1 o=os.popen('ls').read()

2 print(o)
Links

https://www.pythonforbeginners.com/os/subprocess-for-system-administrators

https://pymotw.com/2/commands/

https://stackoverflow.com/questions/914320/capture-stderr-from-python-subprocess-
popencommand-stderr-subprocess-pipe-std

https://pymotw.com/3/subprocess/

https://www.poftut.com/execute-shell-command-python/

You might also like