简体   繁体   English

如何在Python中为变量分配系统命令

[英]How can I assign a system command to a variable in Python

I am working on a project to help me learn python. 我正在研究一个帮助我学习python的项目。 I realize that I am probably reinventing the wheel, as there is probably a ping module out there. 我意识到我可能正在重新发明轮子,因为那里可能有一个ping模块。 If so please don't advise this, as this project is to help me learn python. 如果是这样,请不要建议这个,因为这个项目是为了帮助我学习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. 目前,我只是尝试将ping命令的输出分配给变量。 For the most part I am only interested in a certain portion of the ping output. 在大多数情况下,我只对ping输出的某个部分感兴趣。 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? 所以我的问题是如何解决这个问题,以便当网络地址不存在并且ping返回负面结果时它可以正常工作?

 #! /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: 当IP地址不存在时,我得到以下内容:

>>> ================================ 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 ). 检查手册页( man ping )。 Ping returning 2 means the ping was successfully sent but you're not getting a response. Ping返回2表示ping已成功发送,但您没有得到响应。 Check also here here 点击此处 查看

Try pinging www.google.com ( 8.8.4.4 or 8.8.8.8 ) and see if that works. 尝试ping www.google.com8.8.4.48.8.8.8 )并查看是否有效。

Thank you TheSoundDefense 谢谢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". 我试过,但我不明白如何为“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 . 它也很有趣,因为我可以通过$ ping1 = ping -1 -o -t 192.168.113在perl中轻松搞定。 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. 我并不是想开始一场战争,但到目前为止,看起来python并不像perl那样对系统进行打击。 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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