how can i passs input in adb shell using python script? - python

I am facing a problem, have to pass an input after I run command: adb shell libtest_ip through python:
import subprocess
command = 'adb shell libtest_ip'
p = subprocess.Popen(command, shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
after this I have to pass input like 1 or en_us etc.. but as soon as the command to sun binary(libtest_ip is a binary), is executed, it gets stuck.
Please help me if anyone have idea how to solve this?

I think your best bet is pexpect .
Specially you can take a look at script.py that would help you creating the interactive script.
Basically, you should end up with something like this
...
self.child.expect('Whatever')
self.child.sendline('1')
self.child.expect('Whatever 2')
self.child.sendline('en-us')
...
update
Your example should work, try
#! /usr/bin/env python3
import pexpect
print(pexpect.run('/bin/echo hello'))
and running it should output
% ./test-pexpect.py
b'hello\r\n'

Related

raw_input in subprocess using python

I've a problem with shell command, when i want to enter a value by using raw_input and put it in shell command, it displays "s was unexpected in this context".
Here is my program:
import curses, sys, os, signal,argparse
from multiprocessing import Process
from scapy.all import *
from subprocess import call, PIPE
def main():
var=raw_input("Entre wap's #mac: ")
subprocess.call('tshark -r crackWEP.pcap "((wlan.fc.type_subtype==0x20)&&(wlan.bssid==**"%s"%var**))"|wc -l', shell=True, stdout=subprocess.PIPE)
if __name__ == u'__main__':
main()
Well you are not substituting var in the command now, are you?
You mixed bash and python. You probably meant:
var=raw_input("Entre wap's #mac: ")
subprocess.call('tshark -r crackWEP.pcap "((wlan.fc.type_subtype==0x20)&&(wlan.bssid==**"%s"%'+var+'**))"|wc -l', shell=True, stdout=subprocess.PIPE)
Also care with user input and shell=True. People like to put "much fun" in there. I'd advise to call tshark, with shell=False, catch output from it and count lines in python. Running separate external program seems like a waste.
Edit:
2nd more pythonic version:
command = 'tshark -r crackWEP.pcap "((wlan.fc.type_subtype==0x20)&&(wlan.bssid==**"%s"%{}**))"|wc -l'.format(var)
subprocess.call(command, shell=True, stdout=subprocess.PIPE)

python - subprocess.Popen() synax errors

I am trying to mirror the following shell command using subprocess.Popen():
echo "SELECT employeeid FROM Users WHERE samaccountname=${1};" | bsqldb -S mdw2k8sqlp02.dow.com -D PhoneBookClient -U PortManUser -P plum45\\torts -q
It currently looks like:
stdout = subprocess.Popen(["echo", "\"SELECT", "employeeid", "FROM", "Users", "WHERE", "samaccountname=${1};\"", "|", "bsqldb", "arg1etc"], stdout=subprocess.PIPE)
for line in stdout.stdout.readlines():
print line
It seems that this is wrong, it returns the following standard out:
"SELECT employeeid FROM Users WHERE samaccountname=${1};" | bsqldb arg1etc
Does anyone know where my syntax for subprocess.Popen() has gone wrong?
The problem is that you're trying to run a shell command without the shell. What happens is that you're passing all of those strings—including "|" and everything after is—as arguments to the echo command.
Just add shell=True to your call to fix that.
However, you almost definitely want to pass the command line as a string, instead of trying to guess at the list that will be joined back up into the string to pass to the shell.
Or, even better, don't use the shell, and instead pipe within Python. The docs have a nice section about Replacing shell pipeline (and all kinds of other things) with subprocess code.
But in your case, the thing you're trying to pipe is just echo, which is quite silly, since you already have exactly what echo would return, and can just feed it as the input to the second program.
Also, I'm not sure what you expect that ${1} to get filled in with. Presumably you're porting a shell script that took some arguments on the command line; your Python script may have the same thing in sys.argv[1], but without knowing more about what you're doing, that's little more than a guess.
The analog of echo some string | command arg1 arg2 shell pipeline in Python is:
from subprocess import Popen, PIPE
p = Popen(["command", "arg1", "arg2"], stdin=PIPE)
p.communicate("some string")
In your case, you could write it as:
import shlex
import sys
from subprocess import Popen, PIPE
cmd = shlex.split("bsqldb -S mdw2k8sqlp02.dow.com -D PhoneBookClient "
"-U PortManUser -P plum45\\torts -q")
sql = """SELECT employeeid FROM Users
WHERE samaccountname={name};""".format(name=sql_escape(sys.argv[1]))
p = Popen(cmd, stdin=PIPE)
p.communicate(input=sql)
sys.exit(p.returncode)

Use bat file in CGI Python on localhost

I'm quite stuck with with a complex mix of files and languages! The problem:
My webform starts a python script, as a cgi script, on localhost(apache). In this python script I want to execute a batchfile. This batchfile executes several commands, which i tested thoroughly.
If i execute the following python file in the python interpreter or in CMD it does execute the bat file.
But when I 'start' the python script from the webform it says it did it, but there are no results, so i guess something is wrong with the cgi part of the problem?!
The process is complicated, so if someone has a better way of doing this...pls reply;). I'm using windows so that makes things even more annoying sometimes.
I think it's not the script, because I try subprocess.call, os.startfile and os.system already!
It either does nothing or the webpage keeps loading(endless loop)
Python script:
import os
from subprocess import Popen, PIPE
import subprocess
print "Content-type:text/html\r\n\r\n"
p = subprocess.Popen(["test.bat"], stdout = subprocess.PIPE, stderr = subprocess.PIPE)
out, error = p.communicate()
print out
print "DONE!"
The bat file:
#echo off
::Preprocess the datasets
CMD /C java weka.filters.unsupervised.attribute.StringToWordVector -b -i data_new.arff -o data_new_std.arff -r tweetin.arff -s tweetin_std.arff
:: Make predictions with incoming tweets
CMD /C java weka.classifiers.functions.SMO -T tweetin_std.arff -t data_new_std.arff -p 2 -c first > result.txt
Thanks for your reply!!
Your bat file is redirecting the second program's output to a file, so p.communicate can only get the output of the first program. I'm assuming you want to return the content of result.txt?
I think you should skip the bat file and just do both java invocations in python. You get more control of the execution and you can check the return codes, there might be problems with java not being in the PATH environment variable when run as CGI. The following is mostly equivalent with respect to you getting the program's output back, you want to capture the second program's output if your webservice is supposed to return the predictions.
import os
import shlex
from subprocess import Popen, PIPE
import subprocess
print "Content-type:text/html\r\n\r\n"
p = subprocess.Popen(shlex.split("java weka.filters.unsupervised.attribute.StringToWordVector -b -i data_new.arff -o data_new_std.arff -r tweetin.arff -s tweetin_std.arff"),
stdout = subprocess.PIPE, stderr = subprocess.PIPE)
out, error = p.communicate()
return_code = subprocess.call(shlex.split("java weka.classifiers.functions.SMO -T tweetin_std.arff -t data_new_std.arff -p 2 -c first > result.txt"))
print out
print "DONE!"
A couple of things come to mind. You might want to try setting your Popen's shell=True. Sometimes I have noticed that's solved my problem.
p = subprocess.Popen(["test.bat"], stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell=True)
You may also want to take a look at Fabric, which is perfect for this kind of automation.

