Why does my subprocess.call(command) code write nothing to a txt output file? - python-3.x

I am trying to use the subprocess module of Python 3 to call a command (i.e. netstat -ano > output.txt), but when I run the script, the output file gets created, but nothing gets written into it, in other words, its just blank.
I've tried looking into the subprocess module API about how the subprocess.call() method works, and searching Google for a solution. I tried using the subprocess.check_output() method, but it printed it out as an unformatted string, rather than the column-like format that entering netstat -ano into Windows command prompt usually gives.
This is my current code:
import subprocess as sp
t = open('output.txt', 'w')
command = 'netstat -ano > output.txt'
cmd = command.split(' ')
sp.call(cmd) # sp.call(['netstat', '-ano', '>', 'output.txt'])
t.close()
I thought it was maybe because I didn't use the write() method. But when I changed my code to be
t.write(sp.call(cmd))
I would get the error that the write() method expects a string input, but received an int.
I expected the output to give me what I would normally see if I were to open command prompt (in Windows 10) and type netstat -ano > output.txt, which would normally generate a file called "output.txt" and have the output of my netstat command.
However when I run that command in my current script, it creates the 'output.txt' file, but there's nothing written in it.

If you just cast your cmd to a str like t.write(str(cmd))it will write to output.txt
import subprocess as sp
t = open('output.txt', 'w')
command = 'netstat -ano > output.txt'
cmd = command.split(' ')
t.write(str(cmd))
sp.call(cmd) # sp.call(['netstat', '-ano', '>', 'output.txt'])
t.close()

Related

How to run a python file and scan the generated ips by nmap

I have written a python script to search through shodan, my script code returns a file containing an ip list that each line contains single ip.
here is my code:
import shodan
SHODAN_API="YOUR_SHODAN_API"
api = shodan.Shodan(SHODAN_API)
try:
# Search Using Shodan
results = api.search('EXAMPLE')
# Showing the results
print 'Results found: %s' % results['total']
for result in results['matches']:
print '%s' % result['ip_str']
''' following lines could be uncommented due to more information
Don't Uncomment if you are using scanning methods with the results '''
#print result['data']
#print ''
except shodan.APIError, e:
print 'Error: %s' % e
I was wondering if there is any way to automate the task of running my code and then scanning the ip list by external script or something that work on OSX and Linux ?
You can simply use a bash script like the following one:
#!/bin/bash
python ShodanSearch.py >> IPResult.txt
cat IPResult.txt | while read line
do
sudo nmap -n -Pn -sV -p 80,8080 -oG - $line >> NResult.txt
done
As an alternative to the solution above, you could also execute nmap using the python os module to execute shell commands within your python script, or the now preferred method is with the subprocess module, haven’t personally used the latter, but it can definitely do what you want.

Popen returning nothing

Im trying to run a exe with some arguments within python using subprocesses Popen but the code is currently printing nothing as the output and a CMD window doesnt open when i run the file.
I know the command works as i manually paste it within CMD and it runs perfectly fine, what could i be doing wrong in my code?
import sys
import admin
import subprocess
from subprocess import Popen, PIPE
Path_2to3 = sys.executable[:-11] + "Scripts"
cmdCommand = '''cd "{}" && 2to3.exe -w "C:/Users/Desktop/bulk_converter/tests/test2.py"'''.format(Path_2to3)
process = subprocess.Popen(cmdCommand, stdout=subprocess.PIPE, shell=True)
output, error = process.communicate()
print(output, error)
retured values from print(output,error)
b'' None
Any help/suggestions would be appreciated.
Hi perhaps also specify stderr should be redirected to a pipe:
stderr=subprocess.PIPE
You may also be interested in passing a timeout parameter to communicate.

Executing Commands in multiple devices using Python Code in Putty/Plink

I am trying to execute commands that are in a file and respective host credentials in another file, the target is to pull list of commands from that file and execute the commands in the hosts which are in the Credential file.
The outputs should be routed to another file, I tried to write a code and I was able to achieve on for one device and one command. The output is printing in the screen but with /n for every line not as the desired output.
For now I had placed the command in the same file but my target was to pull the commands in line procedure, Like first line execute the command after that execute the next command.
Please help me in resolving this, I am trying to write it in python.
HOST_CRED.txt:
Hostname <IP> <USERID> <PASSWORD> <command>
import socket
import subprocess
from subprocess import Popen, PIPE, STDOUT
with open("HOST_CRED.txt") as f:
for line in f:
x=line.split()
cmd='plink.exe -ssh '+ x[2] + '#'+ x[1] + ' -pw ' + x[3] + ' ' + x[4]
p=Popen(cmd, stdout=PIPE)
output=p.stdout.read()
print(output)

Why is stdout printing out an empty string in this case?

I am reading about subprocess and playing around with some code.
I'm using Windows 7 with Python3.6
import subprocess
process = subprocess.Popen(['notepad', 'C:\\Users\Amit\Downloads\InsiderTrades.txt'],stdout=subprocess.PIPE, stderr=subprocess.PIPE)
#I'm opening a text file which has a list of stock tickers
stdout1, stderr1 = process.communicate()
print(stdout1.decode('ASCII'))
The output I'm getting is nothing or
b'' as the value for stdout1.
I"m not quite sure what communicate is outputting in this case.
I was under the impression that it would output the text from my text file or it would output anything I type into the text file.
I tried typing into the newly opened text file as well, but I'm still getting the same output , b''
So what am I getting an empty string, despite typing something into the newly opened textfile.
Subprocess is basically as if you run that command in the terminal.
So what you are doing is running
notepad some_file.txt
which just opens a file in notepad, but it doesn't send anything to standard output.
If you run a command that writes something to standard output, then you will have a non-empty stdout1. Try ls for example if you are on a *nix system or dir if on Windows.

No output given by stdout.readlines()

This is a simple code that logs into a linux box, and execute a grep to a resource on the box. I just need to be able to view the output of the command I execute, but nothing is returned. Code doesn't report any error but the desired output is not written.
Below is the code:
import socket
import re
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('linux_box', port=22, username='abc', password='xyz')
stdin, stdout, stderr = ssh.exec_command('grep xyz *.set')
output2 = stdout.readlines()
type(output2)
This is the output I get:
C:\Python34\python.exe C:/Python34/Paramiko.py
Process finished with exit code 0
You never actually print anything to standard output.
Changing last line to print(output2) should print value correctly.
Your code was likely based on interactive Python shell experiments, where return value of last executed command is printed to standard output implicitly. In non-interactive mode such behavior does not occur. That's why you need to use print function explicitly.

Resources