如何在Python中将系统命令赋值给变量

1 投票
4 回答
592 浏览
提问于 2025-04-18 17:18

我正在做一个项目,目的是帮助我学习Python。我意识到我可能在重复造轮子,因为外面可能已经有现成的ping模块。如果真有这样的模块,请不要给我建议,因为这个项目是为了让我学习Python。

我不会详细讲述我的整个项目。目前,我只是想把ping命令的输出结果赋值给一个变量。大部分情况下,我只对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

结果如下:

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

当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

4 个回答

0

顺便说一下,这是我根据这个帖子得到的帮助,创建的程序的副本。

#! /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()
0

谢谢你,TheSoundDefense。

我试了试:except:,效果非常好。我在其他论坛上搜索了这个算法,决定不处理异常。我尝试过,但不太明白怎么为“CalledProcessError”创建一个异常。也许我会再回去研究一下,争取额外的分数。其实这也挺有趣的,因为我在perl中可以很轻松地做到这一点,像这样:$ping1 = ping -1 -o -t 192.168.113。我不是想挑起争论,但到目前为止,看起来python在系统编程方面没有perl那么好。现在,我会继续我的程序。我一开始没提到这一点,但我正在创建一个通用的网络扫描器。

1

查看手册页(man ping)。如果 ping 命令返回 2,说明你发送的请求成功了,但没有收到回应。你也可以查看 这里这里

试着 ping 一下 www.google.com8.8.4.48.8.8.8),看看能不能成功。

2

你可能应该捕捉那个异常,并以那种方式处理这个情况。

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)

撰写回答