Building [Security] Dashboards w/R & Shiny + shinydashboard(转)

Jay & I cover dashboards in Chapter 10 of Data-Driven Security (the book) but have barely mentioned them on the blog. That’s about to change with a new series on building dashboards using the all-new shinydashboard framework developed by RStudio. While we won’t duplicate the full content from the book, we will show different types of dashboards along with the R code used to generate them.

Why R/Shiny/shinydashboard?

You can make dashboards in a cadre of programs: from Excel to PowerPoint, Tableau to MicroStrategy (a tool of choice for the “Godfather of Dashboards” - Stephen Few), Python to Ruby, plus many canned Saas tools. shinydashboards is compelling since it:

  • is completely free (unless you need or are compelled to purchase commerical support options)
  • provides substantial functionality and layout options out-of-the-box
  • facilitates connectivity with diverse dynamic data sources, including “big data” systems

It also enables the use of every data gathering, data munging, statistical, computational, visualization & machine-learning package R has to offer to help make your dashboards as meaningful, accurate and appealing as possible.

The shinydashboard framework is also pretty easy to wrap your head around once you dive into it. So, let’s do so right now!

Prerequisites

You’ll obviously need R, and we also recommend RStudio, especially since it has great support for developing Shiny apps.

You’ll also need the shiny and shinydashboard packages installed:

install.packages(c("devtools", "shiny"))
devtools::install_github("rstudio/shinydashboard")

We also make liberal use of the “hadleyverse” (the plethora of modern R packages created by Hadley Wickham). These include dplyrtidyrhttrrvest and others. Install them as you see them used/need them.

The Basic shinydashboard Framework

Shinydashboard runs on top of Shiny, and Shiny is an R package that presents a web front-end to back-end R processing. All Shiny apps define user-facing components (usually in a file called ui.R) and server-side processing components (usually in a file called server.R) and usereactive expressions to tie user actions (or timed triggers) to server events (or have server-side events change the user-interface). Shiny applications present themselves in a Bootstrap 3template and the shinydashboard package adds a further layer of abstraction, making it fairly simple to embed complex controls and visualizations without knowing (virtually) any HTML.

When building shinydashboards, you work with:

  • header components (titles, notificaitons, tasks & messages)
  • sidebar components (menus, links, input components)
  • main dashboard body (composed of “boxes”)

The following is the R version of that structure in a single-file shinydashboard app (app.R) without any extra components:

library(shiny)
library(shinydashboard)

# Simple header -----------------------------------------------------------

header <- dashboardHeader(title="CYBER Dashboard")

# No sidebar --------------------------------------------------------------

sidebar <- dashboardSidebar()

# Compose dashboard body --------------------------------------------------

body <- dashboardBody(
  fluidPage(
    fluidRow()
  )
)

# Setup Shiny app UI components -------------------------------------------

ui <- dashboardPage(header, sidebar, body, skin="black")

# Setup Shiny app back-end components -------------------------------------

server <- function(input, output) { }

# Render Shiny app --------------------------------------------------------

shinyApp(ui, server)

If you’re wondering what’s up with the long “# xyz ---” comments, RStudio will use them to provide block entries in the source code function navigation menu, making it really easy to find sections of code quite quickly.

Paste that into an RStudio file pane and source (run) it to see how it works (we’ll cover using it in the context of a Shiny server environment in another post).

Building a ‘Con’ Board

We infosec folk seem to really like “Con” (“current threat level”) gauges. We’ve got the SANSISC “Infocon”, Symantec’s “ThreatCon” and IBM X-Force’s “AlertCon” (to name just a few). Let’s build a dashboard that grabs the current “Con” status from each of those three places and puts them all into one place.

It’s always good to start with a wireframe layout for your dashboard (even though this is a pretty trivial one). Let’s have one row of shinydashboard valueBoxes:

which will normalize the look & feel of the alerts, and make a tap/select on each box take the user to the actual alert site for more details.

Since we’re going to be parsing JSON and HTML from various places, we’ll be making liberal use of the hadleyverse and some other packages:

library(shiny)
library(shinydashboard)
library(httr)
library(jsonlite)
library(data.table)
library(dplyr)
library(rvest)
library(magrittr)

