【发布时间】:2021-11-22 17:54:51
【问题描述】:
我不熟悉编程和从事业余项目。 当某个条件为真时,我正在使用 python 中的子进程模块创建一个进程。
现在我想在其他条件为真时终止进程。
if new_lenght>old_length:
print("I will Record")
process = subprocess.Popen(['sudo', 'tcpdump', '-l', '-i', wlan_iface1, '-w',f'{new[-1]}.pcap'], stdout=subprocess.PIPE)
if new_lenght < old_length:
print("I will Stop")
更多代码 所以我正在使用我在 github https://github.com/Lynbarry/WiFinder 上找到的脚本并将其更改为做更多的事情。我所做的更改看起来很糟糕,我还编写了两次函数以更好地理解它。仍然有一些我不理解的部分,例如“UpdateHostList”函数。但是当我进行更多编辑时,我会以某种方式尝试弄清楚在代码中。
import netifaces
import netaddr
import nmap
import re
import sys
import time
import subprocess
import os
hostList = []
gracePeriod = 1
try:
nm = nmap.PortScanner() # instance of nmap.PortScanner
except nmap.PortScannerError:
print('Nmap not found', sys.exc_info()[0])
sys.exit(0)
except:
print("Unexpected error:", sys.exc_info()[0])
sys.exit(0)
def seek():
curHosts =[]
global wlan_iface
ifaces=netifaces.interfaces() #Get all the avalialbe interfaces
pattern = '^w' #Pattern maching for wlan interface
for position in range(len(ifaces)):
name = ifaces[position]
match_result = re.match(pattern,str(name))
if match_result:
wlan_iface=name
addrs = netifaces.ifaddresses(wlan_iface)
ipinfo = addrs[netifaces.AF_INET][0]
address = ipinfo['addr']
wlan_iface1=str(wlan_iface)
netmask = ipinfo['netmask']
# Create ip object and get CIDR
cidr = netaddr.IPNetwork('%s/%s' % (address, netmask))
a=str(cidr)
nm.scan(hosts = a, arguments = '-sn -T4')
# executes a ping scan
localtime = time.asctime(time.localtime(time.time()))
print('============ {0} ============\n'.format(localtime))
for host in nm.all_hosts():
curHosts.append((host,gracePeriod))
curHosts.remove((str(address),gracePeriod))
old=sniff_old()
old_length=len(old)
updateHostList(curHosts)
new=sniff_new()
new_lenght=len(new)
if new_lenght>old_length:
print("I will Record")
process = subprocess.Popen(['sudo', 'tcpdump', '-l', '-i', wlan_iface1, '-w', f'{new[-1]}.pcap'], stdout=subprocess.PIPE)
if new_lenght < old_length:
print("I will Stop")
process.kill()
process.terminate()
process.wait()
return len(hostList)
def sniff_new():
sniff_list=[]
for host in hostList:
sniff_list.append(host[0])
print(f"{sniff_list} NEW")
return((sniff_list))
def sniff_old():
sniff_list=[]
for host in hostList:
sniff_list.append(host[0])
old_sniff=(sniff_list)
print(f"{old_sniff} OLD")
return((old_sniff))
def updateHostList(curHosts):
global hostList
if hostList == []:
hostList = curHosts
else:
hostList = [(x[0],x[1]-1) for x in hostList]
# only the hosts that were new in this iteration
newList = [(x[0],x[1]) for x in curHosts if not (any(x[0]==y[0] for y in hostList))]
for host in newList:
hostList.append(host)
for host in hostList:
if any(host[0] == y[0] for y in curHosts):
hostList[hostList.index(host)] = (host[0],gracePeriod)
for host in hostList:
if host[1] <= 0:
hostList.remove(host)
def beep(): # no sound dependency
print('\a')
if __name__ == '__main__':
old_count = new_count = seek()
startCounter = gracePeriod
# are there any new hosts?
while True:
startCounter -= 1
time.sleep(1) # increase to slow down the speed
old_count = new_count
new_count = seek()
# DANGER!!!
【问题讨论】:
-
process.kill()将终止进程。 -
只有其中一个条件为真。如果第二个条件为真,您将不会创建进程,因此没有什么可以终止。
-
顺便说一句,当两个长度完全相等时,你想做什么?
if中的任何一个都不能处理。 -
谢谢!!我不确定是否可以在条件范围之外使用流程变量,但我会尝试一下。
-
Python 变量范围是按功能划分的,
if没有单独的范围。
标签: python subprocess tcpdump