Reading from linux command line with Python
You need to read stdin
from the python script.
import sys
data = sys.stdin.read()
print 'Data from stdin -', data
Sample run -
$ date | python test.py
Data from stdin - Wed Jun 17 11:59:43 PDT 2015
Execute a command by reading contents of a text file
This should work:
import subprocess
# read in users and strip the newlines
with open('/tmp/users.txt') as f:
userlist = [line.rstrip() for line in f]
# get list of commands for each user
cmds = []
for user in userlist:
cmds.append('smbmap -u {} -p p@ssw0rd -H 192.168.2.10'.format(user))
# results from the commands
results=[]
# execute the commands
for cmd in cmds:
results.append(subprocess.call(cmd, shell=True))
# check for which worked
for i,result in enumerate(results):
if result == 0:
print(cmds[i])
Edit: made it your file path, changed to .format(), checked result == 0 (works for ssh trying passwords)
Edit: forgot to add shell=True
python - read linux command output continuously
You can read the output line by line and process/print it. Meanwhile use p.poll
to check if the process has ended.
def get_message(command):
p = subprocess.Popen(
command,
stdout=subprocess.PIPE,
)
while True:
output = p.stdout.readline()
if output == '' and p.poll() is not None:
break
if output:
yield output.strip()
Reading the output of a linux command from C
-As I said in the comments, instead of using system
or popen
, you might use the system pipe command: |
.
Using the pipe command means redirecting the output (stdout
) of one program to the input (stdin
) of another program.
The simple program (program_that_monitors), that I've insert below, rewrites on the console all the output generated by another program (program_to_monitor) piped (pipe is |
) by it.
from command line:
prog_to_monitor | program_that_monitors
With this trivial command, to have the stderr
too, it will be necessary to redirect it to the stdout
. All very simple:
from command line:
prog_to_monitor 2>&1 | program_that_monitors
where 2>&1
redirects stderr
to stdout
and |
performs pipelining from program_to_monitor to program_that_monitors
Obviously, instead of the part that rewrites the output coming from program_to_monitor, you can insert your control logic.
Here is the very simple C code:
#include <stdio.h>
#include <string.h>
int main()
{
char buff[1000];
while( fgets(buff, 1000, stdin) ) {
printf(">> ");
fwrite(buff,1,strlen(buff),stdout);
}
return 0;
}
How can I run a python code with input on Linux terminal?
You need to use command line arguments.
For example, in the following code:
import sys
print ('# Args:', len(sys.argv))
print ('Argument List:', str(sys.argv))
If you call it from the terminal...
python3 test_args.py ar1 ar2 ar3 ar4 ar5
Gives as a result:
# Args:: 6
Argument List: ['test_args.py', 'ar1', 'ar2', 'ar3', 'ar4', 'ar5']
Reading input file to Python script, using CMD
script.py < example.txt
sends the file contents to stdin which can be accessed via sys.stdin
. The following works:
import sys
# First try supporting commands formatted like: script.py example.txt
if len(sys.argv) > 1:
with open(sys.argv[1]) as f:
contents = f.read()
# Now try supporting: script.py < example.txt
elif sys.stdin:
contents = ''.join(sys.stdin)
# If both methods failed, throw a user friendly error
else:
raise Exception('Please supply a file')
print(contents)
But in good old Python fashion, there is a built-in library that can make our life very easy. The library is fileinput, and it will automatically support both methods of reading input that you mentioned:
import fileinput
contents = fileinput.input()
print( ''.join(contents) )
And that works regardless of if you do script.py example.txt
or script.py < example.txt
or cat example.txt | script.py
and you can even do script.py example1.txt example2.txt example3.txt
and you will receive the file contents of the different files combined together.
Related Topics
How to Create a User in Linux Using Python
Multiple Instances of Python Running Simultaneously Limited to 35
What Is the Easiest Way to Detect Key Presses in Python 3 on a Linux MAChine
Python Convert Microsoft Office Docs to Plain Text on Linux
Allowing Ctrl-C to Interrupt a Python C-Extension
Python: Interplay Between Lib/Site-Packages/Site.Py and Lib/Site.Py
Linux:Python:Clear Input Buffer Before Raw_Input()
Python's Equivalent for R's Dput() Function
Auto.Arima() Equivalent for Python
Converting Python Objects for Rpy2
Which Command to Use for Checking Whether Python Is 64Bit or 32Bit
Killing Sudo-Started Subprocess in Python
Determine If Package Installed with Yum Python API
How Can Python Handle Systemctl Stop
Why Does Os.Path.Getsize() Return a Negative Number for a 10Gb File
Why Is My Python App Stalled with 'System'/Kernel CPU Time