0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

sudo chmod 400 ~.pemをpowershellで

Posted at

目的

  • EC2インスタンスの起動のときにpemキーを発行できて、それでSSHなどができる。
  • マネジメントコンソールにはsudo chmod 400 hogehoge.pemしてからSSH実行とある
  • windowsではどうすればいいか

下記をpowershellに貼り付けてください。

# ============================
# chmod 400 相当(Windows/PowerShell, DACLのみ変更)
# 自分に Read だけ、Administrators / SYSTEM に FullControl
# ※ OpenSSH の厳格チェックに合う想定の最小セット
# ============================

param(
  [string]$File = "keypair.pem"
)

# 存在確認
if (-not (Test-Path -LiteralPath $File -PathType Leaf)) {
  Write-Error "ファイルが見つかりません: $File"
  exit 1
}

# フルパスへ正規化
$File = (Get-Item -LiteralPath $File).FullName

# 実行ユーザー "DOMAIN\User"
$user = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name

# ローカライズに依存しないよう Well-known SID から解決
$admins = (New-Object System.Security.Principal.SecurityIdentifier 'S-1-5-32-544').Translate([System.Security.Principal.NTAccount]) # BUILTIN\Administrators
$system = (New-Object System.Security.Principal.SecurityIdentifier 'S-1-5-18').Translate([System.Security.Principal.NTAccount])     # NT AUTHORITY\SYSTEM

# --- ここから DACL 操作(SACL/Owner には触れない) ---
# DACL だけを取得
$ac = [System.IO.File]::GetAccessControl($File, [System.Security.AccessControl.AccessControlSections]::Access)

# 継承を無効化(継承 ACE を引き継がない)
$ac.SetAccessRuleProtection($true, $false)

# 既存の明示的 ACE を全削除
$rules = $ac.GetAccessRules($true, $true, [System.Security.Principal.NTAccount])
foreach ($r in @($rules)) { $null = $ac.RemoveAccessRule($r) }

# 必要な ACE をだけ追加
$null = $ac.AddAccessRule([System.Security.AccessControl.FileSystemAccessRule]::new($user,   'Read',        'Allow'))
$null = $ac.AddAccessRule([System.Security.AccessControl.FileSystemAccessRule]::new($admins, 'FullControl', 'Allow'))
$null = $ac.AddAccessRule([System.Security.AccessControl.FileSystemAccessRule]::new($system, 'FullControl', 'Allow'))

# 反映(DACLのみ書き戻し)
[System.IO.File]::SetAccessControl($File, $ac)

# 結果表示(自分:(R)、Administrators:(F)、SYSTEM:(F) になっていればOK)
icacls $File

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?