简体   繁体   中英

How can I assign a system command to a variable in Python

I am working on a project to help me learn python. I realize that I am probably reinventing the wheel, as there is probably a ping module out there. If so please don't advise this, as this project is to help me learn python.

I wont go in detail with my entire project. At the present moment, I am simply trying to assign the output of the ping command to a variable. For the most part I am only interested in a certain portion of the ping output. The code works fine when the address exist. So my question is how can I fix this so that it works when the the network address does not exist and ping returns negative results?

 #! /usr/bin/perl
import subprocess

p1 = subprocess.check_output("ping -q -o -t 4 192.168.1.113", shell=True)

ping1 = p1[131:137]

print ping1

The results are as follows

>>> ================================ RESTART ================================
>>> 
 0.0% 
>>> 

When the IP Address does not exist, I get the following:

>>> ================================ RESTART ================================
>>> 

Traceback (most recent call last):
  File "/Users/dmartin/scripts/python/netscan/netscanv2.py", line 6, in <module>
    p1 = subprocess.check_output("ping -q -o -t 4 192.168.1.114", shell=True)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 575, in check_output
    raise CalledProcessError(retcode, cmd, output=output)
CalledProcessError: Command 'ping -q -o -t 4 192.168.1.114' returned non-zero exit status 2

You should probably be catching that exception and handling the case that way.

import subprocess

try:
  p1 = subprocess.check_output("ping -q -o -t 4 192.168.1.113", shell=True)
  ping1 = p1[131:137]
  print ping1
except CalledProcessError, e:
  if "status 2" in str(e):
    print "IP address does not exist."
  else:
    print "Process error encountered: " + str(e)

Check the man page ( man ping ). Ping returning 2 means the ping was successfully sent but you're not getting a response. Check also here here

Try pinging www.google.com ( 8.8.4.4 or 8.8.8.8 ) and see if that works.

Thank you TheSoundDefense

Try: except: worked like a charm. I search other forums for this algorithm, and decided to discard handling the exception. I tried but i did not understand how to create an exception for "CalledProcessError". Maybe I will return to it for extra-credit. Its also kind of funny because I could get this down in perl fairly easy with $ping1 = ping -1 -o -t 192.168.113 . I am not trying to start a war, but so far it does not look like python is as good as perl for system prming. For right now, im going to continue on with my program. I did not mention this at first but I am creating a generic Network Scanner.

by the way. Here is a copy of the program I created with the help I received from this post.

#! /usr/bin/python
import commands

#ping -q -o -t 4 192.168.1.113

pingout = open('pingresults', 'a')


min = raw_input("Please enter minimum network range to be scanned ")
max = raw_input("please enter maximum network rant to be scanned ")

iplist = list(range(int(min),int(max)))

for ip in iplist:
     ipadrs = "192.168.2."+str(ip)


     #results = os.system("ping -q -o -t 4 ipadrs")
     #pingout.write(results)

     command_str = "ping -q -o -t 4 "+ipadrs+" | grep packets | awk -F \" \" \'{print $7}\' | awk -F \"\.\" \'{print $1}\'"

    output1 = commands.getoutput(command_str)
    output2 = int(output1)

    print ipadrs+" "+output1
    if output2 == 100:
        pingout.write(ipadrs+" No device is attached to this ip address\n ")

    else:
        pingout.write(ipadrs+" A device is attached to this ip address\n ")


pingout.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM