本文将为您提供关于在Snort警报上执行脚本的详细介绍,我们还将为您解释报警提示音脚本的相关知识,同时,我们还将为您提供关于Airtest自动化框架——单设备批量执行脚本、c–我可以在STL::vec
本文将为您提供关于在Snort警报上执行脚本的详细介绍,我们还将为您解释报警提示音脚本的相关知识,同时,我们还将为您提供关于Airtest自动化框架——单设备批量执行脚本、c – 我可以在STL :: vector :: iterator上执行指针算术、crontab 定时执行脚本出错,但手动执行脚本正常、Groovy Postbuild不会在Jenkins上执行脚本的实用信息。
本文目录一览:- 在Snort警报上执行脚本(报警提示音脚本)
- Airtest自动化框架——单设备批量执行脚本
- c – 我可以在STL :: vector :: iterator上执行指针算术
- crontab 定时执行脚本出错,但手动执行脚本正常
- Groovy Postbuild不会在Jenkins上执行脚本
在Snort警报上执行脚本(报警提示音脚本)
我目前正在尝试使用Raspberry Pi。我正在运行Snort,这是数据包检测软件。在Snort发出警报的情况下,我想执行一个(Python)脚本。
Snort在树莓派上执行,如下所示:
sudo snort -q -A console -i eth0 -c /etc/snort/snort.conf
我创建了一个python脚本,该脚本在被调用时控制树莓派的GPIO引脚。在上下文中提供更多内容;当覆盆子pi收到ping /
ICMP数据包时,红色警报灯将亮起并由同一设备控制。
snort规则当前有效,并且当ICMP数据包到达时,警报将输出到控制台。但是我不知道如何通过snort执行python脚本
答案1
小编典典以下是3个选项,希望其中一个可以使用:
- “严格”
subprocess
的方式使用子的PIPE
小号 - 使用的方法
pexpect
-“ Pexpect是一个纯Python模块,用于生成子应用程序;对其进行控制;以及响应其输出中的预期模式。” -并非这是您必须与默认的python安装分开获取的唯一非标准软件包。 - 使用伪终端和旧版本
select
读取文件描述符的方法
每种方法都捆绑在一个try_[SOME APPROACH]
函数中。您应该能够在顶部更新3个参数,然后在底部注释/取消注释一种方法来尝试一下。
分别测试两个半部也许是值得的。换句话说,snort + myrpi.py
(下)。然后,如果timed_printer.py
可行,请使用我的(以下)和您的python脚本切换RPi
GPIO。如果它们都独立工作,那么您可以确信不需要做很多事情就能使整个工作流程正常运行。
码
import subprocess_cmd_lst = [''python'', ''-u'', ''timed_printer.py''] # sudo snort -q -A console -i eth0 -c /etc/snort/snort.conf_rpi_lst = [''python'', ''-u'', ''rpi.py''] # python script that toggles RPi_alert = ''TIME'' # The keyword you''re looking for # in snort output#===============================================================================# Simple helper function that calls the RPi toggle scriptdef toggle_rpi(): subprocess.call(_rpi_lst)def try_subprocess(cmd_lst, alert, rpi_lst): p = subprocess.Popen('' ''.join(cmd_lst), shell=True, stdout=subprocess.PIPE, bufsize=1) try: while True: for line in iter(p.stdout.readline, b''''): print("try_subprocess() read: %s" % line.strip()) if alert in line: print("try_subprocess() found alert: %s" % alert) toggle_rpi() except KeyboardInterrupt: print(" Caught Ctrl+C -- killing subprocess...") except Exception as ex: print ex finally: print("Cleaning up...") p.kill() print("Goodbye.")def try_pexpect(cmd_lst, alert, rpi_lst): import pexpect # http://pexpect.sourceforge.net/pexpect.html p = pexpect.spawn('' ''.join(cmd_lst)) try: while True: p.expect(alert) # This blocks until <alert> is found in the output of cmd_str print("try_pexpect() found alert: %s" % alert) toggle_rpi() except KeyboardInterrupt: print(" Caught Ctrl+C -- killing subprocess...") except Exception as ex: print ex finally: print("Cleaning up...") p.close(force=True) print("Goodbye.")def try_pty(cmd_lst, alert, rpi_lst, MAX_READ=2048): import pty, os, select mfd, sfd = pty.openpty() p = subprocess.Popen('' ''.join(cmd_lst), shell=True, stdout=sfd, bufsize=1) try: while True: rlist, _, _, = select.select([mfd], [], []) if rlist: data = os.read(mfd, MAX_READ) print("try_pty() read: %s" % data.strip()) if not data: print("try_pty() got EOF -- exiting") break if alert in data: print("try_pty() found alert: %s" % alert) toggle_rpi() elif p.poll() is not None: print("try_pty() had subprocess end -- exiting") break except KeyboardInterrupt: print(" Caught Ctrl+C -- killing subprocess...") except Exception as ex: print ex finally: print("Cleaning up...") os.close(sfd) os.close(mfd) p.kill() print("Goodbye.")#===============================================================================try_subprocess(_cmd_lst, _alert, _rpi_lst)#try_pexpect(_cmd_lst, _alert, _rpi_lst)#try_pty(_cmd_lst, _alert, _rpi_lst)
测试笔记
为了模拟您的snort脚本(一个“挂起”,然后打印一些内容,然后返回到挂起的脚本,等等),我编写了一个简单的python脚本,称为timed_printer.py
:
import timewhile True: print("TIME: %s" % time.time()) time.sleep(5)
我的rpi.py
文件很简单:
print("TOGGLING OUTPUT PIN")
此处没有显式的输出刷新,以尽力模拟正常的输出。
最后考虑
第一种方法将一次读取整行。因此,如果您希望alert
将其包含在一行中,就可以了。
第二种方法(pexpect
)将阻塞直到alert
遇到。
第三种方法将 在数据可用时立即 读取,我应该指出,这不一定是完整的。如果看到try_pty()read:
snort输出行的片段,导致您错过警报,则需要添加某种缓冲解决方案。
文件
subprocess
pexpect
pty
,select
Airtest自动化框架——单设备批量执行脚本
上期回顾:用.bat文件做Airtest脚本的多设备批量运行
最近在使用airtest进行app自动化,但是只能单个执行,实际需要批量执行。看了网上很多文章,其实很多都没真正实践或者说实践不完全,用的不好用。所以,就自己在那些文章的基础上进行了改进与优化。
一、结构
settings.py:放置配置信息,需要修改配置信息直接改改文件即可,不必到代码去改。
air:该项目下所有的.air文件都存放在这。可以在新建.air文件时直接放到此目录即可。
lib:公共方法库,看自己需求可将一些公共方法提取出来放到此文件夹下,方便重复调用。
log:将所有.air执行过程中的log和最终的html都放到该目录下
template:存放各种html模板的文件夹,可以放多个,需要变更时到settings.py里修改所要用的模板名称即可。
report:存放测试报告
二、执行文件
直接上代码:
from airtest.cli.runner import AirtestCase,run_script
import airtest.report.report as report
from conf.settings import *
from argparse import *
import shutil,os,io,jinja2,datetime
class Air_Case_Handler(AirtestCase):
def setUp(self):
super(Air_Case_Handler, self).setUp()
def tearDown(self):
super(Air_Case_Handler,self).tearDown()
def run_air(self,air_dir,device):
start_time = datetime.datetime.Now()
start_time_fmt = start_time.strftime("%Y-%m-%d %H:%M:%s.%f")[:-3]
results = []
root_log = log_path
if os.path.isdir(root_log):
shutil.rmtree(root_log)
else:
os.makedirs(root_log)
for file in os.listdir(air_path):
if file.endswith(".air"):
airName = file
airDirName = file.replace(".air","")
script = os.path.join(air_dir,file)
air_log = os.path.join(root_path,"log\\" + airDirName)
if os.path.isdir(air_log):
#print(air_log)
shutil.rmtree(air_log)
else:
os.makedirs(air_log)
html = os.path.join(air_log,"log.html")
args = Namespace(device=device, log = air_log, recording=None, script=script)
try:
run_script(args,AirtestCase)
except AssertionError as e:
pass
finally:
rpt = report.LogToHtml(script, air_log)
rpt.report("log_template.html", output_file=html)
result = {}
result["name"] = airName.replace('.air', '')
result["result"] = rpt.test_result
results.append(result)
end_time = datetime.datetime.Now()
end_time_fmt = end_time.strftime("%Y-%m-%d %H:%M:%s.%f")[:-3]
duration = (end_time - start_time).seconds
env = jinja2.Environment(
loader=jinja2.FileSystemloader(template_path),
extensions=(),
autoescape=True
)
template = env.get_template(template_name, template_path)
project_name = root_path.split("\\")[-1]
success = 0
fail = 0
for res in results:
if res['result']:
success += 1
else:
fail += 1
report_name = "report_"+end_time.strftime("%Y%m%d%H%M%s")+".html"
html = template.render({"results": results,"stime":start_time_fmt,'etime':end_time_fmt,'duration':duration,"project":project_name,"success":success,"fail":fail})
output_file = os.path.join(root_path,"report" ,report_name)
with io.open(output_file, 'w', encoding="utf-8") as f:
f.write(html)
if __name__ == "__main__":
test = Air_Case_Handler()
test.run_air(air_path,devices)
这样,执行下来会发现只要有个地方报错就会中断,不在执行剩余用例。原因在于airtest包里面的runner.py文件里的run_script方法写的是在遇到断言失败时,直接终止程序:sys.exit(-1),找到该文件 pthon\Lib\site-packages\airtest\cli\runner.py
改一下即可:
三、测试报告
先上效果图:
这个算朴素版的模板,有需要的可以自己再额外扩展。
几个点说明一下:
1、模板里的参数都来源于runcase.py,采用的是flask框架,参数通过template.render()来传递,可自行增删改。html里调用是通过{{varname}}实现的。
2、各个用例具体结果是放在log目录下,而report.html是放在report文件加下,所以template里的href路径要改为../log/xxxx
3、页面引用了jquery/echart/bootstrap都是线上引用,所以如果没上网的话可能界面会变得更朴素点哈
附:template_summary.html
<!DOCTYPE html>
<Meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="http://cdn.bootcss.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css">
<html>
<head>
<title>测试报告</title>
<style>
.fail {
color: red;
text-align: center;
}
.success {
color: green;
text-align: center;
}
.details-col-elapsed {
text-align: center;
}
.details-col-msg {
text-align: center;
background-color:#ccc;
}
</style>
</head>
<body>
<div>
<div >
<div https://www.jb51.cc/tag/heading/" target="_blank">heading">
<h2>
<span ><i ></i></span>《{{project}}》<small><font color="white">测试结果</font></small>
</h2>
</div>
<div >
<h4>
开始时间:<code>{{stime}}</code>
</h4>
<h4>
结束时间:<code>{{etime}}</code>
</h4>
<h4>
累计耗时:<code><span ><font color="blue">{{duration}}秒</font></span></code>
</h4>
<h4>测试结果:Total- <font color="DodgerBlue">{{results|length}}</font>, Success- <font color="green">{{success}}</font>, Fail- <font color="red">{{fail}}</font></h4>
<div >
<table width="800" border="thin" cellspacing="0" cellpadding="0" >
<tr width="600">
<th >序号</th>
<th width="300" >用例名称</th>
<th >执行结果</th>
</tr>
{% for r in results %}
<tr>
<td >{{loop.index}}</td>
<td ><a href="../log/{{r.name}}/log.html" target="view_window">{{r.name}}</a></td>
<td >{{"成功" if r.result else "失败"}}</td>
</tr>
{% endfor %}
</table>
</div>
<div >
<div id="pie_echarts" >
</div>
</div>
</div>
</div>
</body>
<script src="https://cdn.bootcss.com/echarts/4.4.0-rc.1/echarts.min.js"></script>
<script>
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('pie_echarts'));
// 指定图表的配置项和数据
option = {
title: {
text: '执行结果统计:',
x: 'left'
},
tooltip: {
trigger: 'item',
formatter: "{a} <br/>{b} : {c} ({d}%)"
},
color: ['#CD5C5C', '#9ACD32'],
stillShowZeroSum: false,
series: [
{
name: '测试结果',
type: 'pie',
radius: '80%',
center: ['60%', '60%'],
data: [
{value: {{fail|tojson}}, name: '失败'},
{value: {{success|tojson}}, name: '成功'}
],
itemStyle: {
emphasis: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(128, 128, 128, 0.5)'
}
}
}
]
};
// 使用刚指定的配置项和数据显示图表。
myChart.setoption(option);
</script>
</html>
四、执行
执行脚本必须cmd进入到目录下,用
Python runcase.py
才可以。不然会报
嗯。热乎的!刚出炉的!有实际实践的!希望有用。至此。
源码:https://pan.baidu.com/s/1XzgKAv01PC1fHTDlgeDBHg
解压密码:1234
————————————————
原文链接:
https://blog.csdn.net/ttphoon/article/details/102910119
c – 我可以在STL :: vector :: iterator上执行指针算术
std::vector<int>::iterator it; if (*it == 0);
我可以使用相同的指针算术风格逻辑来测试下一个元素(不改变我的迭代器)?
我首先需要看看它是否会将迭代器推出界限
if (it != myvec.end())
然后测试当前元素和下一个元素
if (*it == 1 && *(it + 1) == 1)
这个工作是否像我期望的那样使用指针?
解决方法
从技术上来说,它可能不是指针算术,但它们就像指针一样.
crontab 定时执行脚本出错,但手动执行脚本正常
原因: crontab 没有去读环境变量,需要再脚本中手动引入环境变量,可以用source 也可以用export 写死环境变量。
为了定时监控Linux系统CPU、内存、负载的使用情况,写了个Shell脚本,当达到一定值得时候,发送邮件通知。需要用到Crontab的定时任务去执行这个脚本,但是发现通过命令(./test.sh)执行Shell文件的时候,可以获取Linux的环境变量;可是通过Crontab做的定时任务,无法获取。
查找资料之后发现,crontab有一个坏毛病,就是它总是不会缺省的从用户profile文件中读取环境变量参数,经常导致在手工执行某个 脚本时是成功的,但是到crontab中试图让它定期执行时就是会出错。
2种方法可以解决这个问题,
1、在Shell文件里面获取环境变量值的路径写成绝对路径,别用环境变量的路径值。例如获取CPU的使用情况 通过绝对路径/proc/cpuinfo 来获取值;
2、Shell脚本缺省的#!/bin/sh开头换行后的第一行用
#!/bin/sh
. /etc/profile
. ~/.bash_profile
这样,crontab在执行脚本的时候,就能够读到用户的环境变量参数
备注:
如果你是在cron里提交的,请注意:
不要假定c r o n知道所需要的特殊环境,它其实并不知道。所以你要保证在s h e l l脚本中提供所有必要的路径和环境变量,除了一些自动设置的全局变量。
分享一些关于Crontab的小知识
Groovy Postbuild不会在Jenkins上执行脚本
看看这个简单的脚本:
String jbN = System.getenv(''JOB_NAME'') println jbN println "Hello"
我会除了我至少会尊敬“你好”.脚本不予回报.我刚收到Build步骤’Groovy Postbuild’标记构建为失败(或成功)
似乎脚本没有被执行.
编辑:
我没有添加它,但我已经有脚本来分析日志,所以我需要它在构建后执行它.
问题比我想的要大.插件:“Scriptler”或“Groovy插件”不打印任何内容.
我正在尝试打印的脚本:
String jbN = System.getenv(''JOB_NAME'') println jbN
解决方法
脚本已执行但未打印到控制台输出.
要将结果打印到控制台输出,您需要编写:
manager.listener.logger.println(“Some string”)而不是println.
为了缩短它:
variable = manager.listener.logger.& println
关于在Snort警报上执行脚本和报警提示音脚本的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于Airtest自动化框架——单设备批量执行脚本、c – 我可以在STL :: vector :: iterator上执行指针算术、crontab 定时执行脚本出错,但手动执行脚本正常、Groovy Postbuild不会在Jenkins上执行脚本的相关信息,请在本站寻找。
本文标签: