设为首页 收藏本站
查看: 643|回复: 0

powershell远程检查多个oracle数据库表空间使用率

[复制链接]

尚未签到

发表于 2018-9-1 12:22:27 | 显示全部楼层 |阅读模式
  作为一个大中企业的DBA,要面对众多大中小多个数据库,除了及时发现异常问题,还要及时了解数据库表空间占用率,掌握空间增长速度过快情况,防止数据库空间不足。
  本程序用powershell语言编写,通过配置文件所列清单,对数据库实例进行远程访问,获得除undo和临时表空间外其它表空间使用率,并按使用率进行由大到小的排序。
  本程序将先检测IP地址和端口侦听是不是正常,如果数据库实例无法远程访问,见及时继续下一个数据库实例,而不会无限等待。
  最主要的是将检查结果显示为html页面的一个表格内,使得检查结果直观,方便结果检查。
  以下为程序源代码:
  Add-PSSnapin VMware.VimAutomation.Core
  function filestring-search($inputFile,$matchstring,$matchcount){
  $tmpcontent = Get-Content $inputFile
  for($i=0;$i -le $tmpcontent.length;i++)
  {
  if($tmpcontent[$i] -like '*异常*'){
  $matchcount++
  wite-host matchcount: $matchcount  -background red
  }
  }
  return
  }
  Function ConvertTo-AdvHTML
  {   
  have the>  Must be at the beginning of the string.
  Example:
  [cellclass:highlight]10mb
  [rowclass:]              Designate the color, and other properties, of the

  row based on a>
  have the>  This control can be anywhere, in any property of the
  object.
  Example:
  [rowclass:greyishbold]
  [image:]

  Include an image in your cell.  Put>  in pixels and url seperated by semi-colons.  Format

  must be>  text in the cell, but the [image] tag must be at the

  end of the tag (so the>  Example:
  [image:100;200;http://www.sampleurl.com/sampleimage.jpg]Alt Text For Image
  [link:]         Include a link in your cell.  Other text is allowed in
  the string, but the [link] tag must be at the end of the
  string.
  Example:
  blah blah blah [link:www.thesurlyadmin.com]Cool PowerShell Link
  [linkpic:]
  This tag uses a picture which you can click on and go to the

  specified link.  You must specify the>  url where it is located, this information is seperated by semi-
  colons.  Other text is allowed in the string, but the [link] tag
  must be at the end of the string.
  Example:
  [linkpic:100;200;http://www.sampleurl.com/sampleimage.jpg]www.thesurlyadmin.com
  [bar:]
  Bar graph makes a simple colored bar graph within the cell.  The
  length of the bar is controlled using .  You can
  designate the color of the bar, and the color of the remainder
  section.  Due to the mysteries of HTML, you must designate a

  >  So if you had a percentage of 95, say 95% used disk you
  would want to highlight the remainder for your report:
  Example:
  [bar:95;dark green;red]5% free
  What if you were at 30% of a sales goal with only 2 weeks left in
  the quarter, you would want to highlight that you have a problem.
  Example:
  [bar:30;darkred;red]30% of goal
  .PARAMETER InputObject
  The object you want converted to an HTML table
  .PARAMETER HeadWidth

  You can specify the>  and are passed to the parameter in array format.  Each element
  in the array corresponds to the column in your table, any element
  that is set to 0 will designate the column with be dynamic.  If you had
  four elements in your InputObject and wanted to make the 4th a fixed

  >  -HeadWidth 0,0,0,600
  .PARAMETER CSS
  Designate custom CSS for your HTML

  .PARAMETER>
  Specifies a>  .PARAMETER PreContent
  Specifies text to add before the opening  tag. By default, there is no text in that position.
  .PARAMETER PostContent
  Specifies text to add after the closing  tag. By default, there is no text in that position.
  .PARAMETER Body
  Specifies the text to add after the opening  tag. By default, there is no text in that position.
  .PARAMETER Fragment

  Generates only an HTML table. The HTML, HEAD,>  .INPUTS
  System.Management.Automation.PSObject
  You can pipe any .NET object to ConvertTo-AdvHtml.
  .OUTPUTS
  System.String
  ConvertTo-AdvHtml returns series of strings that comprise valid HTML.
  .EXAMPLE
  $Data = @"
  Server,Description,Status,Disk
  [row:orchid]Server1,Hello1,[cellclass:up]Up,"[bar:45;Purple;Orchid]55% Free"
  Server2,Hello2,[cell:green]Up,"[bar:65;DarkGreen;Green]65% Used"
  Server3,Goodbye3,[cell:red]Down,"[bar:95;DarkGreen;DarkRed]5% Free"
  server4,This is quite a cool test,[cell:green]Up,"[image:150;650;http://pughspace.files.wordpress.com/2014/01/test-connection.png]Test Images"
  server5,SurlyAdmin,[cell:red]Down,"[link:http://thesurlyadmin.com]The Surly Admin"
  server6,MoreSurlyAdmin,[cell:purple]Updating,"[linkpic:150;650;http://pughspace.files.wordpress.com/2014/01/test-connection.png]http://thesurlyadmin.com"
  "@
  $Data = $Data | ConvertFrom-Csv
  $HTML = $Data | ConvertTo-AdvHTML -HeadWidth 0,0,0,600 -PreContent "This might be the best report EVER" -PostContent "Done! $(Get-Date)" -Title "Cool Test!"
  This is some sample code where I try to put every possibile tag and use into a single set
  of data.  $Data is the PSObject 4 columns.  Default CSS is used, so the [cellclass:up] tag
  will not work but I left it there so you can see how to use it.
  .NOTES
  Author:             Martin Pugh
  Twitter:            @thesurlyadm1n
  Spiceworks:         Martin9700
  Blog:               www.thesurlyadmin.com
  Changelog:

  1.0             Initial>  .LINK
  http://thesurlyadmin.com/convertto-advhtml-help/
  .LINK
  http://community.spiceworks.com/scripts/show/2448-create-advanced-html-tables-in-powershell-convertto-advhtml
  #>
  #requires -Version 2.0
  [CmdletBinding()]
  Param (
  [Parameter(Mandatory=$true,
  ValueFromPipeline=$true)]
  [Object[]]$InputObject,
  [string[]]$HeadWidth,
  [string]$CSS = @"
  
  TABLE {border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}
  TH {border-width: 1px;padding: 3px;border-style: solid;border-color: black;background-color: #6495ED;font-size:120%;}
  TD {border-width: 1px;padding: 3px;border-style: solid;border-color: black;}
  
  "@,
  [string]$Title,
  [string]$PreContent,
  [string]$PostContent,
  [string]$Body,
  [switch]$Fragment
  )
  Begin {
  If ($Title)
  {   $CSS += "`n$Title`n"
  }
  $Params = @{
  Head = $CSS
  }
  If ($PreContent)
  {   $Params.Add("PreContent",$PreContent)
  }
  If ($PostContent)
  {   $Params.Add("PostContent",$PostContent)
  }
  If ($Body)
  {   $Params.Add("Body",$Body)
  }
  If ($Fragment)
  {   $Params.Add("Fragment",$true)
  }
  $Data = @()
  }
  Process {
  ForEach ($Line in $InputObject)
  {   $Data += $Line
  }
  }
  End {
  $Html = $Data | ConvertTo-Html @Params
  $NewHTML = @()
  ForEach ($Line in $Html)
  {   If ($Line -like "**")
  {   If ($Headwidth)
  {   $Index = 0
  $Reg = $Line | Select-String -AllMatches -Pattern "(.*?)"
  ForEach ($th in $Reg.Matches)
  {   If ($Index -le ($HeadWidth.Count - 1))
  {   If ($HeadWidth[$Index] -and $HeadWidth[$Index] -gt 0)
  {   $Line = $Line.Replace($th.Value,"$($th.Groups[1])")
  }
  }
  $Index ++
  }
  }
  }
  Do {
  Switch -regex ($Line)
  {   "\[cell:(.*?)\].*?"
  {   $Line = $Line.Replace("[cell:$($Matches[1])]","")
  Break
  }
  "\[cellclass:(.*?)\]"
  {   $Line = $Line.Replace("[cellclass:$($Matches[1])]","")
  Break
  }
  "\[row:(.*?)\]"
  {   $Line = $Line.Replace("","")
  $Line = $Line.Replace("[row:$($Matches[1])]","")
  Break
  }
  "\[rowclass:(.*?)\]"
  {   $Line = $Line.Replace("","")
  $Line = $Line.Replace("[rowclass:$($Matches[1])]","")
  Break
  }
  "\[bar:(.*?)\](.*?)"
  {   $Bar = $Matches[1].Split(";")
  $Width = 100 - [int]$Bar[0]
  If (-not $Matches[2])
  {   $Text = " "
  }
  Else
  {   $Text = $Matches[2]
  }
  $Line = $Line.Replace($Matches[0],"$Text ")
  Break
  }
  "\[image:(.*?)\](.*?)"
  {   $Image = $Matches[1].Split(";")

  $Line = $Line.Replace($Matches[0],"  }
  "\[link:(.*?)\](.*?)"
  {   $Line = $Line.Replace($Matches[0],"$($Matches[2])")
  }
  "\[linkpic:(.*?)\](.*?)"
  {   $Images = $Matches[1].Split(";")

  $Line = $Line.Replace($Matches[0],"  }
  Default
  {   Break
  }
  }
  } Until ($Line -notmatch "\[.*?\]")
  $NewHTML += $Line
  }
  Return $NewHTML
  }
  }
  function DownloadFile($Username,$Password,$RemoteFile,$LocalFile){
  try
  {
  $ErrorActionPreference="Stop";
  if($RemoteFile -eq $null){
  REM "RemoteFile is null"
  return
  }
  if($LocalFile -eq $null){
  REM "LocalFile is null"
  return
  }
  $FTPRequest = [System.Net.FtpWebRequest]::Create($RemoteFile)
  $FTPRequest.Credentials = New-Object System.Net.NetworkCredential($Username,$Password)
  $FTPRequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
  $FTPRequest.UseBinary = $true
  $FTPRequest.KeepAlive = $false
  # Send the ftp request
  $FTPResponse = $FTPRequest.GetResponse()
  # Get a download stream from the server response
  $ResponseStream = $FTPResponse.GetResponseStream()
  # Create the target file on the local system and the download buffer
  $LocalFileFile = New-Object IO.FileStream ($LocalFile,[IO.FileMode]::Create)
  [byte[]]$ReadBuffer = New-Object byte[] 1024
  if($ResponseStream -eq $null){
  REM "$RemoteFile Download ERR"
  return
  }
  # Loop through the download
  do {
  $ReadLength = $ResponseStream.Read($ReadBuffer,0,1024)
  $LocalFileFile.Write($ReadBuffer,0,$ReadLength)
  }
  while ($ReadLength -ne 0)
  $LocalFileFile.close()
  $ResponseStream.close()
  $ResponseStream.dispose
  REM "$RemoteFile Download OK"
  }
  catch
  {
  REM("Exception Msg: $_")
  }
  }
  function REM($Msg){
  $now= Get-Date
  write-host "$now : $Msg" -foregroundcolor Yellow
  Add-Content $LogFilePath "$now : $Msg"
  }
  #   AIX_51host_B_all_2016070119_result.txtLinux_BJAPTC10_all_2016070119_result.txt
  #   $b = ls C:\DayCheck\
  #   "OS","APP","IP","NAME"
  #Test-Port -ComputerName TestServer  list_port
  function Test-Port
  {
  Param([string]$ComputerName,$ListPort ,$timeout = 1000)
  try
  {
  $tcpclient = New-Object -TypeName system.Net.Sockets.TcpClient
  $iar = $tcpclient.BeginConnect($ComputerName,$ListPort,$null,$null)
  $wait = $iar.AsyncWaitHandle.WaitOne($timeout,$false)
  if(!$wait)
  {
  $tcpclient.Close()
  return $false
  }
  else
  {
  # Close the connection and report the error if there is one
  $null = $tcpclient.EndConnect($iar)
  $tcpclient.Close()
  return $true
  }
  }
  catch
  {
  $false
  }
  }
  # ####################################################################################v
  $today = Get-Date -UFormat "%Y%m%d"
  $LogFilePath = "C:\DayCheck\ftpLog_$today.txt"
  $today = Get-Date -UFormat "%Y%m%d"
  $TargetFileTxt=  "C:\DayCheck\OracleCheckResultALL.txt"
  $TargetFileHtml=  "C:\DayCheck\OracleCheckResultALL.html"
  if( Test-Path $TargetFileTxt ){
  write-host  "$TargetFileTxt exist remove"
  remove-item $TargetFileTxt -Force
  }else {
  write-host "create $TargetFileTxt "
  New-Item -Path $TargetFileTxt -Type file
  }
  remove-item C:\DayCheck\ResultOut.txt -Force
  remove-item C:\DayCheck\OracleCheckResult* -Force
  New-Item -Path  C:\DayCheck\*_result.txt  -Type file
  New-Item -Path  C:\DayCheck\OracleCheckResultSummaryALL.txt  -Type file
  New-Item -Path  C:\DayCheck\ResultOut.txt  -Type file
  New-Item -Path  C:\DayCheck\OracleCheckResultALL.txt  -Type file
  $UserName = "daycheck"
  $Password = "daycheck"
  "IP,INSTANCE,TABESPALCE_NAME,SIZE,Pct_Used"    |  Out-File  -Encoding utf8   C:\DayCheck\OracleCheckResultSummaryALL_TOTAL.csv
  Import-Csv 'C:\DayCheck\OracleList.csv'  |ForEach-Object{
  $IP = $_.IP
  $STRING = $_.STRING
  $PORT = $_.PORT
  $INSTANCE = $_.INSTANCE
  $ConnectStatus =Test-Port -ComputerName $IP  -ListPort $PORT
  if ( $ConnectStatus -eq "True" ){
  $SqlplusCommand = "sqlplus -s " + $STRING + "@"+ $IP + ":"+ $PORT + "/"+ $INSTANCE + " as sysdba "+ "@C:\DayCheck\oracheck_space.sql"
  $SqlplusCommand
  "TABESPALCE_NAME,SIZE,Pct_Used"|  Out-File  -Encoding utf8  C:\DayCheck\OracleCheckResult.csv
  cmd /c $SqlplusCommand | Out-File   -Encoding utf8   -append  C:\DayCheck\OracleCheckResult.csv
  Get-Content C:\DayCheck\OracleCheckResult.csv  | where { !([string]::IsNullOrWhiteSpace($_))} |Out-File   -Encoding utf8   C:\DayCheck\OracleCheckResult_ttt.csv
  Import-Csv C:\DayCheck\OracleCheckResult_ttt.csv  |ForEach-Object{
  $TABESPALCE_NAME = $_.TABESPALCE_NAME
  $SIZE = $_.SIZE
  $Pct_Used = $_.Pct_Used
  "$IP,$INSTANCE,$TABESPALCE_NAME,$SIZE,$Pct_Used"
  "$IP,$INSTANCE,$TABESPALCE_NAME,$SIZE,$Pct_Used"|Out-File  -Encoding utf8 -append  C:\DayCheck\OracleCheckResultSummaryALL_TOTAL.csv
  }
  remove-item C:\DayCheck\OracleCheckResult.csv -Force
  }else {
  "$IP,$INSTANCE,$PORT,NotConnect,NotConnect"|Out-File  -Encoding utf8 -append  C:\DayCheck\OracleCheckResultSummaryALL_TOTAL.csv
  }
  }
  import-csv C:\DayCheck\OracleCheckResultSummaryALL_TOTAL.csv | ConvertTo-advhtml |Set-Content  "C:\DayCheck\OracleCheckResultSummaryALL_TOTAL.html"
  invoke-item "C:\DayCheck\OracleCheckResultSummaryALL_TOTAL.html"
  ====================file oraclelist.csv====================================
  "IP","STRING","PORT","INSTANCE","APPNAME"
  "192.168.0.90","sys/oracle","1521","wcmdb","wcmdb"
  "192.168.0.102","sys/oracle","1521","racdb","racdb"
  ======================file  oracheck_space.sql====================================
  SET ECHO        OFF
  SET FEEDBACK OFF
  SET HEADING     OFF
  SET LINESIZE    180
  SET PAGESIZE    50000
  SET TERMOUT     ON
  SET TIMING      OFF
  SET TRIMOUT     ON
  SET TRIMSPOOL   ON
  SET VERIFY      OFF
  SELECT Upper(F.TABLESPACE_NAME)||','||D.TOT_GROOTTE_MB||','||To_char(Round(( D.TOT_GROOTTE_MB - F.TOTAL_BYTES ) / D.TOT_GROOTTE_MB * 100, 2), '990.99')  FROM   (SELECT TABLESPACE_NAME,
  Round(Sum(BYTES) / ( 1024 * 1024 ), 2) TOTAL_BYTES,
  Round(Max(BYTES) / ( 1024 * 1024 ), 2) MAX_BYTES
  FROM   SYS.DBA_FREE_SPACE where  Upper(TABLESPACE_NAME) not like '%UNDO%'
  GROUP  BY TABLESPACE_NAME) F,
  (SELECT DD.TABLESPACE_NAME,
  Round(Sum(DD.BYTES) / ( 1024 * 1024 ), 2) TOT_GROOTTE_MB
  FROM   SYS.DBA_DATA_FILES DD  where (TABLESPACE_NAME not like '%UNDO%' )or  (TABLESPACE_NAME not like '%undo%')
  GROUP  BY DD.TABLESPACE_NAME) D
  WHERE  D.TABLESPACE_NAME = F.TABLESPACE_NAME
  ORDER  BY  To_char(Round(( D.TOT_GROOTTE_MB - F.TOTAL_BYTES ) / D.TOT_GROOTTE_MB * 100, 2), '990.99') desc
  /
  exit


运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-561109-1-1.html 上篇帖子: Powershell命令中的 CommonParameters是指什么 下篇帖子: 一些powershell指令
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表