GVKun编程网logo

在Snort警报上执行脚本(报警提示音脚本)

18

本文将为您提供关于在Snort警报上执行脚本的详细介绍,我们还将为您解释报警提示音脚本的相关知识,同时,我们还将为您提供关于Airtest自动化框架——单设备批量执行脚本、c–我可以在STL::vec

本文将为您提供关于在Snort警报上执行脚本的详细介绍,我们还将为您解释报警提示音脚本的相关知识,同时,我们还将为您提供关于Airtest自动化框架——单设备批量执行脚本、c – 我可以在STL :: vector :: iterator上执行指针算术、crontab 定时执行脚本出错,但手动执行脚本正常、Groovy Postbuild不会在Jenkins上执行脚本的实用信息。

本文目录一览:

在Snort警报上执行脚本(报警提示音脚本)

在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 + my
rpi.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
  • ptyselect

Airtest自动化框架——单设备批量执行脚本

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-&nbsp;<font color="DodgerBlue">{{results|length}}</font>,&nbsp;Success-&nbsp<font color="green">{{success}}</font>,&nbsp;Fail-&nbsp;<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上执行指针算术

c – 我可以在STL :: vector :: iterator上执行指针算术

目前我使用迭代器搜索一个向量并测试它的元素.我访问使用的元素
std::vector<int>::iterator it;
if (*it == 0);

我可以使用相同的指针算术风格逻辑来测试下一个元素(不改变我的迭代器)?

我首先需要看看它是否会将迭代器推出界限

if (it != myvec.end())

然后测试当前元素和下一个元素

if (*it == 1 && *(it + 1) == 1)

这个工作是否像我期望的那样使用指针?

解决方法

是的,std :: vector的迭代器是 random access iterators,所以你加/减积分值来获得其他有效的迭代器.

从技术上来说,它可能不是指针算术,但它们就像指针一样.

crontab 定时执行脚本出错,但手动执行脚本正常

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的小知识

但是最近在使用crontab过程中,接连遇到头疼的问题:手动执行脚本时一点问题都没有,可是放在 crontab中脚本死活也不运行。最后查出来原因一次是因为脚本里面文件路径没有写全路径导致的,另一次是因为脚本运行需要依赖java环境变量,其实 两次都是环境变量的问题造成的。从网上同样了解到一般crontab无法运行的问题都是由环境变量在crontab中不一定可识别引起的。某前辈总结 说:crontab如果不注意的话早晚会出问题,而且这种问题一旦出一次,就会永远记得,因为这种问题很折腾人。精辟啊~~
下面我也来试试总结下crontab的基本用法,环境变量以及其他要注意的问题。各位看官可以参考下,有什么问题也可以留言讨论。
 
————————————————————————————
1.crontab的基本用法
Usage: crontab [-u user] [-e|-l|-r]
Crontab 的格式说明如下:
* 逗号(‘,’) 指定列表值。如: “1,3,4,7,8″
* 中横线(‘-’) 指定范围值 如 “1-6″, 代表 “1,2,3,4,5,6″
* 星号 (‘*’) 代表所有可能的值
*/15 表示每 15 分钟执行一次
# Use the hash sign to prefix a comment
# +—————- minute (0 – 59)
# |  +————- hour (0 – 23)
# |  |  +———- day of month (1 – 31)
# |  |  |  +——- month (1 – 12)
# |  |  |  |  +—- day of week (0 – 7) (Sunday=0 or 7)
# |  |  |  |  |
# *  *  *  *  *  command to be executed
2.crontab与环境变量
不要假定cron知道所需要的特殊环境,它其实并不知道。所以你要保证在 shelll脚本中提供所有必要的路径和环境变量,除了一些自动设置的全局变量。所以注意如下3点:
1)脚本中涉及文件路径时写全局路径;
2)脚本执行要用到java或其他环境变量时,通过source命令引入环境变量,如:
cat start_cbp.sh
#!/bin/sh
source /etc/profile
export RUN_CONF=/home/d139/conf/platform/cbp/cbp_jboss.conf
/usr/local/jboss-4.0.5/bin/run.sh -c mev &
3)当手动执行脚本OK,但是crontab死活不执行时。这时必须大胆怀疑是环境变量惹的祸,并可以尝试在crontab中直接引入环境变量解决问题。如:
0 * * * * . /etc/profile;/bin/sh /var/www/java/audit_no_count/bin/restart_audit.sh
3.其他应该注意的问题
1)新创建的cron job,不会马上执行,至少要过2分钟才执行。如果重启cron则马上执行。
2)每条 JOB 执行完毕之后,系统会自动将输出发送邮件给当前系统用户。日积月累,非常的多,甚至会撑爆整个系统。所以每条 JOB 命令后面进行重定向处理是非常必要的: >/dev/null 2>&1 。前提是对 Job 中的命令需要正常输出已经作了一定的处理, 比如追加到某个特定日志文件。
3)当crontab突然失效时,可以尝试/etc/init.d/crond restart解决问题。或者查看日志看某个job有没有执行/报错tail -f /var/log/cron。
4)千万别乱运行crontab -r。它从Crontab目录(/var/spool/cron)中删除用户的Crontab文件。删除了该用户的所有crontab都没了。
5)在crontab中%是有特殊含义的,表示换行的意思。如果要用的话必须进行转义\%,如经常用的date ‘+%Y%m%d’在crontab里是不会执行的,应该换成date ‘+\%Y\%m\%d’`。
—————————————————————————————–
/etc/profile, /etc/bashrc, .bash_profile和.bashrc的差别
用户登陆Linux操作系统的时候,”/etc/profile”, “~/.bash_profile”等配置文件会被自动执行。执行过程是这样的:登陆Linux系统时,首先启动”/etc/profile”,然后启动 用户目录下的”~/.bash_profile”,如果”~/.bash_login”和”~/.profile”文件存在的时候也会在执行”~ /.bash_profile”后被依次调用。
——————
cat .bash_profile
# .bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
# User specific environment and startup programs
PATH=$PATH:$HOME/bin
export PATH
alias vi=vim
通过上面脚本可以看到~/.bash_profile文件先调用~/.bashrc,然后再把PATH加载。
——————
下面是一些区别:
/etc/profile:此文件为系统的每个用户设置环境信息,当用户第一次登录时,该文件被执行,并从/etc/profile.d目录的设置文件中搜集 shell的设置;
/etc/bashrc:为每一个运行bash shell的用户执行此文件,当bash shell被打开时,该文件被读取;
~/.bash_profile:每个用户都可使用该文件输入专用于自己使用的shell信息,当用户登录时,该文件仅仅执行一次!默认情况下,他设置一些环境变量,执行用户的.bashrc文件,
~/.bashrc:该文件包含专用于你的bash shell的bash信息,当登录时及每次打开新的shell时,该文件被读取;
~/.bash_logout:当每次退出系统(退出bash shell)时,执行该文件;
——–
/etc/profile是全局性的功能,其中设置的变量作用于所有用户,~/.bash_profile中设置的变量能继承/etc/profile中的变量并作用于用户。
~/.bash_profile 是交互式、login 方式进入 bash 运行的;~/.bashrc 是交互式 non-login 方式进入 bash 运行的。
参考:  https://www.cnblogs.com/gmq-sh/p/6971588.html

Groovy Postbuild不会在Jenkins上执行脚本

Groovy Postbuild不会在Jenkins上执行脚本

我写过简单的groovy脚本,但我不知道如何在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上执行脚本的相关信息,请在本站寻找。

本文标签: