Python script to check if android device is connected to internet - android

I am writing a python script to check if my android device is connected to internet. I am trying to do the following in adb shell:
busybox telnet 173.194.33.97 80
GET / HTTP/1.0
The output is:
- HTTP/1.0 200 OK
I care only about HTTP/1.0 200 OK, to check the internet connectivity.
I tried to use netcat in python but I don't have a very good experience to implement it.
Any help will be greatly appreciated!

Finally, the Python script is:
cmd = "adb shell \"echo \'GET / HTTP/1.0\n\n\' | nc 173.194.33.103 80\""
p = Popen(shlex.split(cmd), stdout=PIPE, stderr=STDOUT)
#The output will be "HTTP/1.1 200 OK", "HTTP/1.0 200 OK" OR "HTTP/2.0 200 OK"
for line in iter(p.stdout.readline, b''):
if line.rstrip().startswith('HTTP/') and line.rstrip().endswith('200 OK'):
print '\nFOUND IT: ' + line.rstrip()
wifi_flag = True
break

Related

Unable to execute plink command using groovy script

I got stuck in a issue with plink command running on windows.Below is the command I am firing to drop iptable of remote android device.
plink.exe -v -ssh rauser#HOSTNAME -pw PASSWORD iptables -D INPUT -p tcp -m tcp --dport 5555 -j DROP
I am able to execute the command from command prompt manually but when I am executing command as a bat file from groovy script it throws me an error.I am sharing both with you.
Groovy Script
// enable ADB
commandsList.add(""
"enable-adb.bat "
"" + deviceip)
// run adb commands
commandsList.each {
def command = pathtoadb + it
log.info command
def proc = command.execute()
proc.waitFor() // Wait for the command to finish
// Obtain status and output
log.info "return code: ${ proc.exitValue()}" // "0" is success
//log.info "stderr: ${proc.err.text}"
log.info "stdout: ${proc.in.text}" // *out* from the external program is *in* for groovy
def error = proc.err.text;
// if the output contains "Bad rule" that means ADB is already enabled and we don't want the test to fail
if (!error.contains("Bad rule")) {
log.info " _______ There was a problem connecting to your device using SSH. Check if remote access is enabled on your device"
log.info("ERROR: " + error)
} else {
log.info " _______ return code is 1 because ADB was already enabled - this is not a failure"
log.info(" ******** ADB has been enabled on device --> " + deviceip)
}
Exeception Message
Server version: SSH-2.0-OpenSSH_5.9
Using SSH protocol version 2
We claim version: SSH-2.0-PuTTY_Release_0.62
Doing Diffie-Hellman group exchange
Server unexpectedly closed network connection
FATAL ERROR: Server unexpectedly closed network connection

subprocess.check_output fails to execute a command but the same works in windows

I am trying to connect two devices to my pc and run some commands on them using python and adb.
when I run the command from the command prompt, it goes through fine, but when i put those in the python script, they give me errors.
this is causing the errors all the time:
from subprocess import check_output, CalledProcessError
try:
adb_ouput = check_output(["adb","devices","-l","|", "grep", "\"model\""])
print adb_ouput
except CalledProcessError as e:
print e
The error message I get is this:
Usage: adb devices [-l]
Command '['adb', 'devices', '-l', '|', 'grep', '"model"']' returned non-zero exit status 1
When I try the same code without the grep command, it works
adb_ouput = check_output(["adb","devices","-l"])
It gives me the right output.
When I try the same in windows command prompt, It works fine (I am replacing grep with FINDSTR because i'm using it in windows, and I have tried doing the same in the python script as well, with 'shell = True' and also without.)
eg:
adb devices -l | FINDSTR "model"
This gives me an ouptut without any problems.
The output I get is
123ab6ef device product:xxxxxxxxx model:xxxxxxxxx device:xxxxxxxxx
bd00051a4 device product:yyyyyyyyyy model:yyyyyyyyyy device:yyyyyyyyy
I am trying to understand where I am going wrong here, but can't figure it out.
So far I have checked the docs: https://docs.python.org/3/library/subprocess.html
https://docs.python.org/3/library/subprocess.html#subprocess.CalledProcessError
These just give me the error codes.
I have also looked at these answers:
Python, adb and shell execution query
I took some error checking from here and added to my code.
Python subprocess.check_output(args) fails, while args executed via Windows command line work OK
python check_output fails with exit status 1 but Popen works for same command
I think i am close but just can't put my finger on it.
Any help would be appreciated.
First
adb_ouput = check_output(["adb","devices","-l","|", "grep", "\"model\""])
certainly requires shell=True, but even with that it's not equivalent to
adb devices -l | FINDSTR "model"
When using check_output, you're passing "model" as grep argument literally but you should pass just model. "model" is not in your output (with quotes) so grep fails to find it, and returns exitcode 1 which is not really an error for grep but makes check_output trigger an exception because it expects 0.
So I would to this as a quickfix:
adb_ouput = check_output(["adb","devices","-l","|", "grep", "model"],shell=True)
And as a longfix I'd perform the grep command directly with python.
adb_output = check_output(["adb","devices","-l"])
for l in adb_output.splitlines():
if "model" in l:
print(l)

wpa_supplicant reply to any command with UNKNOWN COMMAND except PING, LIST_NETWORKS, ATTACH, DETACH, TERMINATE, and STATUS?

First of all my target system is android.
I created a c++ application to communicate with wpa_supplicant through the control interface provided as a wpa_ctrl.c file (I included the header file wpa_ctrl.h and linked with the library libwpa_client.so)
here is the documentation page.
Every thing was working fine, but suddenly every command I send is replied by UNKNOWN COMMAND, I suppose that the commands that work fine (ping, list_networks, status, and terminate) have a common thing (maybe they do not need to open the wpa_supplicant.conf which causes the problem on other commands)
here is how I open the connection:
this->ctrl = wpa_ctrl_open(this->socket.c_str());
here is how I send commands:
s = wpa_ctrl_request(this->ctrl, cmd.c_str(), cmd.length(), this->_reply, &reply_len, msg_cb);
above method signatures:
struct wpa_ctrl * wpa_ctrl_open(const char *ctrl_path);
int wpa_ctrl_request(struct wpa_ctrl *ctrl, const char *cmd, size_t cmd_len,
char *reply, size_t *reply_len,
void (*msg_cb)(char *msg, size_t len));
example output:
PING
PONG
UNKNOWN COMMAND: MIB
UNKNOWN COMMAND: STATUS-VERBOSE
UNKNOWN COMMAND: PMKSA
UNKNOWN COMMAND: LOGON
UNKNOWN COMMAND: LOGOFF
UNKNOWN COMMAND: REASSOCIATE
UNKNOWN COMMAND: RECONNECT
UNKNOWN COMMAND: RECONFIGURE
LIST_NETWORKS
network id / ssid / bssid / flags
UNKNOWN COMMAND: DISCONNECT
UNKNOWN COMMAND: SCAN
UNKNOWN COMMAND: SCAN_RESULTS
UNKNOWN COMMAND: BSS
UNKNOWN COMMAND: ADD_NETWORK
STATUS
p2p_device_address=12:d3:8a:c8:34:ef
p2p_state=IDLE
wifi_display=1
ifname=p2p0
address=12:d3:8a:c8:34:ef
ifname=wlan0
address=10:d3:8a:c8:34:ef
UNKNOWN COMMAND: ADD_NETWORK
closed connection with wpa_supplicant.
Can not create Network
Here is a screenshot of an older version of the program working almost fine:
any help is appreciated.
EDIT: I tested the program on my other device and it worked well. But still broken on my main device, probably a factory reset will solve it. But I still want to know the cause of the problem.
The problem was that the interface name was wrong.

Android/adb redirect console app output

I am trying to get the output of a WLAN driver control interface via adb shell on a motorola droid 2. The command is called wlan_cu. To run the command,I am using:
% wlan_cu -itiwlan0 -s /data/jay/stat.sh
Connection established with supplicant .../Connection> Bssid_list,
Connect, Disassociate, Status, Full_bssid_list, wPs/
Status : DISCONNECT MAC : f8.7b.7a.7b.b7.9b SSID : <empty>
BSSID : 00.00.00.00.00.00
Channel : <empty>
Driver/, Connection/, Management/, Show/, Privacy/, scAn/, roaminG/, qOs/, poWer/, eVents/, Bt coexsistance/, Report/, dEbug/, biT/, aboUt, Quit
[1] Segmentation fault wlan_cu -itiwlan0 -s /data/jay/stat.sh
The -s option is to read wlan_cu commands from a script.
% cat /data/jay/stat.sh
c s
/
q
If I try to redirect the output i.e.
% wlan_cu -itiwlan0 -s /data/jay/stat.sh &> out.txt
out.txt is created, but empty and the output still goes to screen. Anyone have an idea? been stuck on this for quite a while.
you can try to redirect both stdout and stderr to the out.txt. Try this,
# wlan_cu -itiwlan0 -s /data/jay/stat.sh > out.txt 2>&1

GSM module with Android on BeagleBoard

I'm using http://www.sparkfun.com/products/9427 as GSM module. I've built for FTDI and generic usb-serial driver. Everytime I try to pppd call GPRS I'll get pppd: connect script failed.
The commands executed were:
1. pppd /dev/ttyUSB0
2. netcfg ppp0 up
3. pppd call gprs
gprs script:
/dev/ttyUSB0
460800
crtscts
modem
noauth
debug
nodetach
usepeerdns
noipdefault
defaultroute
user ""
0.0.0.0:0.0.0.0
connect '/system/bin/chat -s -v -f /system/etc/ppp/gprs-connect-chat' `
gprs-connect-chat script:
TIMEOUT 15
ABORT "DELAYED"
ABORT "BUSY"
ABORT "ERROR"
ABORT "NO DIALTONE"
ABORT "NO CARRIER"
TIMEOUT 40
'' \rAT
OK ATZ
OK "ATQ0 V1 E0 S0=0 &C1 &D2 +FCLASS=0"
OK AT+CGDCONT=1,"IP","Singtel"
OK ATDT*99#
CONNECT

Categories

Resources