The initial setup code looks the same as the basic example above, but it adds some elements to the fluidRow to give us places for our status boxes:

header <- dashboardHeader(title="CYBER Dashboard")

sidebar <- dashboardSidebar()

body <- dashboardBody(
  fluidPage(
    fluidRow(
      a(href="http://isc.sans.org/",
        target="_blank", uiOutput("infocon")),
      a(href="http://www.symantec.com/security_response/threatcon/",
        target="_blank", uiOutput("threatcon")),
      a(href="http://webapp.iss.net/gtoc/",
        target="_blank", uiOutput("alertcon"))
    )
  )
)

ui <- dashboardPage(header, sidebar, body, skin="black")

Now, in the server function, we have three sections, each performing data gathering, extraction and placement in the valueBoxes. We start with the easiest, the SANS ISC Infocon:

server <- function(input, output) {

  output$infocon <- renderUI({

    infocon_url <- "https://isc.sans.edu/api/infocon?json"
    infocon <- fromJSON(content(GET(infocon_url)))

    valueBox(
      value="Yellow",
      subtitle="SANS Infocon",
      icon=icon("bullseye"),
      color=ifelse(infocon$status=="test", "blue", infocon$status)
    )

  })

The output$infocon is tied to the uiOutput("infocon") in the dashboardBody and the setup code grabs the JSON from the DSheild API and ensures the right color and label is used for thevalueBox (I’m not entirely thrilled with the built-in color choices, but they can be customzed through CSS settings and we’ll cover that in a later post, too).

The remaning two section require finding the right HTML tags and extracting the con status from it, then tying the level to the right color. I use both CSS & XPath selectors in the following examples just to show how flexible the rvest package is (and I am a recoveringXML/XSLT/XPath user):

  output$threatcon <- renderUI({

    pg <- html("http://www.symantec.com/security_response/#")
    pg %>%
      html_nodes("div.colContentThreatCon > a") %>%
      html_text() %>%
      extract(1) -> threatcon_text

    tcon_map <- c("green", "yellow", "orange", "red")
    names(tcon_map) <- c("Level 1", "Level 2", "Level 3", "Level 4")
    threatcon_color <- unname(tcon_map[gsub(":.*$", "", threatcon_text)])

    threatcon_text <- gsub("^.*:", "", threatcon_text)

    valueBox(
      value=threatcon_text,
      subtitle="Symantec ThreatCon",
      icon=icon("tachometer"),
      color=threatcon_color
    )

  })

  output$alertcon <- renderUI({

    pg <- html("http://xforce.iss.net/")
    pg %>%
      html_nodes(xpath="//td[@class=‘newsevents‘]/p") %>%
      html_text() %>%
      gsub(" -.*$", "", .) -> alertcon_text

    acon_map <- c("green", "blue", "yellow", "red")
    names(acon_map) <- c("AlertCon 1", "AlertCon 2", "AlertCon 3", "AlertCon 4")
    alertcon_color <- unname(acon_map[alertcon_text])

    valueBox(
      value=alertcon_text,
      subtitle="IBM X-Force",
      icon=icon("warning"),
      color=alertcon_color
    )

  })

}

shinyApp(ui, server)

The result is a consistent themed set of internet situational awareness at a high level:

OK, I snuck some extra elements in on that screen capture, mostly as a hint of things to come. The core elements - the three “con” status boxes are unchanged from the simple example presented here.

You can find the code for the dashboard in this gist and you can even take a quick view of it (provided you’ve got the required packages installed) viashiny::runGist("e9e941ad4e3568f98faf"). As a general rule, I advise either running code locally (after inspection) or carefully examining the remote code first before blindly running foreign URLs. This is the R equivalent of curl http://example.com/script.sh | sh, which is also abad practice (unless it’s your own code).

Next Steps

The dashboard in this post loads all the data dynamically, but only once. In the next post, we’ll show you how to incorporate more data elements, incorporate dynamic updating capabilities and also add some other sections to the dashboard, including sidebar menus and header notifications.

转自:http://datadrivensecurity.info/blog/posts/2015/Jan/building-security-dashboards-with-r-and-shiny-shinydashboard/

时间: 2024-10-12 18:25:46

Building [Security] Dashboards w/R & Shiny + shinydashboard(转)的相关文章

R|Shiny练习

参考:https://docs.rstudio.com/shinyapps.io/ 1. 日期计算 仿照:http://bjtime.cn/riqi/ 链接:https://dingdangsunny.shinyapps.io/DateCalculate/ 练习Shiny基本输入输出. library(shiny) ui <- fluidPage( titlePanel("使用Shiny进行日期计算"), h4(textOutput("currentTime"

股票 W&amp;R威廉指标形态图解

一.用途 该指标表示的涵义是当天的收盘价在过去一段日子的全部价格范围内所处的相对位置,是一种兼具超买超卖和强弱分界的指标.它主要的作用在于辅助其他指标确认讯号. 二.使用方法 1. 从WR的绝对取值方面考虑. A.当WR 高于80,即处于超卖状态,行情即将见底,应当考虑买进. B.当WR 低于20,即处于超买状态,行情即将见顶,应当考虑卖出. C.WMS%R=50是多空平衡线,上穿或跌破此线,是稳健投资者的买卖信号. 2. 从WR的曲线形状考虑. A.在WR进入高位后,一般要回头,如果这时股价还

dual memory w/r comparison

单通道双通道 原文地址:https://blog.51cto.com/1960961732/2437745

Python3 文件读写r,w,a

1 # Author;Tsukasa 2 ''' 3 f = open('yesterday','w') #文件句柄...注意open分为'r'读模式,'w'写模式(d会先创建文件或者覆盖文件),'a'为追加模式(添加), 4 #data = f.read()#读取文件read() 5 f.write('hello') #注意如果要写文件的话 上面open模式要改 6 7 8 f = open('yesterday','a') 9 print(f.tell())#打印当前光标位置 10 #pri

文件操作 模式r+与w+

r+与w+ r+是读写模式,在文件的末尾进行追加操作. >>> myfile=open('pwd.txt', ... 'r+') >>> myfile.read() 'admin 123 1\nczz 121 0\nusr 123 0\n' >>> myfile.write('123') >>> myfile.read() '' >>> myfile.seek(0) >>> myfile.read(

SHINY-SERVER R(sparkR)语言web解决方案 架设shiny服务器

1. shiny server简介 shiny-server是一种可用把R 语言以web形式展示的服务,其实RStudio公司自己构建了R Shiny Application运行的平台(http://www.shinyapps.io/ ), 用户可以通过RStudio上面的工具把自己编写调试好的Shiny Application上传到shinyapps.io上去(这里需要先注册和设置些东西).这样构建了一个云端的服务器.但是有时还是有必要自己去构建一个自己的Shiny 服务器,这样操作起来还是方

python 读写文件中 w与wt ; r与rt 的区别

w,r,wt,rt都是python里面文件操作的模式. w是写模式,r是读模式. t是windows平台特有的所谓text mode(文本模式),区别在于会自动识别windows平台的换行符. 类Unix平台的换行符是\n,而windows平台用的是\r\n两个ASCII字符来表示换行,python内部采用的是\n来表示换行符. rt模式下,python在读取文本时会自动把\r\n转换成\n. wt模式下,Python写文件时会用\r\n来表示换行.

R语言包翻译

Shiny-cheatsheet 作者:周彦通 1.安装 install.packages("shinydashboard")  2.基础知识 仪表盘有三个部分:标题.侧边栏,身体.下面是最最小的仪表面板页面的UI: # ui.R #library(shinydashboard) dashboardPage( dashboardHeader(), dashboardSidebar(), dashboardBody()) 通过shinyApp()函数可以快速查看R控制台: # app.R

HDU 5033 Building

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5033 解题报告:在一条x轴上有n个建筑物,每个建筑物有一个高度h,然后现在有q次查询,查询的内容是假设有一个人站在xi这个位置,问他看天空的视角是多大,用角度表示. 数据量都比较大,n和q都是10^5,但因为q次都是查询操作,并没有要求在线更新和查询,所以我们想到用离线算法,先把全部的输入接收,然后离线算出最后打出结果. 这题的思路是把所有的建筑物按照高度从大到小排序,然后所有的查询按照x从小到大排