Windowsイベントログに書き込む、イベントログから抽出する

===

イベントログに書き込むコマンド

 

Write-EventLog -LogName System -EntryType Error -Source 'Microsoft-Windows-Time-Service' -EventId 999 -Message “test event log error”

 

Write-EventLog -LogName System -EntryType Warning -Source 'Microsoft-Windows-Time-Service' -EventId 999 -Message “test event log warn”

 

===

イベントログから抽出するコマンド

wevtutil qe system /f:text /q:"*[System[Provider[@Name='Microsoft-Windows-Time-Service'] and TimeCreated[timediff(@SystemTime) <= 86400000]]]"

新人さんへ Powershellの基礎コマンド

#############################
#コマンド実行
#############################
$cmd1="Get-ChildItem"
$cmd1

Invoke-Expression $cmd1

#############################
#配列
#############################
$arg = @("a1","a2","a3")
$arg[0]

$arg2 = @(1,2,3,4,5,6,7,8)
$arg2[0..4]

$arg2[4]=-15
$arg2

$arg2.GetType()

Get-Member -InputObject $arg2

$arg2 = $arg2 +100
$arg2
$arg2 += 120
$arg2
$newarg =$arg2[0..2]+$arg2[8..9]
$newarg

#############################
#連想配列
#############################
$hsh = @{NRT="成田国際空港";HND="東京国際空港";KIX="関西国際空港";`
        NGO="中部国際空港"}
$hsh["NGO"]
$hsh.Keys
$hsh.Values
$hsh.GetType()
Get-Member -InputObject $hsh

$hsh.Values
$hsh.add("SFO","サンフランシスコ国際空港")
$hsh.Values

$hsh.remove("NRT")
$hsh.Values

[int] $a =10
[int] $b =20
$a+$b

[string] $a =10
[string] $b =20
$a+$b

#############################
#自動変数(用意されている変数
#############################
Get-Varia$pble

#############################
#Write-Outputでパイプラインに書き込む
#############################
cd $home
Write-Output $pwd | Get-Member

#############################
#引用符
#############################
Write-Host "dirは$pwd"
Write-Host 'dirは$pwd'

#############################
#変数のスコープ
#############################
$G="ブロックの外で定義するとデフォルトでグローバル変数"
$private:P="プライベート変数"

#スクリプトブロック
$exec={
#ローカル変数
Write-Host "ブロック開始==="
$L="ブロックの中で定義するとデフォルトでローカル変数"
Write-Host "ブロック外で定義したグローバル変数にアクセス可能 G=$G"
Write-Host "ブロック外で定義したプライベート変数にアクセス可能 P=$P"
Write-Host "ブロック内で定義したローカル変数にアクセス可能 L=$L"

$private:P2="ブロックの中で定義したプライベート変数"
Write-Host "ブロック終了==="
    }
#スクリプトブロック実行
&$exec

Write-Host "ブロック内で定義したローカル変数にアクセス不可 L=$L"
Write-Host "ブロック内で定義したプライベート変数にアクセス不可 P2=$P2"


#############################
#where
#############################
Get-ChildItem c:\ | Where-Object {$_.psiscontainer}


#############################
#ifとfor
#############################

#forとif組み合わせ
foreach ($item in Get-ChildItem C:\Users\Maasashi\Documents)
{
    if ($item.psiscontainer)
        {
        Write-Host $item.name -ForegroundColor Red
        }
    else
        {
        Write-Host $item.name -ForegroundColor Yellow
        }
}


#break
foreach ($item in Get-ChildItem C:\Users\Maasashi\Documents)
{
    if ($item.psiscontainer)
        {
        Write-Host $item.name -ForegroundColor Red
        }
    else
        {
        Break #ループの終了
        }
}

#Continue
foreach ($item in Get-ChildItem C:\Users\Maasashi\Documents)
{
    if ($item.psiscontainer)
        {
        continue #次のループ処理に移る
        }
    else
        {
        Write-Host $item.name -ForegroundColor Yellow
        }
}

#############################
#switch
#############################
$test=
{
    switch ($fault)
    {
    {$fault -le 3}{"アクセス失敗"}
    {($fault -gt 3) -and ($fault -le 7)}{"アクセス失敗が多発"}
    {$fault -gt 7}{"不正アクセス"}
    }
}

$fault = 3
&$test

$fault = 4
&$test

$fault = 8
&$test

#############################
#制御構文
#############################
Get-ChildItem c:\  | ForEach-Object {$_.GetType()} | ft Name

#############################
#配列の要素確認
#############################
$arg= Get-ChildItem c:\
$arg.Name
$arg.GetType()

$arg[0].Name
$arg[0].GetType()
$arg[0].GetType().BaseType

Write-Output $arg | ForEach-Object{$_.Name}

#############################
#ForEach
#############################
#ForEachのAlias確認
Get-Alias | Where-Object{$_.Definition -match "ForEach-Object"}

#Cドライブのリストを黄色で出力
$arg= Get-ChildItem c:\
ForEach($item in $arg){write-host $item.Name -ForegroundColor Yellow}

#上記と同じことをForEach内にコマンド直書き
ForEach($item in Get-ChildItem c:\)`
{Write-Host $item.Name -ForegroundColor Yellow}

#############################
#for
#############################
$ar = Get-ChildItem c:\
For ($i=0;$i -lt $ar.Count ; $i++)
{
    Write-Host $ar[$i].Name -ForegroundColor Yellow
}

#############################
#while
#############################
$ar = Get-ChildItem c:\
$index = 1
while ($index -lt $ar.Count)
{
    Write-Host $ar[$index].Name -ForegroundColor Yellow
    $index += 1
}

#############################
#do while
#############################
$ar = Get-ChildItem c:\
$index=0

Do
{
    Write-Host $ar[$index].Name -ForegroundColor Yellow
    $index += 1
}
while($index -lt $ar.Count)

#############################
#do until
#############################
$ar = Get-ChildItem c:\
$index=0

Do
{
    Write-Host $ar[$index].Name -ForegroundColor Yellow
    $index += 1
}
until($index -ge $ar.Count)


#############################
#関数
#############################
function ADDArg($arg1,$arg2)
{
    return $arg1 + $arg2
}
addarg 3 5

$ans = addarg 5 5
Write-Host "ans=$ans"

#############################
#関数 データ型指定
#############################

function ADDArg([int]$arg1,[int]$arg2)
{
    return $arg1 + $arg2
}
addarg 3 5

addarg 5 "b"


#############################
#関数 自動変数
#引数が、配列argsに勝手に格納される
#############################
function ADDArg()
{
    $sum=0
    $i=0
    ForEach($arg in $args)
    {
        
        Write-Host "args.$i===>"$args[$i]
        $sum += $arg
        $i += 1
    }
    $count = $arg.Count
    return $sum

}
addarg 3 5 10 100


#############################
#スクリプトブロックでの自動変数
#############################
$addarg={
    $sum=0
    $i=0
    ForEach($arg in $args)
    {
        
        Write-Host "args.$i===>"$args[$i]
        $sum += $arg
        $i += 1
    }
    $count = $arg.Count
    return $sum


}
&$addarg 3 5 10 100


#############################
#関数を使用したスクリプトの例
#############################

Function SayNumber($num,$flag)
{
    if($flag)
    {
        [System.Console]::Beep() #ビープ音
        Write-Host "$num !"

    }
    else
    {
        Write-Host "$num" -ForegroundColor White
    }
}

Function Finish()
{
    Write-Host "終了" -ForegroundColor Green
    Write-Host ""
}

#メイン処理
#3の倍数はtrue
[int32]$maxCount=Read-Host "いくつまで数えますか?"
for($count=1;$count -lt $maxCount + 1;$count++)
{
    if((($count %3) -eq 0) -or ($count -match "3"))
    {
        SayNumber $count $TRUE
    }
    else
    {
        SayNumber $count $FALSE
    }
    Sleep 1 #1秒待ち(Start-SleepのAlias)
}
Finish

#############################
#WMIオブジェクトのリスト
#############################
Get-WmiObject -List

Get-WmiObject -List | Where-Object{$_.Name -like "win32*"} | `
Sort-Object Name | Select-Object -First 100

Get-WmiObject -List | `
Where-Object{$_.Name -like "win32*disk*"} | `
Sort-Object Name | Format-Table Name



#############################
#WMIオブジェクト
#############################
Get-WmiObject -Class Win32_LogicalDisk
Get-WmiObject -Class Win32_ComputerSystem
Get-WmiObject -Class Win32_Environment
Get-WmiObject Win32_product | ft name,version
Get-WmiObject Win32_process | ft name,status
Get-WmiObject Win32_service  | Where-Object{$_.name -like "vmi*"}| ft name,state
Get-WmiObject Win32_operatingSystem


#############################
#WQL
#############################
Get-WmiObject -Query `
"select * from Win32_Service where name like '%in%'"


#############################
#PSドライブ(PowerShellのドライブ)
#############################
Get-PSDrive
pwd
Set-Location d:

Get-PSProvider

#Diskドライブ作成(マイPCにて接続ディスクがないため未検証
#New-PSDrive -Name X -PSProvider FileSystem -Root \\server1\testdirectory -Persist


#############################
#レジストリ
#############################
sl "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion"
pwd

Get-ChildItem
Get-Location

#PSドライブをCに変更してもPSProviderのロケーションは,それぞれ現在のキーが
#記憶されている
Set-Location "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion"
Set-Location c:
Get-Location -PSProvider Registry

Set-Location C:\PerfLogs
Set-Location "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion"
Get-Location -PSProvider FileSystem
#############################
#レジストリ 値取得
#############################
Set-Location "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion"
Get-Item .\Winlogon
$prop = Get-ItemProperty .\Winlogon
$prop.Shell
$prop.Userinit

#
#
Set-Location HKLM:\
Get-Item "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"
New-ItemProperty `
"HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"`
DefaultPassword -PropertyType String -Value 'Pa$$w0rd'
Get-Item "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"

ansibleで遊んだ時のメモ

Ansible導入

◆パッケージインストール
yum -y install パッケージ
<対象パッケージ>
bzip2-devel
sqlite-devel
git
patch
gcc
openssl-devel

cd /var/tmp
git clone https://github.com/tagomoris/xbuild.git
xbuild/python-install 2.7.6 /opt/python-2.7
/opt/python-2.7/bin/pip install ansible

◆ユーザ作成
groupadd -g 1500 ansuser
useradd -g ansuser -u 1500 ansuser -d /home/ansuser -s /bin/bash

◆プロファイル修正
vi ~/.bashrc
export PATH=/opt/python-2.7/bin:$PATH

SSH鍵作成
・ansibleサーバ→秘密鍵/公開鍵作成
ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/ansuser/.ssh/id_rsa): 鍵の名前
Enter passphrase (empty for no passphrase): ←空白で[Enter]キーを押す
Enter same passphrase again: ←空白で[Enter]キーを押す
※ここでパスワードを指定すると、パスワードが必要な鍵になってしまう
秘密鍵→id_rsa 。 公開鍵→id_rsa.pub

・ansibleサーバ→SSH接続の設定 .ssh/config
vi ~/.ssh/config
Host ホスト名
  HostName IP
  Port 22
  User root
  IdentityFile ~/gmo-vps.key

権限変更 chmod 755 ~/.ssh/config


・管理サーバ→公開鍵配置
vi ~/.ssh/authorized_keys
→~.pubをコピー

権限
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys


ssh接続確認
ssh ホスト名

◆ansible稼働確認
ansible -i ~/hosts ホスト名 -m ping


Playbookの基礎

◆イベントリファイルにグループを定義
vi ~/hosts
[test-servers]
ホスト名

◆vi test01.yml
- hosts: test-servers
  sudo: yes
  tasks:
    - name: be sure httpd is running and enabled
      service: name=httpd state=running enabled=yes

◆構文チェック
ansible-playbook -i ~/hosts test01.yml --syntax-check
playbook: test01.yml

◆タスク一覧
ansible-playbook -i ~/hosts test01.yml --list-tasks

playbook: test01.yml

  play #1 (test-servers):       TAGS:
    be sure httpd is running and enabled        TAGS:


◆シュミレーション(実際は実行しないが、どういう挙動になるか確認
ansible-playbook -i ~/hosts test01.yml --check

PLAY [test-servers] ***********************************************************

GATHERING FACTS ***************************************************************
ok: [xxx.xxx.xxx.xxx]

TASK: [be sure httpd is running and enabled] **********************************
changed: [xxx.xxx.xxx.xxx]

PLAY RECAP ********************************************************************
xxx.xxx.xxx.xxx            : ok=2    changed=1    unreachable=0    failed=0



◆PlayBookを実行
ansible-playbook -i ~/hosts test.yml

TIPS

ファイルの編集
http://tanksuzuki.com/post/ansible-config-control/

ループ
http://inforno.net/articles/2013/10/15/ansible-tips

外部から値を渡す
http://d.hatena.ne.jp/akishin999/20130818/1376824640

高度な使い方
https://github.com/shkumagai/ansible-doc-ja/blob/master/playbooks2.rst

with_itemsとvarsの組み合わせ
http://qiita.com/hnakamur/items/f8d8ceec3d0e8c4c3a86

file
file: リモートのファイルの設定変更を行う

copy
copy: ローカルのファイルをリモートにコピーするtemplate
template
template: 埋め込んだ変数を置換してファイルをリモートに配置する
    templateモジュール自体はファイルコピーとほぼ同じなのだが、変数部分を置換後にコピーするというのが違い。
http://blog.rutake.com/techmemo/2015/06/01/ansible-%E3%83%86%E3%83%B3%E3%83%97%E3%83%AC%E3%83%BC%E3%83%88%E3%82%92%E5%85%83%E3%81%AB%E5%A4%89%E6%95%B0%E3%82%92%E5%9F%8B%E3%82%81%E3%81%A6%E3%82%B3%E3%83%94%E3%83%BC%E3%81%99%E3%82%8Btemplate/
synchronize
synchronize: rsyncでディレクトリごと同期する

http://dev.classmethod.jp/server-side/ansible/ansible-file-modules-intro/

ansibleで実行対象を切り替える方法
http://tdoc.info/blog/2014/05/30/ansible_target_switching.html

マジック変数の一覧
http://qiita.com/h2suzuki/items/15609e0de4a2402803e9