To pass `echo t | ` as arg in `subprocess.check_output`

I am new to Python. I am struck up with the below problem.
I have called an exe using subprocess.check_output from my python script.
res = subprocess.check_output(["svn.exe", "list", "Https://127.0.0.1:443/svn/Repos"], stderr=subprocess.STDOUT)
when the script is executed in command prompt, i get a prompt message to enter an input,
(R)eject, accept (t)emporarily or accept (p)ermanently?
But when i execute the script from a batch file, i dont get this message and by default the call check_output fails.
Is there any way to pass the input while calling subprocess.check_output, so that i could run the script in batch.
Hi, Im updating my question:
I tried to run svn from command prompt with the below command,
echo t | svn.exe list Https://127.0.0.1:443/svn/Repos
I got the output without any user input.
But i couldnt able to pass the echo t | in subprocess.check_output.
Is there any way to do this?
Please help me to resolve this.
Thanks
I guess this is not the answer to the question in title, but did you try running svn with --non-interactive --trust-server-cert? Isn't that what you want?
The message you're getting looks related to certificates to me. So rather than adding the complication of passing input to the command either fix the certificate problem or pass the --trust-server-cert flag to the SVN command.
res = subprocess.check_output(["svn.exe", "--trust-server-cert", "list", "url"], stderr=subprocess.STDOUT)
I found two solutions for my problem,
1.found this soultion from this link http://desipenguin.com/techblog/2009/01/13/fun-with-python-subprocessstdin/
proc = subprocess.Popen((["svn.exe", "list", "Https://127.0.0.1:443/svn/Repos"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
print proc.communicate(‘t\n’)[0]
This resolved providing key input 't' to the process. But i was not able to read the output. So, i followed the second solution.
2.Using two subprocesses:
p = subprocess.Popen("echo t |", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
p1 = subprocess.Popen(["svn.exe", "list", "Https://127.0.0.1:443/svn/Repos"], shell=True, **stdin=p.stdout**, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
output = p1[0]
Here the output of process 1 is given as input of process 2. So this is equal to echo t | svnmucc mkdir d:\temp.
Thanks.

Virtuozzo and automating commands with Python's subprocesses

I'm dealing with a Virtuozzo server and want to automate logging into each container and issuing a few commands in Python by creating a subprocess for 'vzctl enter '.
Here is the snippet that I'm working on right now -
#!/usr/bin/python
import subprocess
print 'Start'
proc = subprocess.Popen(['vzctl enter 123'],
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
shell=True)
print proc.communicate('whoami')[0]
print 'Finished'
But the output I see everytime is -
Unable to get term attr: Invalid argument
Unable to restore term attr: Invalid argument
I really think this is a BASH error, can anyone give me a suggestion?
Looks like vzctl expects stdin/stdout to be a terminal. You can find out which by experimenting (in bash):
$ echo whoami | vzctl enter 123 # stdin is not a tty
$ vzctl enter 123 | cat # stdout is not a tty
whoami
<ctrl-d>
You can use the pty module from the standard library to create pseudottys, but that module is very low-level.
There's a 3rd-party module called pexpect that might fit the bill.

Categories