ゲスト.
レベル 1 ユーザー
登録不要。進捗はブラウザに保存されます。セーブコードをエクスポートして別デバイスでもプレイ可能。
獲得したバッジ一覧
オンラインLinuxターミナル実践 — 実践して学ぶ
無料のBash学習ゲームとファイルシステムシミュレーションを通じて、必須のLinuxコマンドを習得します。
インタラクティブな学習パスとターミナル目標
体系的な目標を備えたLinux学習パス。ロック解除されたノードをクリックしてワークスペースを開きます。
1. ファイルシステムの基本
私は誰で、どこにいますか?
何百万もの本が蔵書されている暗くて巨大な図書館に足を踏み入れたところを想像してみてください。しかし、地図はなく、自分の名札さえ思い出せません。何かを調べる前に、自分が誰で、どこに立っているのかを知る必要があります。 Linux シェルでは、まったく同じ質問から始めます。 - `whoami` コマンドは、現在ログインしているユーザー名を出力します。 - `pwd` (作業ディレクトリの表示) コマンドは GPS のように機能し、現在いる場所の正確なフォルダー パスを表示します。
ファイルの移動とリスト
自分がどこにいるかはわかったので、このデジタル ライブラリ内の別の部屋に移動するにはどうすればよいでしょうか? Linux では、次の 2 つの簡単なコマンドを使用してこれを行います。 - `ls`: 部屋の照明をオンにして、その中にあるすべてのファイルとフォルダーを確認するようなものです。 - `cd <path>`: 「ディレクトリ変更」の略で、ドアを通って別のフォルダに移動できます。 行き先を指定するには、**絶対** パス (`/var/log` など、システムのまさにルート `/` から始まる) または **相対** パス (`..` を使用して親フォルダーに戻るなど、現在の場所に基づく) を使用できます。
Listing Detailed Information
A standard `ls` lists only the names of files, giving you no indication of how large they are, who owns them, or when they were last modified. In Linux, we inspect detailed file metadata using the long listing option: - The `-l` (long) option shows permissions, link counts, file owner, group, exact size in bytes, and last modification date. - The `-h` (human-readable) option, when combined with `-l` as `ls -lh`, translates raw byte counts into intuitive units like `K` (kilobytes), `M` (megabytes), and `G` (gigabytes).
ディレクトリの作成
机の上にバラバラの紙が山積みになっており、整理整頓するために物理的なフォルダーが必要であると想像してください。 Linux では、`mkdir` (ディレクトリの作成) コマンドを使用してフォルダー (ディレクトリ) を作成し、ファイルを整理します。 `mkdir code` を実行すると、現在の場所に「code」という名前の新しいフォルダーが作成されます。 `mkdir` に相対パスまたは絶対パスを指定すると、ファイル システム内の任意の場所にフォルダーを作成できます。
入れ子になったディレクトリとオプション
一連の入れ子人形を構築しようとしているところを想像してください。ただし、内側の小さな人形を構築する前に、最も外側の人形を構築する必要があります。デフォルトでは、`mkdir` はそのようになっており、まだ存在しないフォルダーの奥深くにフォルダーを作成することを拒否します。フォルダーを 1 つずつ作成する手間を省くために、スイッチを使用します。 - `-p` (または `--parents`) オプションは、最終フォルダーに到達する途中で不足している親フォルダーを自動的に構築するように `mkdir` に指示します。たとえば、`mkdir -p workspace/src/utils` は、`workspace`、`workspace/src`、および `workspace/src/utils` をすべて 1 つのコマンドで作成します。 **これが重要な理由**: `-p` を使用せずに `mkdir workspace/src/utils` を実行し、`workspace` と `workspace/src` がまだ存在しない場合、`mkdir: cannot create directory 'workspace/src/utils': No such file or directory` が得られます。 `-p` フラグは、不足している親フォルダーをすべて自動的に作成することでこの問題を修正します。
Visualizing Directory Trees (tree)
When navigating complex project directories, flat listings from `ls` make it difficult to visualize nested structures. The `tree` command recursively lists directory contents in a clear, tree-like ASCII visual hierarchy with branch lines showing directory nesting. In large repositories, a full recursive tree can produce thousands of lines. To keep output manageable, use the `-L <level>` switch (e.g., `tree -L 2`) to restrict visualization depth to a specific number of directory levels.
Linux ディレクトリ構造と FHS
すべての Linux システムは、ルート ディレクトリ `/` から始まる標準のファイルシステム階層に従います。 Windows (`C:` や `D:` などのドライブ文字を使用する) とは異なり、Linux はすべてのファイルとストレージを `/` の下に統合します。 すべての Linux ユーザーが知っておくべき主要なシステム ディレクトリは次のとおりです。 - `/` (ルート): システム全体の最上位の親フォルダー。 - `/etc`: システム構成を保持します (例: `/etc/hosts`、`/etc/passwd`)。 - `/var`: 時間の経過とともに変化する可変データ (`/var/log` のようなログ、スプール、キャッシュ) を保持します。 - `/home`: ユーザーの個人フォルダー (例: `/home/learner`)。 - `/tmp`: 一時ファイル用の一時ストレージ領域。 - `/usr`: ユーザー ユーティリティ、アプリケーション、およびシステム ライブラリ。
Inspecting File Types & Metadata (file & stat)
In Linux, file extensions (like `.txt` or `.png`) are merely hints for humans—the operating system does not rely on them. To identify what a file truly contains, the `file` command reads the file's binary header (magic bytes) and determines its actual format (ASCII text, ELF executable, gzip archive, etc.). To inspect deep filesystem metadata beyond what `ls -l` shows, the `stat` command displays the file's exact size in bytes, allocated blocks, filesystem inode number, octal access permissions (e.g. `0644`), and exact timestamps: Access (`atime`), Modify (`mtime`), and Change (`ctime`).
画面をクリアする
デスクが乱雑なメモや書類で覆われていて圧倒されてしまったことはありませんか?端末も同様に乱雑になる可能性があります。その場合は、古いテキストをすべて一掃して、新たに始めることができます。 - `clear` コマンドは、表示されている画面をきれいに消去し、以前の出力を表示の外にスライドさせて、ターミナルの上部に新しい空白のキャンバスを表示します。
シェル ヘルプの検索
新しいボード ゲームを購入するときは、通常、ルールブックまたはリファレンス カードを覗いて、どのような手が許可されているかを確認します。私たちのターミナル エミュレーターには、チート シートが組み込まれています。 - `help` コマンドは、このシミュレーターがサポートするすべてのコマンドと、出力のパイプまたはリダイレクトをサポートするかどうかの詳細をリストします。
Boss Challenge 1: The Wiped Project Tree
EMERGENCY ALERT: A faulty CI/CD deployment script executed an unconstrained cleanup routine and wiped the directory tree under `/home/learner/app`. The backend production daemon refuses to start until the project directory structure is restored. To recover, you must reconstruct the missing directory hierarchy: create `/home/learner/app/logs`, `/home/learner/app/config`, and the nested module directory `/home/learner/app/src/modules`. No step-by-step hints are provided for Boss Challenges. Inspect the system, plan your approach, and verify your filesystem state.
2. ファイル操作
空のファイルの作成
新しい日記エントリを書き始めたいと考えているところを想像してください。しかし、その前に白紙の紙が必要です。 Linux では、`touch` コマンドを使用して、新しい空のテキスト ファイルを取得します。 - `touch` コマンドは、新しい空のファイルが存在しない場合に作成します (`touch draft.txt` を実行して `draft.txt` を作成する場合など)。ファイルがすでに存在する場合、ファイルの内容は変更せずに、ファイルの「最終変更」タイムスタンプを更新するだけです。新しいプロジェクト フォルダーにファイルを置きましょう。
ファイルの内容を読む
フォルダーを開いてテキストのページを取り出し、それをかざして読むことを考えてください。 Linux では、`cat` (連結) コマンドを使用して、重いテキスト エディターを開かずにファイルを即座に読み取ります。 - `cat` コマンドは、ファイルの内容全体を端末画面に直接出力します。たとえば、`cat notes.txt` を実行すると、`notes.txt` 内に何が書かれているかをすぐに確認できます。
ファイルの覗き見 (head & tail)
`cat` を使用してファイル全体を読み取ることができるようになりましたが、ファイルに数千行があり、先頭または末尾のみを確認したい場合はどうすればよいでしょうか。 `cat` を含む巨大なファイルをダンプすると、画面があふれてしまいます。代わりに、`head` と `tail` を使用してエッジを確認します。 - `head` コマンドは、デフォルトでファイルの最初の 10 行を表示します。これは `-n <number>` を使用して変更できます (例: 最初の 5 行は `head -n 5 log.txt`)。 - `tail` コマンドは、デフォルトで最後の 10 行を表示し、同じ `-n` オプションをサポートします。 - 重要なことに、`tail -f` (以下) はファイルをリアルタイムで監視し、システムによって書き込まれる新しい行を表示します。これは、ライブ ログを監視するためのシステム管理者のお気に入りのツールです。
インタラクティブなファイル スクロール (less & more)
`head` と `tail` を使用してファイルの先頭と末尾を覗くのは素晴らしいことですが、長い構成ファイルをページごとに参照する必要がある場合はどうすればよいでしょうか? `less` や `more` のようなポケットベルはそのためのものです。 - ページャーはファイルを対話的に読み込み、一度に 1 ページのテキストを表示して、大きなファイルでのシステムの速度低下を防ぎます。 - `less` は最新の選択肢であり、矢印キーを使用して前後にスクロールし、`/` でテキストを検索し、`q` を押して終了することができます。 - `more` は、前方にスクロールするだけの古い、よりシンプルなページャです。
ファイル名内のスペースの処理
ロボットに「寝室を青に塗る」ように指示する場合、ロボットは、「私の寝室」が 1 つの場所なのか、それとも「私の」と「寝室」が 2 つの異なる命令なのかを知る必要があります。 Linux ではコマンドと引数を区切るためにスペースを使用します。したがって、`mkdir my folder` を実行すると、Linux は 2 つの別々のフォルダーを作成したいと考えます。1 つは「my」という名前で、もう 1 つは「folder」という名前です。 - スペースを含む名前が単一の項目であることを Linux に伝えるには、名前を引用符で囲むか (`"my folder"` または `'my folder'`)、バックスラッシュを使用してスペースをエスケープする必要があります (`my\ folder`)。
ファイルの書き込みと上書き
黒板にメッセージを書きたい場合は、まず黒板を完全にきれいに拭き、それから新しい言葉を書きます。 Linux では、`>` (出力リダイレクト) 演算子を使用してファイルにメッセージを書き込みます。 - `echo "message"` コマンドは通常、テキストを画面に出力します。 - `>` シンボルを追加することで、代わりにそのテキストをファイルにリダイレクトします。たとえば、`echo "Hi" > greeting.txt` は `greeting.txt` に「Hi」を書き込みます。ファイルにすでにテキストが含まれている場合、`>` はそれを新しいメッセージで完全に上書きします。
ファイルへの追加
黒板を消去する代わりに、単に下部に新しい行を追加したい場合はどうすればよいでしょうか? Linux では、`>>` (追加リダイレクト) 演算子を使用して、既存のコンテンツには触れずにファイルの末尾にテキストを追加します。 - `>>` 演算子は、新しいテキストをファイルの一番下に追加します。たとえば、`echo "New Line" >> logs.txt` は、すべての古いログを安全に保ちながら、`logs.txt` の末尾に「改行」を追加します。
ファイルのコピーと移動
部屋を整理することを想像してください。文書のコピーを作成して別の引き出しに保管したい場合もあれば、フォルダーを取得して新しい棚にスライドさせたり、ラベルを変更したりしたい場合もあります。 Linux では次のような簡単なコマンドを使用してこれを実行します。 - `cp <source> <destination>` は、新しい場所にファイルの同一の複製を作成します。 - `mv <source> <destination>` は、ファイルを新しいフォルダーに移動するか、同じフォルダー内にファイルを保持する場合はファイルの名前を変更します (例: `mv old.txt new.txt`)。
ワイルドカードと複数ファイルの操作
「log_monday」、「log_tuesday」、「log_wednesday」というラベルの付いたフォルダーのスタックがあり、すべての名前を入力せずに、それらすべてを開いて一度に読み取りたいとします。 Linux では、**ワイルドカード**を検索ショートカットとして使用できます。 - `*` シンボルは、任意の長さの文字に一致します。たとえば、`cat log_*` は、「log_」で始まるすべてのファイルを読み取ります。 - `?` シンボルは、単一文字のプレースホルダーとして機能します。たとえば、`log_?.txt` は `log_1.txt` と一致しますが、`log_12.txt` は無視されます。
ファイルとフォルダーの削除
物理的なデスクを片づけるとき、間違った場合に回収できる古い書類をリサイクル箱に捨てることがあります。 Linux にはセーフティ ネットがありません。ターミナルから何かを削除すると、その内容は永久に失われます。 - `rm` コマンドはファイルを削除します。 - フォルダーには他のファイルを含めることができるため、`rm` はデフォルトではフォルダーを削除しません。 `-r` (再帰) フラグを追加して、Linux にフォルダーを実行し、フォルダー内のすべてのものを削除するように指示する必要があります。 **これが重要な理由**: `downloads` がフォルダーの場合に、`-r` を使用せずに `rm downloads` を実行すると、`rm: cannot remove 'downloads': Is a directory` が得られます。 `-r` フラグは、フォルダーとその中のすべてを再帰的に削除するように Linux に指示します。
Brace Expansion & Safe Directory Removal ({} & rmdir)
Bash **brace expansion** `{}` is a powerful productivity feature that generates arbitrary string combinations before commands run, eliminating repetitive typing: - Comma-separated lists: `mkdir -p app/{src,bin,logs}` expands to `app/src`, `app/bin`, and `app/logs` in a single command. - Numeric or alphabetic ranges: `touch file_{1..3}.txt` expands to `file_1.txt`, `file_2.txt`, and `file_3.txt`. When deleting folders, `rm -r` deletes everything recursively without safety checks. By contrast, `rmdir` provides a strict safety guarantee: it **only removes directories that are completely empty**, preventing accidental loss of files.
Boss Challenge 2: Broken Deployment Cleanup
INCIDENT REPORT: An aborted container update left messy temporary build artifacts in `/home/learner`. The leftover files `temp_install.tmp` and `old_log.txt` are creating conflicts. Furthermore, the verified staging configuration `/home/learner/staging.conf` was never promoted to production. Purge the obsolete temporary files and establish `/home/learner/production.conf` with the configuration from staging. This is a Boss Challenge: evaluate the files, execute the cleanup, and prepare the production configuration.
3. パイプとフィルタリング
パイプとトイレの紹介
ある作業員が製品を包装し、すぐに次の作業員に渡して箱に詰める組立ラインを想像してください。中間の保管場所は必要ありません。 Linux では、**パイプ** (`|`) を使用して、まさにこのようにコマンドを接続します。 - パイプ (`|`) は、1 つのコマンドの出力を次のコマンドの入力に直接ルーティングします。たとえば、`ls | wc -l` はファイルをリストし、そのリストをすぐに `wc -l` (単語数 - 行数) に渡し、一時ファイルを必要とせずにその場でファイルをカウントアップします。 **これが重要な理由**: `-l` を使用せずに `wc` を実行すると、行、ワード、バイト (` 5 10 85` など) という 3 つの別々の数値が出力されます。このため、クリーンな単一の数値カウントを必要とするパイプラインやスクリプトでの使用が困難になります。 `-l` フラグは、出力を行数のみに制限します。
ユニークなものの並べ替えと検索
重複したカードがあちこちに散らばっているデッキのカードを並べ替えることを想像してください。重複を簡単に見つけて削除するには、まず同一のカードをグループ化します。 Linux では、`uniq` コマンドは繰り返し行をフィルターで除外しますが、これには欠点があります。**互いに隣接する重複のみを検出する**ということです。 - 乱雑なリストからすべての重複を削除するには、まず `sort` を使用して行を並べ替えてから、その結果を `uniq` に渡す必要があります。たとえば、`sort raw.txt | uniq` はリストを一度に整理して消去します。
grep
によるフィルタリング システム エラーが発生するたびに、数千ページにわたる膨大なログブックを調べて見つけることを想像してください。これを手動で行うと何時間もかかります。 Linux では、`grep` をデジタル虫眼鏡として使用し、特定の単語やパターンを瞬時に検索します。 - `grep` コマンドは、ファイルまたはパイプされたテキストをフィルター処理し、検索語に一致する行のみを出力します。たとえば、`grep "ERROR" logs.txt` を実行すると、ファイルがスキャンされ、「ERROR」を含む行のみが抽出されます。
Splitting Output with tee
In plumbing, a T-pipe splits a single water stream into two paths. In Linux, the `tee` command does the exact same thing with text streams: it reads standard input and writes it simultaneously to both the screen (stdout) and one or more files. E.g.: `cmd | tee output.log`. Furthermore, `tee` solves a classic Linux permissions pitfall: running `sudo echo "config" > /etc/app.conf` fails because redirection `>` is handled by your unprivileged shell before `sudo` executes. Piping to `sudo tee -a /etc/app.conf` (where `-a` appends) runs `tee` with superuser privileges, safely writing to protected system files.
Comparing Files with diff
In production environments, servers fail when configuration files silently diverge over time—a problem called "configuration drift". The `diff` utility compares two text files line by line and highlights every difference: - Standard format: `diff file1.conf file2.conf` uses `<` to indicate lines from the first file and `>` for lines in the second file. - Unified format: `diff -u file1.conf file2.conf` produces unified diff output (`-` for removed lines, `+` for added lines), which is the standard format used by Git patches and modern pull requests.
Advanced grep Flags (-i, -v, -r, -E)
While basic `grep` searches for exact strings, production log analysis requires powerful matching flags: - `-i`: Case-insensitive search (matches `error`, `Error`, or `ERROR`). - `-v`: Invert match (prints lines that do **not** match the given pattern, perfect for stripping noise). - `-r` (or `-R`): Recursive directory search across all subdirectories and files. - `-E`: Extended regular expressions (supports `|` alternation for multiple patterns, `+`, and parentheses without escape backslashes).
Boss Challenge 3: Security Incident Log Triage
SECURITY ALERT: The server logged dozens of suspicious requests in `/home/learner/access.log`. The SOC team needs a clean, deduplicated list of attacking IP addresses to update the network firewall blocklist. Process the raw web server log to extract all unique IP addresses, sort them, and save the result into `/home/learner/banned_ips.txt`. Analyze the data pipeline and construct a command pipeline to generate the required forensic report.
4. リダイレクトとセキュリティ
ファイル権限の変更
マネージャーのみが小切手に署名でき、従業員はスケジュールを読み取ることができ、訪問者は店舗の看板を見ることしかできないビジネスを運営していることを想像してください。 Linux では、数値のセキュリティ システム (8 進表現と呼ばれます) を使用して、ファイルの読み取り、書き込み、または実行ができるユーザーを制御します。 - `7` = フルアクセス: 読み取り + 書き込み + 実行 (`rwx`) - `6` = アクセスの変更: 読み取り + 書き込み (`rw-`) - `5` = 読み取りおよび実行アクセス: 読み取り + 実行 (`r-x`) - `4` = 読み取り専用アクセス: 読み取り (`r--`) これらの設定を `chmod <octal> <file>` で適用します。たとえば、`chmod 755 script.sh` を使用するとスクリプトを実行できますが、他のスクリプトは読み取りと実行のみが可能です。現在ロックダウンされている `deploy.sh` という名前のスクリプトがあります。実行可能にしてみましょう。
隠しファイルと構成
メインのワークスペースを乱雑にしないように、システム設定を保管する机の下の秘密の引き出しを考えてください。 Linux では、名前をドット (`.`) で始めるだけで隠しファイルが作成されます。 - これらのドットファイル (`.bashrc` や `.config` など) は、ユーザー設定と構成設定をバックグラウンドで保存します。 - 標準の `ls` コマンドでは表示されません。これらの隠しファイルを覗くには、`ls -a` を実行して、`-a` (すべて) フラグを追加する必要があります。 **これが重要な理由**: `-a` を使用せずに `ls` を実行すると、隠しファイル (名前が `.` で始まるファイル) は出力から完全に省略されます。 `.config_names` などの重要なファイルが表示されないため、それらが見つからないと思われる可能性があります。 `-a` フラグは、隠しファイルを含むすべてのファイルをリストするように `ls` に指示します。
ファイル所有権の変更
家を購入し、新しい所有者の名前で権利書を正式に登録する必要があることを想像してください。 Linux では、すべてのファイルとフォルダーに正式な所有者とグループがあります。ファイルの所有権を他の人 (システム管理者など) に渡す必要がある場合は、`chown` (所有者の変更) コマンドを使用します。 - ファイルの所有者の変更は機密性の高いセキュリティ操作であるため、管理者権限でファイルを実行するには、ファイルの先頭に `sudo` を付ける必要があります。たとえば、`sudo chown root reports.csv` はファイルをユーザー「root」に割り当てます。
Linux ファイアウォール (ufw & iptables)
入り口に警備員が立って ID をチェックし、許可されていない訪問者をブロックしている安全なアパートに住んでいることを想像してください。 Linux では、**ファイアウォール** がネットワーク ポートのセキュリティ ガードとして機能します。 - `ufw` (Uncomplicated Firewall) コマンドは、ファイアウォール ルールを管理するための使いやすいインターフェイスです。 `sudo ufw status` を実行すると、ファイアウォールがアクティブかどうか、およびどのポート (SSH の場合はポート 22、Web サーバーの場合はポート 80 など) が開いているかが表示されます。 - `iptables` コマンドは、実際にパケットをブロックまたはリダイレクトする低レベルの従来の Netfilter ツールです。 `sudo iptables -L` を実行すると、アクティブなセキュリティ チェーンとパケット マッチング ルールが一覧表示されます。
Standard Error & /dev/null (2>, 2>&1)
In Linux, every process opens three standard I/O streams: - File descriptor `0`: `stdin` (Standard Input) - File descriptor `1`: `stdout` (Standard Output — where normal output goes) - File descriptor `2`: `stderr` (Standard Error — where error messages go) When you run `cmd > output.txt`, only stdout is saved; error messages still appear on your screen. To redirect errors separately, specify file descriptor 2: `cmd 2> errors.log`. To silence noisy errors completely, redirect them to the Linux null device (black hole): `cmd 2> /dev/null`. To combine both stdout and stderr into one stream or file, use `&> output.log` or `cmd > output.log 2>&1`.
Multi-Line Input with Here-Docs (<<EOF)
In automated scripts and cloud deployment routines (like Dockerfiles or cloud-init), opening an interactive text editor like nano is impossible. Instead, Bash uses **Here-Documents** (`<<EOF`) to inject multi-line blocks of text directly into commands. The syntax `cat <<EOF > config.env` tells the shell to capture all following lines into `config.env` until a line containing only the delimiter word `EOF` is reached.
Default Permissions & Group Ownership (umask & chgrp)
Whenever a program creates a new file or folder, its initial permissions are determined by the **umask** (user file-creation mode mask). The umask acts as a filter that strips away permissions from maximum defaults (`666` for files, `777` for directories): - Standard umask `022` subtracts group/other write permissions, yielding `644` (`rw-r--r--`) for files and `755` (`rwxr-xr-x`) for folders. - Running `umask 027` tightens security by stripping all permissions from "others", yielding `640` and `750`. To change only the group owner of a file without altering its user owner, use `chgrp <group> <file>`.
Special Permissions (SUID, SGID & Sticky Bit)
Standard file permissions (`rwx`) have three special bits that provide advanced access models: - **Sticky Bit (`+t` or octal `1000`)**: Set on shared directories like `/tmp`. Anyone can create files, but users can only delete or rename files they own. Displayed as `t` in `ls -l` (e.g. `drwxrwxrwt`). - **SUID (Set User ID, `u+s` or octal `4000`)**: When set on an executable binary, standard users run the binary with the file owner's privileges (usually root). Displayed as `s` in owner execute position (e.g. `-rwsr-xr-x`). Essential for tools like `/usr/bin/passwd`. - **Security Auditing**: Attackers frequently abuse SUID binaries for privilege escalation. Sysadmins audit systems for SUID binaries using: `find / -perm -4000 2> /dev/null`.
Access Control Lists (getfacl & setfacl)
Standard Linux permissions only support one user owner, one group, and others. When complex enterprise collaboration requires granting distinct rights to multiple users or groups on a single file, **POSIX Access Control Lists (ACLs)** are used: - `getfacl <file>`: Reads and displays the file's extended ACL entries (user, group, mask, other). - `setfacl -m u:<username>:<perms> <file>`: Modifies the ACL to grant specific permissions (`r`, `w`, `x`) to an individual user without changing the file owner. - Notice that when a file has an ACL, `ls -l` displays a `+` symbol at the end of the permission string (e.g., `-rw-rw-r--+`).
Boss Challenge 4: Security Audit & Permissions Lockdown
AUDIT FAILURE: An internal compliance scanner raised a critical security finding: `/etc/vault.conf` containing sensitive credentials was deployed with permissive `777` permissions and is owned by `learner` instead of `root`. Remediate the vulnerability immediately by changing the owner of `/etc/vault.conf` to `root:root` and locking down permissions to strict `600` (read/write for owner only). Inspect the file with `ls -l` before and after running your remediation.
5. スーパーユーザーとパッケージ
スーパーユーザー権限 (sudo)
重要なオペレーティング システム ファイルを誤って削除しないように、標準アカウントを使用してコンピューターで作業していることを想像してください。ソフトウェアをインストールしたり、システム設定を変更したりする必要がある場合、コンピュータは管理者の承認を求めます。 Linux では、管理キー カードとして `sudo` (「superuser do」の略) を使用します。 - `root` ユーザーは、システムを完全に制御できるマスター管理者アカウントです。 - 標準ユーザーは機密ファイル (パスワード データベース `/etc/shadow` など) の読み取りをブロックされます。コマンドの前に `sudo` と入力すると、一時的な管理者権限でコマンドを実行し、これらのブロックを回避できます。
パッケージ管理 (apt)
App Store または Google Play ストアを使用してスマートフォンにアプリをインストールすることを考えてください。安全で、厳選され、自動化されています。 Linux では、パッケージ マネージャーと呼ばれるコマンド ライン アプリ ストアを使用して、ソフトウェアを安全に取得してインストールします。 - Ubuntu/Debian システムでは、標準のパッケージ マネージャーは `apt` (Advanced Packaging Tool) です。 - ソフトウェアをインストールするとシステム全体のフォルダーが変更されるため、常に `sudo` を使用してソフトウェアを認証する必要があります。たとえば、`sudo apt install tree` はディレクトリ ビジュアライザ「ツリー」をダウンロードしてインストールします。
パッケージの検索 (apt search)
Linux にソフトウェアをインストールする前に、リポジトリで利用可能なパッケージをどのように見つけますか? Linux では、`apt search` を使用して、キーワードによってソフトウェア カタログをクエリします。 - `apt search <keyword>` コマンドは、リポジトリの説明をスキャンし、一致するソフトウェア パッケージをそのバージョンとともにリストします。 - `apt install` とは異なり、パッケージ リポジトリの検索はローカル カタログ インデックス ファイルを読み取るだけであり、スーパーユーザー (`sudo`) 権限は**必要ありません**。
パッケージのパージ (apt purge)
Linux でソフトウェアをアンインストールする場合、標準の `apt remove` はアプリケーション バイナリをアンインストールしますが、後で再インストールする場合に備えてシステム構成ファイルを残します。ソフトウェア パッケージを完全に削除し、関連するすべての構成ファイルを消去するには、`apt purge` (または `apt remove --purge`) を使用します。 - `sudo apt purge <package>` コマンドはアプリケーションを削除し、残っているすべての構成ファイルを消去します。 - パージではシステム全体のフォルダーと構成ファイルが変更されるため、スーパーユーザー (`sudo`) 権限が必要です。
Debian パッケージ管理 (dpkg)
`apt` は、リポジトリからのパッケージの依存関係のダウンロードと解決を自動化しますが、`.deb` パッケージ ファイルをすでに手動でダウンロードしており、それを検査またはインストールしたい場合はどうすればよいでしょうか。 Linux では、`dpkg` (Debian パッケージ) を使用してパッケージと直接対話します。 - `dpkg -l` コマンドは、Debian/Ubuntu システムに現在インストールされているすべてのパッケージを一覧表示します。 - `dpkg -s <package>` コマンドは、特定のパッケージのステータス、バージョン、およびアーキテクチャ情報を表示します。
RedHat パッケージ マネージャー (yum & dnf)
すべての Linux 環境が Debian/Ubuntu に基づいているわけではありません。 RedHat、Fedora、または CentOS システムで作業している場合、`apt` や `dpkg` は見つかりません。代わりに、古い `yum` または最新の `dnf` (Dandified YUM) パッケージ マネージャーを使用してパッケージを管理します。 - `dnf check-update` (または `yum check-update`) コマンドは、RedHat リポジトリに接続して、利用可能なパッケージ更新をスキャンします。 - `dnf install <package>` コマンドは、`apt install` と同様のプログラムを取得してインストールします。
Updating vs. Upgrading (apt update & apt upgrade)
New system administrators often confuse updating and upgrading. In Debian and Ubuntu environments: - `sudo apt update`: Refreshes your local cache of package lists from upstream repository servers (`/etc/apt/sources.list`). It discovers which newer package versions exist, but **does not modify or upgrade any software** on disk. - `sudo apt upgrade`: Compares your currently installed software against the refreshed list and downloads/installs the newer package versions. Running `apt upgrade` without running `apt update` first will either install outdated versions or fail completely because your system does not know newer releases exist!
Universal & RPM Packages (rpm & snap)
In cross-distribution Linux environments, you will frequently encounter formats beyond Debian `.deb` packages: - **RPM (`rpm`)**: The native package format for RedHat, CentOS, and Fedora. Use `rpm -qa` to list every installed RPM package, and `rpm -qi <package>` to query deep metadata (version, build architecture, signature, description). - **Snap (`snap`)**: Canonical's universal containerized package system. Snaps bundle all dependencies in an isolated sandbox across any Linux distro. Inspect installed snaps with `snap list` and install new tools with `sudo snap install <package>`.
Boss Challenge 5: Package Hygiene & Malware Purge
INCIDENT RESPONSE: An unauthorized script dropped a suspicious unsigned package archive `/tmp/corrupt_pkg.deb` into temporary storage. Furthermore, the standard network diagnostic utility `curl` is missing or unverified in the system catalog. Cleanse the temporary directory by purging `/tmp/corrupt_pkg.deb` and ensure the package manager has `curl` installed and ready for service.
6. ディスクとシステムリソース
ディスク容量の確認 (df)
巨大なビデオ ゲームをダウンロードしようとすると「ストレージがいっぱいです」エラーが発生することを想像してください。しかし、どのディスク ドライブがボトルネックになっているのかわかりません。 Linux では、`df` (ディスク空き) コマンドを使用してシステムのストレージ容量を確認します。 - `df` コマンドは、接続されているすべてのドライブの合計容量、使用済み容量、および利用可能な容量を表示します。 - `df -h` を実行する (「人間が判読できる」ように `-h` フラグを追加する) と、紛らわしいブロック数ではなく、分かりやすいギガバイト (G) とメガバイト (M) 単位でストレージが表示されるため、どのドライブ (`/` や `/home` など) がいっぱいになっているかを簡単に特定できます。 **これが重要な理由**: `-h` を使用せずに `df` を実行すると、サイズは生の 1K ブロック数値 (たとえば、`47G` の代わりに `49258284`) で表示されます。これは、人間にとって読み取って計算するのが非常に困難です。 `-h` フラグは、これらのサイズを人間がわかりやすいギガバイト (G) とメガバイト (M) にフォーマットします。
ディレクトリ サイズの確認 (du)
*どの*ドライブがいっぱいになっているかがわかったら、すべてのスペースを蓄えている特定のフォルダーをどのように見つけますか?それはダウンロード フォルダーですか、それとも隠しキャッシュですか? `du` (ディスク使用量) コマンドを使用して、この謎を解決します。 - `du <directory>` は、フォルダーとその中のすべてのサブフォルダーのサイズをリストします。 - `du -sh <directory>` (`-s` は「要約」を意味し、`-h` は「人間が判読できる」を意味します) は、その特定のフォルダーの単一のクリーンな合計サイズを計算して出力します。 **これが重要な理由**: `-s` を使用せずに `du` を実行すると、単一の概要を提供するのではなく、個々のサブディレクトリとファイルを再帰的にリストする膨大なテキストの壁がダンプされます。 `-s` フラグはフォルダーの合計サイズを要約し、`-h` は人間が判読できるようにします。
メモリ使用量の確認 (free)
ラップトップの動作が遅くなり、Web ページがフリーズし、アプリの切り替えがひどく遅く感じられると想像してみてください。これは通常、コンピュータのアクティブ メモリ (RAM) が不足していることを意味します。 Linux では、`free` コマンドを使用して、システムにどれだけの呼吸スペースがあるかを確認できます。 - `free` コマンドは、合計、使用済み、および利用可能な物理メモリ (RAM) とスワップ領域を表示します。 - `-h` フラグを追加すると (`free -h` を実行)、メモリ サイズが読みやすいギガバイト (GB) とメガバイト (MB) にフォーマットされるため、プログラムがすべてのリソースを使い果たしているかどうかがわかります。 **これが重要な理由**: `-h` を使用せずに `free` を実行すると、メモリ使用量が未加工のキロバイト単位で出力されます (例: `16G` ではなく `16323456`)。これを迅速に解釈するのは困難です。 `-h` フラグは、読みやすいように数値をギガバイト (G) またはメガバイト (M) に自動的にスケールします。
システム稼働時間とカーネルの詳細
サーバーが誤動作し始め、最近再起動したかどうかを確認する必要があるサーバーのトラブルシューティング、または内部で実行されているオペレーティング システムのバージョンを正確に確認することを想像してください。これらのシステムの詳細を数秒でクエリできます。 - `uptime` コマンドは、マシンが前回起動してからどのくらいの時間稼働しているのか、またどのくらいビジー状態 (システム負荷) であるかを正確に示します。 - `uname -a` (unix 名) コマンドは、システムのカーネル、プラットフォーム名、およびマシン アーキテクチャの完全なレポートを出力します。 **これが重要な理由**: `-a` を使用せずに `uname` を実行すると、基本的なオペレーティング システム名 (`Linux` など) のみが出力されます。カーネルのバージョン、プラットフォーム名、プロセッサ アーキテクチャなどの重要な詳細は省略されています。 `-a` フラグは、利用可能なシステムの詳細をすべて 1 つのレポートに出力します。
CPU 詳細の表示 (lscpu)
システム パフォーマンスのトラブルシューティングを行う場合、または需要の高いアプリケーションを展開する場合は、システムの CPU の機能を把握する必要があります。 Linux では、`lscpu` コマンドを使用して詳細な CPU アーキテクチャ情報を読み取ります。 - `lscpu` コマンドは、CPU モデル、ベンダー、クロック速度、コア数、ハイパースレッディングの詳細、キャッシュ サイズなどのプロセッサの詳細をカーネル ファイル システムから直接表示します。
I/O と CPU の統計 (iostat)
データベースまたは Web アプリケーションの実行が遅いとき、問題が CPU のボトルネックであるのか、それともハード ドライブの速度が遅いのかをどのように判断しますか? Linux では、`iostat` を使用してシステムの出力/入力パフォーマンス メトリックを監視します。 - `iostat` コマンドは、CPU 使用率とアクティブ デバイスの読み取り/書き込みスループットに関するレポート統計を表示し、ディスクの混雑を特定するのに役立ちます。
Block Devices & Partitions (lsblk & blkid)
Before a disk can store files, it is divided into storage blocks and partitions formatted with filesystems. In Linux: - `lsblk`: Lists block storage devices (hard drives, NVMe SSDs, flash drives) in an intuitive tree showing parent drives (like `sda`, `sdb`), child partitions (like `sda1`, `sdb1`), sizes, and active mountpoints. Adding `-f` shows filesystem types and UUIDs. - `sudo blkid`: Queries disk headers directly to print device Universally Unique Identifiers (UUIDs), filesystem formats (such as `ext4`, `xfs`, `vfat`), and partition labels used in boot and mount configurations.
Mounting Filesystems (mount, umount & /etc/fstab)
In Unix systems, disk drives do not have isolated drive letters like `C:\` or `D:\`. Instead, all filesystems attach into a unified directory tree: - `sudo mount <device> <directory>`: Attaches a formatted block partition (e.g. `/dev/sdb1`) into an existing directory folder (the "mountpoint", e.g. `/mnt/data`). - `sudo umount <directory>`: Safely detaches the filesystem, committing unwritten buffers to disk before unplugging or reformatting. - `/etc/fstab`: The static filesystem table file describing which partitions automatically mount at boot time, their mount options, and dump/fsck pass priorities.
Kernel Ring Buffer & Hardware Logs (dmesg)
When hardware devices attach, drives fail, or the Linux kernel encounters system memory exhaustion, kernel messages are written to a special memory area called the **Kernel Ring Buffer**. - `dmesg`: Dumps raw kernel boot and runtime log messages. - `dmesg -T`: Converts raw timestamps into readable date and time strings. - Pipelining `dmesg | grep -i error` or filtering for "Out of memory" reveals low-level driver failures and Out-Of-Memory (OOM) killer terminations.
Boss Challenge 6: Disk Space Outage Emergency
CRITICAL ALERT: Root filesystem capacity has hit 99%! Production monitoring reports that an unhandled core dump `/var/log/huge_core_dump.log` is suffocating system storage. Locate the runaway file, delete `/var/log/huge_core_dump.log` to reclaim space, and create a status confirmation log `/home/learner/disk_recovery.txt` containing a summary of recovered capacity.
7. プロセス管理
実行中のプロセスの一覧表示 (ps)
オペレーティング システムを、すべての従業員 (または実行中のプログラム) にプロセス ID (PID) と呼ばれる固有のネーム タグが割り当てられている多忙なオフィスと考えてください。 Linux では、これらのアクティブなプログラムを **プロセス** と呼び、`ps` コマンドを使用してリストします。 - `ps` を単独で実行すると、現在のターミナル ウィンドウ内で実行されているプログラムのみが表示されます。 - `ps aux` を実行すると、マスター オフィス レジストリのように機能し、システム全体で実行されているすべてのアクティブなプログラム、誰が起動したか、および使用している CPU とメモリの量をリストします。 **これが重要な理由**: `aux` を使用せずに `ps` を実行すると、現在のターミナル ウィンドウで実行中のプロセスのみが表示されます (通常は `bash` と `ps` 自体のみ)。バックグラウンド サービス、システム プロセス、または他のユーザーが実行するプログラムは表示されません。 `aux` オプションは、システム全体で実行中のすべてのプロセスを明らかにします。
インタラクティブ プロセス モニター (top)
高速道路の静止写真を見るのと、交通カメラのライブ フィードを見ることを想像してみてください。 `ps` では現在実行中のものの簡単なスナップショットが得られますが、`top` ではシステムのパフォーマンスをライブで監視できます。 - `top` コマンドは、数秒ごとに更新される対話型のリアルタイム ダッシュボードを起動します。 CPU 使用率、負荷平均を表示し、現時点で実行されている最もリソースを大量に使用するプロセスを動的にランク付けします。
開いているファイルのリスト (lsof)
Unix 系システムでは、「すべてがファイル」です。これは、テキスト ファイルやフォルダーだけでなく、ネットワーク ソケット、システム ハードウェア、プロセスもファイルとして扱われることを意味します。どの実行中のプログラムがどのファイルにアクセスしているかを調べるには、`lsof` (開いているファイルのリスト) を使用します。 - `lsof` を実行すると、開いているすべてのファイルの包括的なリストが、それらを開いたプロセス ID (PID) およびコマンドとともに表示されます。 - たとえば、`lsof -i` を実行すると、すべてのネットワーク ファイル/ソケットがリストされます。これは、どのプロセスが特定のネットワーク ポート (ポート 80 など) でリッスンしているかを検出するのに非常に役立ちます。
不正なプロセスの停止 (kill)
携帯電話上のアプリがフリーズして画面が完全にロックされ、再びスムーズに動作させるにはアプリを強制的に閉じる必要があると想像してください。 Linux では、プログラムのプロセス ID (PID) を続けて `kill` コマンドを使用して、不正な動作やフリーズしたプログラムを停止します。 - `kill 1234` を実行すると、プログラムに作業内容を保存して終了するよう求める丁寧なリクエストが送信されます。 - フリーズし、丁寧な要求を無視した場合、`kill -9 1234` はオペレーティング システムを即座に強制的にシャットダウンします。現在、PID `9999` の暴走プロセスがすべての CPU を占有しています。シャットダウンしましょう。
バックグラウンドでのジョブの実行
巨大なフォルダーを USB ドライブにコピーしようとしているところを想像してください。コピー中も同じウィンドウで作業を続け、他のコマンドを入力したいとします。 Linux では、時間のかかるタスクを「バックグラウンド」で実行できるため、コマンド ラインがロックされることはありません。 - コマンドの末尾にアンパサンド `&` を追加すると (`sleep 100 &` など)、バックグラウンドでコマンドを実行し、すぐにプロンプトを返すように端末に指示します。 - `jobs` コマンドは、現在バックグラウンドで実行されている内容を表示します。 - `fg` (フォアグラウンド) コマンドは、バックグラウンド タスクを中央ステージに戻します。
Process Niceness (nice & renice)
忙しいオフィスでは、優先度の低いタスク (領収書の提出など) は待つことができますが、優先度の高い要求はすぐに処理する必要があります。 Linux は、-20 (最高の優先順位) から 19 (最低の優先順位) の範囲の **niceness** 値を使用してプロセスの優先順位を管理します。 - `nice` コマンドは、カスタマイズされた優先順位でプロセスを起動します。例えば。 `nice -n 10 sleep 5` は、ポライト優先度 10 でスリープ コマンドを開始します。 - `renice` コマンドは、すでに実行中のプロセスのスケジュール優先度を変更します。例: `sudo renice +5 9999` はプロセス 9999 の優先度を下げます。
バックグラウンド ジョブの再開 (bg)
`&` を使用してバックグラウンドでタスクを開始し、`fg` を使用してタスクを戻す方法はすでに説明しました。しかし、`&` を使用せずにコマンドを開始した場合、または `Ctrl+Z` を使用してコマンドを一時停止した場合はどうなるでしょうか? `bg` を使用してバックグラウンドで再開できます。 - `bg` コマンドは、一時停止されたジョブを再開し、端末プロンプトをブロックすることなくバックグラウンドでジョブを実行できるようにします。
Finding & Killing Processes by Name (pgrep, pkill, killall)
In fast-paced system operations, looking up process IDs with `ps aux | grep name` just to pass a numerical PID into `kill` is slow and error-prone. Linux provides process lookup and signal tools that operate directly by process name: - `pgrep <pattern>`: Scans active processes and returns matching PIDs. Adding `-a` outputs the full command line alongside the PID. - `pkill <pattern>`: Sends termination signals directly to all processes matching the pattern (e.g. `pkill -9 miner`). - `killall <name>`: Kills processes matching the exact binary executable name.
Persistent Processes & Live Monitoring (nohup & watch)
Long-running tasks need two critical abilities: surviving unexpected network disconnects, and real-time execution monitoring without manual re-typing: - `nohup <command> &`: Runs a command immune to SIGHUP (hangup signals). If your SSH session drops or terminal closes, the program continues executing in the background, redirecting stdout/stderr into `nohup.out`. - `watch -n <seconds> <command>`: Repeatedly executes a command at a set interval (default 2s), clearing the screen to display a live updating dashboard of system state.
Boss Challenge 7: Rogue Cryptominer Neutralization
SERVER THROTTLED: CPU load average has spiked above 25.0. An unauthenticated background script (PID 9999 running `rogue_process.sh`) is monopolizing 99.1% of processor cycles and starving application threads. Inspect the active process table to discover the rogue PID, determine its signal tolerance, and kill the process immediately so it ceases execution.
8. ネットワークのトラブルシューティング
接続性のテスト (ping)
Web ページをロードしようとすると、ブラウザが際限なく回転し、家の Wi-Fi が切断されているのではないか、Web サイト自体がクラッシュしたのではないかと疑問に思うことを想像してください。 Linux では、`ping` コマンドを使用して基本的なネットワーク接続をテストします。 - `ping` コマンドは、小さなデータ パケットをサーバー (`google.com` など) に送信し、応答を受信するまでにかかる時間をミリ秒単位で測定します。 - Linux では、`ping` はデフォルトで永久に実行され続けます。数回試行した後に停止するには、`-c` (カウント) フラグを使用して `ping -c 3 google.com` を実行します。 **これが重要な理由**: `-c` を使用せずに `ping google.com` を実行すると、無限にパケットの送信と出力の出力が継続されます。他のコマンドを実行するには、`Ctrl+C` を使用して手動で中断する必要があります。 `-c 3` フラグは、ちょうど 3 つのパケットを送信した後にコマンドを自動的に停止します。
ネットワーク インターフェイスとローカル IP
ネットワーク プリンターをセットアップしたり、同じ Wi-Fi 上の友人のコンピューターとファイルを共有したりするときに、自分のマシンのローカル IP アドレスを知る必要があることを想像してください。 Linux では、`ip` コマンドを使用してネットワーク ハードウェアと IP を検査します。 - `ip addr` (または単に `ip a`) を実行すると、すべてのネットワーク インターフェイス デバイス (有線イーサネットの場合は `eth0`、ワイヤレスの場合は `wlan0` など) のリストが、割り当てられたローカル IP アドレスとともに出力されます。
インターフェイスの確認 (ifconfig)
最新の `ip` コマンド スイートが標準になる前は、Linux システム管理者は `ifconfig` (インターフェイス コンフィギュレーター) を利用してネットワーク インターフェイスを表示および管理していました。 - `ifconfig` コマンドは、アクティブなネットワーク インターフェイス、ローカル IP 構成、ネットマスクの詳細、および MAC ハードウェア アドレスを表示します。一部の新しいディストリビューションでは非推奨になっていますが、レガシー サーバーでは依然として広く使用されています。
ネットワーク接続 (nmcli)
最新の Linux ワークステーションおよびサーバーでは、ネットワーク インターフェイスは NetworkManager と呼ばれるシステム デーモンによって管理されます。構成ファイルを手動で編集するのではなく、`nmcli` を使用してネットワークの詳細を構成します。 - `nmcli` (NetworkManager CLI) コマンドを使用すると、ハードウェア接続、デバイスの状態、アクティブな Wi-Fi ネットワークを検査できます。
ソケットと接続の統計 (netstat & ss)
データベースまたは Web サーバーをセットアップするときは、サービスが正しいポートで実行およびリッスンしていることを確認し、不正な接続が確立されていないかどうかを確認する必要があります。これは、`netstat` または `ss` を使用して行います。 - `netstat` (ネットワーク統計) コマンドは、TCP 接続とリスニング ポートを表示するための古典的なツールです。例えば。 `netstat -tuln` は、TCP/UDP リスニング ポートをリストします。 - `ss` (ソケット統計) コマンドは、カーネル名前空間から直接ソケット接続の詳細を表示する `netstat` に代わる最新の高速なコマンドです。
パケット ルートのトレース (traceroute)
Web ページの読み込みに失敗した場合、問題がホーム ルーター、インターネット サービス プロバイダー (ISP)、または宛先サーバーにあるのかどうかをどのように特定しますか? Linux では、`traceroute` を使用してパケットをトレースします。 - `traceroute` コマンドは、パケットがリモート サーバーに向かう途中で通過するすべてのルーター ゲートウェイ (ホップ) と、各ホップの応答遅延を一覧表示します。
Web ファイルのダウンロード (curl)
ブラウザを開いて「ダウンロード」ボタンをクリックせずに、Web サーバーから直接ファイルをダウンロードしたり、セットアップ スクリプトのコードを取得したりしたいと想像してみてください。 Linux では、`curl` (「クライアント URL」の略) を使用して Web データを取得します。 - `curl <url>` を実行すると、ページのコンテンツがダウンロードされ、画面に直接印刷されます。 - ダウンロードしたコンテンツを表示するのではなくファイルとして保存するには、`>` リダイレクトまたは `-o` 出力フラグと組み合わせます。
DNS Resolution & Lookups (dig, nslookup & host)
When your machine translates a human-readable domain name like `example.com` into an IP address like `93.184.216.34`, it queries DNS nameservers configured in `/etc/resolv.conf`. - `/etc/resolv.conf`: Contains your system's primary and fallback DNS nameservers. - `dig <domain>`: The de-facto standard administrator tool for testing DNS queries, returning response headers, query latency, and record TTLs. Adding `+short` prints only the final IP answer. - `nslookup <domain>` and `host <domain>`: Lightweight queries for checking A/AAAA and MX mail exchange records.
Routing Tables & Gateways (ip route)
When your server sends a packet to an IP address outside its local subnet, how does the kernel know which router or network card interface to send it through? It consults the **Kernel IP Routing Table**. - `ip route` (or `ip r` / `ip ro`): Displays active routing table entries. - The line starting with `default via <IP> dev <interface>` defines your **Default Gateway** (your router), which handles all internet traffic not addressed to a local subnet.
Port Testing & File Downloads (nc & wget)
Two everyday network maintenance tasks are testing whether remote ports are open and downloading files without browsers: - `nc` (Netcat): Often called the "Swiss Army Knife" of TCP/IP. Running `nc -zv <host> <port>` scans a target port without sending application data (`-z` for zero-I/O port scanning, `-v` for verbose output), instantly confirming if a firewall or service is responding. - `wget`: The robust non-interactive network downloader. Running `wget -O <output-file> <url>` downloads files reliably, resuming broken connections.
Managing System Hostnames (hostname & hostnamectl)
Every computer on a network possesses a hostname that identifies it to other machines and shell prompts (e.g., `learner@bashquest:~$`). In modern systemd environments: - `hostname`: Displays the current simple system hostname. - `hostnamectl`: Displays complete system identification metadata, including operating system release, kernel build version, hardware chassis, and virtualization hypervisor. - `sudo hostnamectl set-hostname <name>`: Persistently updates the hostname across reboots by modifying `/etc/hostname` and updating the systemd hostnamed daemon.
Boss Challenge 8: DNS Poisoning Remediation
SECURITY COMPROMISE: An attacker injected a DNS poisoning entry `0.0.0.0 evil-tracker.local` directly into `/etc/hosts`, corrupting internal hostname resolution. Remediate the threat: edit or clean `/etc/hosts` to remove all references to `evil-tracker.local`, and record `evil-tracker.local` in `/etc/blocked_hosts.conf` so the domain is permanently logged for network blacklisting.
9. ファイル検索とコマンド探索
名前によるファイルの検索 (find)
重要なテキスト ファイルをユーザー フォルダーのどこかに置き忘れて、ネストされた多数のディレクトリを 1 つずつ検索しなければならないことを想像してください。 Linux では、超高速のシステム全体の検索エンジンとして `find` ユーティリティを使用することで、手動による検索をバイパスします。 - `find` コマンドは、名前、サイズ、タイプ、または日付に基づいてディレクトリ ツリーを検索します。 - 構文は `find <where> -name "<pattern>"` です。たとえば、`find . -name "*.txt"` は、現在のディレクトリとすべてのサブフォルダーで `.txt` で終わるファイルを検索します。 **これが重要な理由**: `-name` を使用せずに `find . "*.log"` を実行すると、エラー `find: paths must precede expression: '*.log'` が発生します。 `-name` フラグは、後続のパターンをファイル名と照合する必要があることを指定するために必要です。
コマンド履歴の確認
10 分前に長く複雑なネットワーク診断コマンドを入力し、再度実行する必要があるが、正確なオプションや構文を思い出せないと想像してください。頭を悩ませたり、何度も入力したりする代わりに、Linux がそれを記憶してくれます。 - `history` コマンドは、最近実行したすべてのコマンドの番号付きリストを表示します。 - 感嘆符の後にリスト番号を入力すると、項目をすばやく再実行できます (コマンド #42 を再実行する `!42` など)。
マニュアル ページを参照する
新しいコマンドを使用しようとしているが、そのコマンドがどのようなフラグをサポートしているか、またはその入力をどのようにフォーマットする必要があるかがわかりません。オンラインで検索する代わりに、Linux には公式の包括的なユーザー マニュアルが端末に直接組み込まれています。 - `man` (手動) コマンドの後に任意のユーティリティ名 (`man ls` など) を指定すると、詳細なリファレンス ガイドが開きます。 - ガイド内で、矢印キーでスクロールし、「/」で検索し、`q` を押してマニュアルを閉じ、プロンプトに戻ります。
Advanced find by Size, Time & Exec (-size, -mtime, -exec)
Beyond basic filename queries, `find` is a powerhouse filter engine for automated system cleanup and log rotation: - `-size +50M`: Filters for files strictly larger than 50 Megabytes (`+` for greater than, `-` for less than). - `-mtime -7`: Filters for files modified within the last 7 days. - `-exec <cmd> {} +`: Passes all matched files directly into a command in batches, replacing `{}` with matched file paths. Combining these allows single-line system maintenance, such as finding and purging runaway logs: `find /var/log -size +50M -exec rm {} +`.
Indexed Search & Command Introspection (locate, whereis, type)
When `find` is too slow because it scans the live disk tree, and you need to inspect command binaries vs shell builtins: - `sudo updatedb`: Crawls the entire filesystem and builds a high-speed precomputed search index database (`mlocate.db`). - `locate <name>`: Instantly searches the indexed database in milliseconds instead of seconds. - `whereis <cmd>`: Locates binary executables, source files, and man pages in standard system paths. - `type <name>`: Identifies whether a command is a shell builtin (e.g. `cd`, `umask`), an alias (e.g. `ll`), or an external binary disk file (e.g. `/bin/ls`).
Searching Manual Page Descriptions (apropos & whatis)
When you know what task you want to achieve, but don't remember the exact Linux command name, or when you need a quick one-line summary of what an unfamiliar command does: - `apropos <keyword>`: Searches through the short one-line description summaries of **all manual pages** on the system, returning any command related to that concept (e.g. `apropos partition`, `apropos process`). - `whatis <cmd>`: Displays the exact single-line summary from section 1 or 8 of that specific tool's manual page (e.g. `whatis ls`, `whatis grep`).
Boss Challenge 9: Lost Disaster Recovery Archive
DISASTER RECOVERY: Before an unexpected reboot, a database administrator saved an encrypted backup archive named `db_backup_secure.tar.gz`, but failed to document its path. It is lost somewhere on the filesystem. Locate the misplaced archive file anywhere across the system hierarchy, and restore it to its designated safe haven: copy it to `/home/learner/backups/db_backup_secure.tar.gz`.
10. サービスとSystemd
サービスの制御 (systemctl)
コンピューター上で Web サイトをホストしているときに、バックグラウンド Web サーバー プログラムが実行されていないため、訪問者に「サイトにアクセスできません」というエラーが表示されることを想像してください。 Linux では、自動的に起動してバックグラウンドで実行されるバックグラウンド プロセス (データベース、ファイアウォール、Web サーバーなど) は **サービス** と呼ばれ、`systemctl` を使用して管理されます。 - `systemctl status <service>` コマンドは、サービスがアクティブであるか停止しているかを確認します。 - サービスの開始または停止はすべてのユーザーとシステムのセキュリティに影響するため、`sudo systemctl start <service>` や `sudo systemctl stop <service>` などのコマンドを実行するには `sudo` を使用する必要があります。
システム ログ (journalctl)
`systemctl` を使用してバックグラウンド サービスを開始および停止できるようになりましたが、バックグラウンド サービスが失敗した場合に、どのようにトラブルシューティングを行うでしょうか? `journalctl` ユーティリティを使用すると、systemd によって管理されるサービスによって生成されたシステム ログを検査できます。 - デフォルトでは、`journalctl` はすべてのシステム ログを表示します。これは大規模になる可能性があるため、集中力を維持するためにフィルタリングします。 - `-u <service>` オプションはログをフィルタリングして、特定のサービス (`journalctl -u apache2` など) からのメッセージのみを表示します。 - `-n <number>` オプションは、最新のエントリのみを表示します (たとえば、最後の 5 つのログの `journalctl -n 5`)。 - `-f` (フォロー) フラグは、ログが書き込まれるときにリアルタイムでログを表示します。
Enabling Services at Boot (systemctl enable & disable)
Starting a service with `systemctl start` only launches it for the current session. If the server reboots, the service will stay offline unless you configure it to start automatically on system initialization. - To start a service at boot, run `sudo systemctl enable <service>`. - To verify whether a service is scheduled to launch at boot, run `systemctl is-enabled <service>`. - When creating or editing systemd unit files, always notify systemd to reload its configuration cache with `sudo systemctl daemon-reload`. - To disable a service from starting at boot, run `sudo systemctl disable <service>`.
System Clock, Timezones & Power (timedatectl & shutdown)
Accurate system time is critical for log auditing, authentication protocols (Kerberos, TLS certificates), and scheduled database backups. - The `timedatectl` utility queries and changes the system clock and its timezone. - View the current time settings, RTC, and active timezone with `timedatectl status` (or simply `timedatectl`). - Set the system timezone using superuser rights: `sudo timedatectl set-timezone UTC`. - When shutting down or restarting production servers, use the `shutdown` command with safety delays and broadcast notices: `sudo shutdown -r now` (reboots immediately) or `sudo shutdown -c` (cancels scheduled shutdowns).
Boss Challenge 10: Production Web Service Recovery
OUTAGE REPORT: The primary HTTP frontend service `apache2.service` crashed and is currently in an `inactive (dead)` state. Client web requests are timing out. Inspect the service status with your service management tools, discover the problem, and use `systemctl` with superuser privileges to restart or start `apache2` so it returns to `active (running)`.
11. ターミナルでのテキスト編集
構成ファイルの編集 (nano)
グラフィカル デスクトップやカーソルがなく、構成ファイル内の行をすばやく修正する必要があるリモート クラウド サーバーに SSH 接続することを想像してください。これらのシナリオでは、`nano` などのターミナル テキスト エディターを使用する必要があります。 - `nano <filename>` を実行すると、シンプルで軽量のテキスト エディタがシェル ウィンドウ内に直接ロードされます。 - ショートカットは常に画面の下部に表示されます。変更を書き出す (保存する) には `Ctrl+O` を押し、エディターを終了するには `Ctrl+X` を押します。
Vim Basics: Modes, Saving & Exiting (vim)
Vim is one of the most powerful and ubiquitous terminal text editors in Linux. Unlike traditional graphical editors, Vim is **modal**: - **Normal Mode**: The default mode used for navigation, deleting, and issuing commands. - **Insert Mode**: The mode used for typing text. Press `i` from Normal Mode to start typing. - **Return to Normal Mode**: Press `Esc` at any time to leave Insert Mode. - **Command-Line Mode**: From Normal Mode, press `:` to type commands at the bottom prompt: - `:w` writes (saves) the file. - `:q` quits the editor. - `:wq` (or `:x`) saves and exits in one step. - `:q!` quits immediately, discarding all unsaved changes.
Vim Navigation, Deleting & Searching (dd, yy, p, /)
Once you master Normal mode commands, Vim allows lightning-fast text manipulation without touching a mouse: - `dd`: Delete (cut) the entire current line into the yank buffer. - `yy`: Yank (copy) the current line. - `p`: Paste the yank buffer on the line below the cursor. - `/pattern`: Search forward through the file for text matching `pattern`. - `:%s/old/new/g`: Global search and replace throughout the entire file without manual edits.
Boss Challenge 11: Corrupted Server Configuration
CONFIGURATION CORRUPTION: A late-night config commit broke `/home/learner/server.conf`. The file contains invalid directives: `host=0.0.0.0.0` (malformed IP) and `port=99999` (outside the 1-65535 port range). Open `/home/learner/server.conf` with your text editor (nano, vim, or shell tools) and correct the file so that `host=127.0.0.1`, `port=80`, and `max_connections=500` are set.
12. シェルスクリプトと自動化
初めての Bash スクリプトの作成
毎朝実行しなければならない 20 個のタスクのリストがあると想像してください。手動で入力するのは面倒で、タイプミスの余地が残ります。 Linux では、コマンドをシェル スクリプトと呼ばれるファイルにまとめて、すべてを一度に実行できるようにします。 - すべてのスクリプトは最初の行の「shebang」(`#!/bin/bash`) で始まり、ファイルの実行にどのシェル インタプリタを使用するかをシステムに指示します。 - スクリプトを保存した後、`chmod 755 script.sh` を介して実行権限を付与し、`./script.sh` を使用して実行することで実行可能になります。
変数と引数 ($1)
Web サイト用にパーソナライズされたウェルカム メッセージを作成することを想像してください。顧客名ごとに個別のスクリプトを作成する必要はありません。代わりに、実行時に名前を入力として受け取るスクリプトを 1 つ作成します。 - bash スクリプトでは、`$1`、`$2` などの変数に、コマンド ラインで渡す「引数」または入力が保持されます。 - たとえば、`./greet.sh Alice` を実行すると、スクリプト内の `$1` にテキスト「Alice」が自動的に含まれることになります。同様に、`$#` はユーザーが提供した入力の数を追跡します。
条件付きロジック (if/else)
CSV レポートを処理するスクリプトを構築するところを想像してください。ただし、レポート ファイルが実際にディスク上に存在しない場合、スクリプトはクラッシュします。エラーを防ぐために、`if/else` 条件付きロジックを使用して決定を行うスクリプトを作成します。 - 括弧 `if [ -f "$1" ]; then ... fi` を使用して条件を確認します。 - `-f` フラグはパスがファイルを指しているかどうかをチェックし、`-d` フラグはそれがディレクトリであるかどうかをチェックします。スクリプトは、条件が true と評価されるか false と評価されるかに応じてアクションを分岐します。
ループによる自動化
100 個のログ ファイルが含まれるフォルダーがあり、すべてのログ ファイルのバックアップ コピーを作成する必要があると想像してください。個別にコピーするのは大変です。 Linux では、`for` ループを使用して、項目のリスト全体にわたって同じアクションを自動的に繰り返します。 - `for` ループ (`for file in *.txt; do ... done` と同様) は、パターンに一致するすべての項目を反復し、それらを一瞬のうちに次々に処理します。
再利用可能なロジック (bash functions)
スクリプト内のアクションを自動化するループと条件を記述しました。しかし、スクリプトが大きくなるにつれて、同じロジックを何度もコピー&ペーストすると保守が困難になります。 bash では、コマンドを再利用可能な関数にグループ化できます。 - 関数を定義するには、名前の後に括弧と中括弧を続けて関数を宣言します: `log_msg() { echo "msg"; }`。 - 関数は、関数本体内のローカル位置パラメーター `$1`、`$2` などを使用してアクセスされるシェル スクリプトと同じように引数を受け取ることができます。 - 関数を呼び出すには、他のコマンドと同様にその名前を使用するだけです: `log_msg "Backup started"`。
タスクのスケジュール設定 (crontab)
堅牢なシェル スクリプトを作成したので、バックアップ ヘルパーを実行するためだけに真夜中にログインする必要はありません。 Linux は、特定の時間にコマンドまたはスクリプトを自動的に実行する `cron` サービスを提供します。 - cron サービスは、`crontab` というスケジュール テーブルをチェックします。 - 各 cron スケジュールには、時間を表す 5 つのフィールドがあります: `minute hour day-of-month month day-of-week` の後にコマンドが続きます。 - たとえば、`30 2 * * * /path/to/script.sh` は毎日午前 2 時 30 分にスクリプトを実行します。 - `crontab -l` を使用してアクティブな cron ジョブをリストし、`crontab <filename>` を使用してファイルからスケジュールをロードします。
Exit Codes & Logical Chaining ($?, &&, ||)
Every command executed in Linux returns an **exit status code** between 0 and 255 upon completion: - `0`: Success (no errors occurred). - `1-255`: Failure or error code. - The special shell parameter `$?` stores the exit code of the immediately preceding command: `echo $?`. Shell logic operators chain commands based on exit codes: - `cmd1 && cmd2`: Logical AND. Runs `cmd2` **only if** `cmd1` succeeds (exit code 0). - `cmd1 || cmd2`: Logical OR. Runs `cmd2` **only if** `cmd1` fails (non-zero exit code). Combining them creates clean resilient commands: `mkdir backup && cp app.db backup/ || echo "Backup failed"`.
User Input & Command Substitution (read & $(...))
Interactive and automated scripts rely on two essential shell capabilities: 1. **User Input (`read`)**: Prompts the user to enter data and stores the response in a shell variable. The `-p` flag prints a custom prompt string: `read -p "Enter username: " USERNAME` 2. **Command Substitution (`$(...)`)**: Executes a command in a subshell and substitutes its standard output into the variable or command line: `TODAY=$(date +%F)` This lets you create dynamic timestamped filenames and automated reports.
while Loops & case Statements
Two of the most common control structures in systems engineering scripts are file-reading loops and case branches: 1. **File-reading `while` loop**: Reads input line by line safely using `read -r` without interpreting escape characters: `while read -r line; do echo "Processing: $line"; done < names.txt` 2. **`case` statement**: Matches a variable against multiple patterns cleaner than multiple `if/elif` blocks: `case $1 in start) systemctl start app ;; stop) systemctl stop app ;; *) echo "Usage: $0 {start|stop}" ;; esac`
Boss Challenge 12: Automated Healthcheck Script
OPERATIONAL REQUIREMENT: Deploy an automated system health-check script at `/home/learner/healthcheck.sh`. The script must be a valid executable Bash script containing the `#!/bin/bash` shebang on line 1, must output the token `SYSTEM_OK`, and must have executable permissions (`755` or `rwxr-xr-x`) so monitoring agents can invoke it directly without errors.
13. 高度なテキスト処理
sed
を使用したストリーム編集 巨大なデータベース ダンプ ファイルがあり、古いサーバー IP アドレスが出現するすべてを新しいものに置き換える必要があると想像してください。エディターで開くとコンピューターがフリーズする可能性があります。 Linux では、`sed` (「ストリーム エディター」の略) を使用してテキスト ストリームをオンザフライで編集します。 - テキストを検索して置換するための基本的な構文は `sed "s/old/new/g" file.txt` です。 - `-i` (インプレース) フラグを追加すると、変更されたテキストが画面上に表示されるだけでなく、置換が直接ファイル自体に保存されます。 **これが重要な理由**: `-i` を使用せずに `sed "s/port=80/port=8080/g" server.conf` を実行すると、変更されたテキストのみが端末画面に表示されます。実際のファイルは完全に変更されません。 `-i` (インプレース) フラグは、変更をファイルに直接保存するために必要です。
awk
を使用したデータ抽出 プレーン テキストとして保存された大きなスプレッドシートを受け取ることを想像してください。列はカンマまたはスペースで区切られており、データの最初の列だけを抽出する必要があります。 Linux では、強力な言語 `awk` を使用してテキストの構造化列を解析します。 - デフォルトでは、`awk` は空白によって行を分割し、列 1 を `$1`、列 2 を `$2` などに割り当てます。 - `-F` フラグを使用すると、カスタム区切り記号 (コロンの `-F:` など) を指定できます。たとえば、`awk -F: '{print $1}' /etc/passwd` はコロンで区切られたリストからユーザー名のみを抽出します。 **これが重要な理由**: `-F:` を使用せずに `awk '{print $1}' /etc/shadow` を実行すると、`awk` はコロンではなく空白 (デフォルト) で行を分割します。シャドウ ファイルの行にはスペースがないため、行全体が 1 つのフィールドとして扱われ、すべてのユーザーの完全なハッシュの詳細が出力されます。 `-F:` フラグは、`awk` にコロンで列を分割することを強制します。
データの翻訳と切り取り
トランザクションの日付と名前の CSV スプレッドシートを操作することを想像してください。最初の列 (日付) のみを抽出し、一貫性を保つためにすべてのテキストを大文字に変換したいと考えています。 Linux では、パイプラインで軽量の解析ツールを組み合わせることができます。 - `cut` コマンドは、構造化テキストから特定の列を切り出します。たとえば、`cut -d, -f1` はカンマで行を分割し (`-d,`)、最初の列を抽出します (`-f1`)。 - `tr` (変換) コマンドは、小文字を大文字に置き換える (`tr "a-z" "A-Z"`) など、標準入力の文字を変換します。 **これが重要な理由**: `-d,` と `-f1` を使用せずに `cut reports.csv` を実行すると、`cut: you must specify a list of bytes, characters, or fields` が得られます。 `-f1` を指定して `-d,` を省略した場合、デフォルトでタブが使用されます。これは、CSV ファイルを分割せず、行全体を印刷することを意味します。 `-d,` フラグは列区切り文字としてカンマを定義し、`-f1` は最初の列のみを抽出するように指示します。
Parsing JSON in the Terminal (jq)
Modern cloud infrastructure, Kubernetes, Docker, and REST APIs all communicate in JSON. The `jq` command-line JSON processor is the industry standard tool for slicing, filtering, and mapping structured JSON data in terminal pipelines. - Pretty-print and syntax validate JSON: `cat api.json | jq '.'` (or `jq '.' api.json`). - Extract specific keys: `jq '.version' api.json`. - Access array items and nested object fields: `jq '.users[0].name' api.json`. - Output unquoted raw strings (ideal for shell variables): `jq -r '.users[0].name' api.json`.
Advanced Counting & Numeric Sorting (uniq -c & sort -nr)
When troubleshooting DDoS attacks, brute force login attempts, or high-traffic API endpoints, sysadmins rely on one classic pipeline composed of `sort`, `uniq -c`, and `sort -nr`. 1. `sort access.log`: Groups identical lines together (a mandatory prerequisite for `uniq`). 2. `uniq -c`: Counts the number of duplicate occurrences for each unique line, prefixing each line with its tally count. 3. `sort -nr`: Sorts the tally lines **numerically** (`-n`) and in **reverse** (`-r`) order so the most frequent occurrences appear at the top. 4. `head -n 5`: Isolates the top 5 most frequent entries.
Binary & Hex Inspection (strings & xxd)
Binary executables and database files cannot be read with `cat` or text editors without corrupting the terminal display. Linux provides dedicated tools for inspecting compiled binaries and memory dumps: - `strings <file>`: Scans binary files and extracts continuous human-readable ASCII/UTF-8 character sequences (defaulting to 4+ characters). Essential for finding hardcoded URLs, secret keys, version strings, or embedded error messages in compiled software. - `xxd <file>` or `hexdump -C <file>`: Creates a canonical two-column hexadecimal and ASCII dump of binary files to inspect magic bytes (like `ELF` headers) and binary data offsets.
Boss Challenge 13: Data Pipeline Normalization
ETL DATA INCIDENT: A legacy mainframe exported `/home/learner/messy_data.csv` using unconventional formatting: fields are separated by colons and rows end with semicolons (`alice:dev:engineering;`). The analytics ingestion engine rejects this format. Transform the file into clean CSV format at `/home/learner/clean_users.csv`, containing only the user and department (fields 1 and 3) separated by commas (`alice,engineering`), with semicolons stripped.
14. 環境変数とシェル設定
環境変数の管理
Web アプリケーションをデプロイしていて、安全なローカルの「開発」サンドボックスで実行するか、ライブの「実稼働」データベースに接続するかを認識する必要があると想像してください。 Linux では、**環境変数**を使用して、このような構成を実行中のプログラムに渡します。 - `export` コマンドを使用して変数を定義し、シェルによって起動されたプログラムが変数を読み取れるようにします。例: `export APP_ENV=production`。 - 変数の値を確認または表示するには、変数名の前にドル記号を付けます: `echo $APP_ENV`。
環境の検査
プログラムのパスが見つからないために失敗し続けるスクリプトをデバッグしようとしている場合、またはこの端末でどのユーザー アカウントがアクティブであるかを確認したい場合を想像してください。 Linux では、これらすべてのセッション全体の構成が一緒に保存されます。 - `env` コマンドは、アクティブなセッションに現在ロードされているすべての環境変数の完全なディレクトリを出力し、一度で構成を確認できます。
コマンド (which)
の検索 `PATH` (Linux がコマンドを検索するディレクトリを保存する) などのアクティブな環境変数については理解できたので、`ls` または `grep` と入力したときに実行されるプログラムの正確なファイル パスを見つけるにはどうすればよいでしょうか。 `which` を使用してコマンド バイナリを見つけます。 - `which` コマンドは、`$PATH` 変数にリストされているフォルダーを検索し、コマンドの実行時に実行されるバイナリの絶対パスを出力します (たとえば、`which ls` は `/bin/ls` を出力します)。 - これは、ツールがインストールされている場所を見つけたり、同じツールの複数のバージョン間の競合を解決したりするのに役立ちます。
カスタム シェル ショートカット (alias)
複数のフラグを指定して長いコマンドを入力すると、非常に疲れる可能性があります。 Linux では、エイリアスと呼ばれるカスタム ショートカットを作成できます。たとえば、`ll` をマップして `ls -la` を自動的に実行できます。 - 一時的なエイリアスを作成するには、`alias name='command'` (例: `alias ll='ls -la'`) を実行します。 - 引数なしで `alias` を実行すると、現在のセッション内のすべてのアクティブなエイリアスが一覧表示されます。 - エイリアスを再起動後も永続的にするには、通常、エイリアスは `.bashrc` または `.bash_profile` 構成ファイルに書き込まれます。
Reloading Shell Configs (source & .bashrc)
When you edit your startup scripts like `~/.bashrc` to add new environment variables or aliases, those changes do not automatically affect your current shell session. Traditionally, users had to log out and log back in. In Linux, we use the `source` command (or its POSIX shorthand `.`) to read and execute commands from a file directly in the current shell context. - Syntax: `source ~/.bashrc` or `. ~/.bashrc` - This loads newly defined variables, updated `$PATH` directories, and aliases immediately without killing your session.
Cleaning the Environment (unset & unalias)
During debugging or deployment, you may temporarily export sensitive API keys, database credentials, or create test shortcuts. Leaving these variables active in your environment can cause security leaks or unintended script behavior. Linux provides `unset` to delete variables and `unalias` to delete custom command shortcuts. - `unset SECRET_KEY`: Permanently deletes the `SECRET_KEY` variable from the current environment. - `unalias la`: Removes the shortcut `la` so typing `la` no longer executes `ls -a`.
Boss Challenge 14: Compromised Environment Cleanup
SECURITY BREACH: A malicious session injected a backdoor path `/tmp/evil_bin` into `/home/learner/.bashrc`, attempting to hijack user commands. Eradicate the persistence mechanism: clean `/home/learner/.bashrc` by removing all references to `evil_bin`, and delete the `/tmp/evil_bin` directory entirely from the system.
15. アーカイブ・バックアップ・チェックサム
アーカイブと圧縮 (tar)
500 件のサーバー ログを含むフォルダーがあり、それを同僚に電子メールで送信するか、クラウド ストレージにバックアップしたいとします。 500 個の個別ファイルを送信するのは時間がかかり、非効率的です。 Linux では、`tar` (「テープ アーカイブ」の略) を使用して、それらを単一のコンパクトな zip のようなファイルに圧縮します。 - フラグを使用して圧縮アーカイブを作成します: `-c` (作成)、`-z` (gzip で圧縮)、`-v` (ファイルの詳細リスト)、および `-f` (ファイル名を指定)。たとえば、`tar -czvf backup.tar.gz folder/` はディレクトリをバンドルして圧縮します。 **これが重要な理由**: `-f` を使用せずに `tar -cz logs.tar.gz logs` を実行すると、`tar: Refusing to write archive contents to terminal` が得られます。 `-f` フラグは、生のバイナリ アーカイブ データを端末に直接送信するのではなく、出力をファイルに書き込むように `tar` に指示するため、重要です。 `-c` フラグと `-z` フラグも、それぞれアーカイブの作成と圧縮に必要です。
ファイル圧縮 (gzip & gunzip)
大規模なデータセットを含む 1 つのテキスト ファイルがあり、ディスク領域を節約したり、共有を高速化するためにそのサイズを削減したいとします。 Linux では、`gzip` を使用して個々のファイルを圧縮し、`gunzip` を使用して復元します。 - `gzip <filename>` コマンドはファイルを圧縮し、`.gz` で終わる圧縮バージョンに置き換えます (例: `backup.txt` は `backup.txt.gz` になります)。 - `gunzip <filename.gz>` コマンドはファイルを解凍し、元のバージョンを復元します。
zip および unzip
によるアーカイブ Linux では `tar` と `gzip` が標準ですが、クロスプラットフォームの世界 (Windows/macOS) では `zip` が最も一般的なアーカイブ形式です。 Linux では、`zip` を使用してファイルを zip ファイルにパッケージ化および圧縮し、`unzip` を使用して解凍します。 - `zip <archive.zip> <files>` コマンドは zip アーカイブを作成します。 - `unzip <archive.zip>` コマンドはアーカイブからファイルを抽出します。
代替圧縮 (bzip2 & xz)
`gzip` および `zip` を超えて、Linux は、CPU 速度を犠牲にしてより高い圧縮率を実現するために最適化された他の圧縮形式をサポートしています。これらは、`bzip2` (bz2) と `xz` (xz) です。 - `bzip2 <file>` コマンドはファイルを圧縮し、`<file>.bz2` を出力します。 - `xz <file>` コマンドは、ロスレス LZMA 圧縮を使用して `<file>.xz` を作成します。これにより、ファイル サイズが非常に小さくなるため、Linux カーネル リリースに最適です。
リンクの作成 (ln -s)
ネストされたフォルダー (`/var/www/html/configs/app/settings.conf` など) の奥深くに構成ファイルが埋め込まれているが、それを常に編集する必要があると想像してください。毎回長いフォルダー パスを入力する代わりに、デスクトップにすばやくショートカットを作成したいと考えています。 Linux では、リンクを作成することでこれを行います。 - **ハード リンク**: 生のファイル データを指す直接クローン。元のファイルを削除しても、リンクは引き続き機能します。 - **シンボリック リンク (ソフト リンク)**: パスベースのショートカット (Windows ショートカットと同様)。元のファイルを削除するとリンクが切れてしまいます。 `ln -s target link_name` を使用して作成します。 **これが重要な理由**: `-s` を使用せずに `ln logs/app.log app_link.log` を実行すると、シンボリック ショートカットではなくハード リンクが作成されます。ファイルが異なるディスク パーティションに存在する場合は、`ln: failed to create hard link: Invalid cross-device link` が返されます。 `-s` フラグは、さまざまなドライブやディレクトリ間で機能する柔軟なシンボリック リンク (ショートカット) を作成します。
検索結果 (xargs) の処理
検索を実行して 100 個の一時ファイルが返されたので、それらをすべて削除したいとします。検索出力は画面上の単なるテキスト名のリストです。これらの名前を削除コマンドへの直接入力としてどのように入力するのでしょうか? Linux では、`xargs` を使用してこのギャップを埋めます。 - `xargs` (引数の実行) コマンドは、標準入力の行 (`find` からのファイル リストなど) を受け取り、それらを引数として 1 行ずつ別のコマンドに渡します。 - たとえば、`find . -name "*.tmp" | xargs rm` はすべての一時ファイルを検索し、1 回のスイープですべて削除します。
Repairing Symbolic Links (ln -sf)
DANGLING LINK ALERT: Following a log consolidation migration, the operational link at `/home/learner/links/current_log` became dangling because its original target was moved. Repair the link farm: update the symbolic link `/home/learner/links/current_log` so it points directly to the real system logging destination `/var/log/syslog`.
Incremental Sync with rsync
While `cp` blindly copies entire files every time, `rsync` (remote sync) uses a delta-transfer algorithm to copy only files and bytes that have changed. It is the gold standard for server migrations, incremental directory backups, and continuous mirroring. - `-a` (archive): Preserves timestamps, symlinks, permissions, and operates recursively. - `-v` (verbose): Shows which files are being copied. - `-z` (compress): Compresses file data during transmission. - Notice trailing slashes: `rsync -avz src/ backup/` copies the contents of `src/` inside `backup/`.
Verifying File Integrity (sha256sum & md5sum)
When downloading critical software, ISO images, or backup tarballs over the network, files can become corrupted by transmission errors or tampered with by malicious actors. In Linux, cryptographic checksums verify file integrity bit-for-bit. - `sha256sum <file>`: Computes a 256-bit SHA-2 cryptographic hash. - `md5sum <file>`: Computes a 128-bit MD5 digest. - If a single bit in the file changes, the entire hash string changes completely (the avalanche effect).
Block Cloning & Temp Files (dd & mktemp)
Sometimes system administrators need to manipulate raw disk blocks rather than regular filesystem files—such as creating empty swapfiles, zeroing out drives, or writing ISO images directly to USB disks. We use `dd` (dataset definition). - `dd if=<source> of=<destination> bs=<block_size> count=<number>` clones raw blocks. - E.g. `dd if=/dev/zero of=disk.img bs=1M count=1` creates a 1MB dummy disk file filled with null bytes. - When automation scripts require scratch files without race conditions or overwriting existing user data, `mktemp` creates uniquely named files under `/tmp`.
Boss Challenge 15: Corrupted Backup & Checksum Recovery
DATA INTEGRITY INCIDENT: The nightly backup pipeline flagged a corrupted archive in `/home/learner/backups/data_backup.tar.gz`. The mission-critical archive failed integrity checks. 1. Run `sha256sum -c checksums.sha256` inside `/home/learner/backups` (or `sha256sum -c /home/learner/backups/checksums.sha256`) to confirm the corrupted file (`FAILED`). 2. Overwrite the corrupted archive by copying the pristine valid backup from the system cache at `/var/backups/data_backup.tar.gz` into `/home/learner/backups/data_backup.tar.gz`. 3. Re-verify the backup using `sha256sum -c checksums.sha256` to confirm integrity (`data_backup.tar.gz: OK`).
16. リモートアクセスとユーザー管理
ユーザー管理 (useradd & passwd)
これまでは、`learner` ユーザーとして作業してきました。しかし、現実のサーバーでは、システム管理者は複数のアカウントを管理する必要があります。新しいユーザーを追加し、パスワードを設定する方法を学びましょう。 - `useradd` コマンドは、新しいユーザー アカウントを作成します。アカウントの作成はシステムのセキュリティに影響するため、スーパーユーザー権限 (`sudo useradd deployer` など) で実行する必要があります。 - `passwd` コマンドは、ユーザーのパスワードを設定または変更します。 `sudo passwd deployer` として実行して、デプロイヤ ユーザーのパスワードを設定します。
ユーザーの管理 (adduser & userdel)
`useradd` はシステム構成ファイルにユーザーの詳細を登録するだけの低レベル ユーティリティですが、Debian/Ubuntu システムは、ホーム フォルダーの作成、パスワードの設定、およびシェル環境の初期化を自動化する `adduser` と呼ばれる高レベルの対話型スクリプトを提供します。逆に、`userdel` はユーザー アカウントを完全に削除します。 - `sudo adduser tester` を実行すると、対話形式でユーザー構成をガイドできます。 - `sudo userdel tester` を実行すると、ユーザー アカウントが削除されます。
ユーザー ID (id)
の表示 権限エラーのトラブルシューティングを行う場合は、実行している正確なユーザーおよびグループ ID コンテキストを確認する必要があります。これは `id` を使用して行います。 - `id` を実行すると、現在のユーザーのユーザー ID (UID)、プライマリ グループ ID (GID)、およびすべての補足グループ リストが出力されます。 - `id <username>` を実行すると、特定のユーザーの情報がクエリされます。
グループ管理 (groupadd & groups)
Linux では、ユーザーは権限を簡単に共有するために **グループ**に編成されます。たとえば、すべての開発者が `developers` という名前のグループに属しているとします。これにより、チーム全体で一度にファイルを共有できるようになります。 - `groupadd` コマンドは新しいグループを作成します。これはシステム構成であるため、スーパーユーザー権限が必要です (例: `sudo groupadd developers`)。 - `groups [username]` コマンドは、ユーザーが属するすべてのグループを一覧表示します。引数なしで実行すると、現在のユーザーのグループが表示されます。
グループの削除 (groupdel)
プロジェクト チームがサービスを再編成または廃止する場合、対応するセキュリティ グループをクリーンアップする必要があります。 Linux では、`groupdel` を使用してグループを削除します。 - `groupdel <group_name>` コマンドは、システム構成ファイルからグループを永久に削除します。これにはスーパーユーザー権限が必要です。
セキュリティ コンテキストの切り替え (su)
`deployer` アカウントを作成したので、ローカルでログインしてその環境をテストするにはどうすればよいでしょうか? Linux では、`su` (代替ユーザー) コマンドを使用して、ログアウトせずにアカウントを切り替えます。 - `su <username>` コマンドは、現在の端末シェルをそのユーザーのセッションに切り替えます。 - 切り替えた場合、`whoami` を実行すると、新しいユーザー名が反映されます。 - 元のユーザー アカウント セッションに戻るには、`exit` と入力するか、`Ctrl+D` を押します。
Secure Shell Access (ssh)
ユーザーをローカルに切り替えることは便利ですが、クラウド コンピューティングでは、サーバーはリモート データ センターに存在します。ネットワーク経由で安全に接続するには、`ssh` (Secure Shell) を使用します。 - `ssh` コマンドは、盗聴を防ぐためにマシンとリモート ホスト間の接続を暗号化します。 - 構文: `ssh user@hostname` または `ssh user@ip_address` (例: `ssh admin@192.168.1.100`)。 - 最初の接続では、一意の ECDSA フィンガープリントを表示して、リモート ホストの信頼性を確認するよう求められます。 **注意:** これはブラウザベースのサンドボックスであるため、接続するための実際のリモート サーバーはありません。このコマンドを実行すると、実際のライブ対話型セッションではなく、予想される実際の出力パターン (ホスト検証、接続、セッション) が即座に表示されます。実際の端末では、`exit` と入力するまで、ssh によってまったく別のリモート シェルが表示されます。
Secure File Transfer (scp)
SSH 経由でリモート サーバーにログインする方法はわかったので、ローカル ファイル (バックアップ アーカイブなど) をリモート サーバーにコピーするにはどうすればよいでしょうか? `scp` (安全なコピー) コマンドは、内部で SSH を使用してホスト間でファイルを安全にコピーします。 - 構文は `scp source_path user@host:destination_path` です。 - たとえば、`scp log.txt admin@192.168.1.100:/tmp/` はローカルの `log.txt` ファイルをリモートの `/tmp/` フォルダーにコピーします。 **注意:** ssh と同様に、ここには実際のリモート サーバーはありません。このコマンドを実行すると、ローカル ファイルが存在することが確認され、予想される転送出力が表示されますが、実際にはデータはどこにも送信されません。
Modifying User Groups & Shell (usermod)
When onboarding engineers or automation service accounts, you must configure their supplementary group memberships and default login shells. In Linux, `usermod` modifies existing accounts in `/etc/passwd` and `/etc/group`. - `-aG <group>`: Appends the user to supplementary groups without removing them from existing groups. (CRITICAL: omitting `-a` would replace all existing secondary groups!). - `-s <shell>`: Specifies the new login shell (e.g. `/bin/bash` or `/usr/sbin/nologin`).
SSH Key Authentication (ssh-keygen & ssh-copy-id)
Password authentication on remote SSH servers is vulnerable to brute-force attacks and credential stuffing. Production infrastructure relies on asymmetric SSH keypair authentication. - `ssh-keygen -t ed25519`: Generates a high-security Ed25519 public/private keypair (`~/.ssh/id_ed25519` and `~/.ssh/id_ed25519.pub`). - `ssh-copy-id deployer@192.168.1.50`: Automatically appends your local public key to the remote user's `~/.ssh/authorized_keys` file, enabling passwordless login.
Auditing Active Sessions (who, w & last)
When investigating unexpected system load or performing security audits on multi-tenant servers, you must know who is logged in and what commands they are executing. - `who`: Prints logged-in usernames, terminal devices (TTY/PTS), and login timestamps. - `w`: Comprehensive snapshot showing system uptime, load averages, logged-in users, and their currently running processes. - `last`: Parses `/var/log/wtmp` to show recent system reboot and user login history.
Terminal Multiplexing (tmux)
When working over SSH, closing your laptop lid or losing Wi-Fi sends a hangup signal (SIGHUP) that immediately terminates your long-running builds, database dumps, and tests. A terminal multiplexer like `tmux` runs persistent virtual terminals on the server independent of your SSH connection. - `tmux new -s <name>`: Starts a new persistent session. - `tmux ls`: Lists all running sessions. - `tmux attach -t <name>`: Re-attaches to a running session from any computer at any time.
Boss Challenge 16: Unauthorized User & Group Audit
FINAL SECURITY AUDIT: An intrusion detection audit revealed that an unauthorized user account `backdoor` was quietly added to `/etc/passwd`, and an unauthorized administrative group `rogue_admins` was added to `/etc/group`. Audit and cleanse the authentication databases: inspect the files with `cat` or `grep`, safely remove the `backdoor` user using `sudo userdel backdoor`, and delete the `rogue_admins` group using `sudo groupdel rogue_admins`. Verify that both unauthorized entries have been completely eradicated.
17. GitとLinuxコンテナ
Version Control Basics (git status, diff, log)
Modern Linux servers and cloud infrastructure rely on Git for version control, continuous integration, and infrastructure-as-code deployments. Let's master the core introspection commands. - `git status`: Checks working tree and staging area state, revealing modified, untracked, and staged files. - `git diff`: Shows line-by-line differences between modified files and the last commit. - `git log`: Displays commit hashes, author metadata, and change messages.
Inspecting Linux Containers (docker ps, logs, exec)
Docker encapsulates applications inside isolated Linux cgroups and namespaces (containers). As a DevOps engineer or sysadmin, troubleshooting containerized workloads requires inspecting running containers and executing commands within their namespaces. - `docker ps`: Lists running containers, container IDs, images, uptime, and mapped network ports. - `docker logs <container>`: Streams standard output and error logs generated by the containerized service. - `docker exec -it <container> <command>`: Executes an interactive or diagnostic command directly inside the container namespace.
Staging & Committing Code (git add, git commit, git branch)
In Git version control, modifications made to working files must be staged before they can be committed into repository history. - `git add <file>`: Stages modified files into the index (e.g., `git add server.js`), preparing them for commit. - `git commit -m "<message>"`: Records a permanent snapshot of staged changes with a descriptive message (e.g., `git commit -m "Fix config"`). - `git branch`: Lists all local repository branches and indicates the currently active branch with an asterisk.
Managing Container Lifecycle (docker start, stop, restart)
Managing microservices in production requires controlling container lifecycle states when restarting services after configuration changes or stopping unneeded containers. - `docker restart <name>`: Gracefully stops and immediately starts a running container (e.g., `docker restart web-api`). - `docker stop <name>`: Stops an actively running container (e.g., `docker stop web-api`). - `docker start <name>`: Boots up an existing stopped container without creating a new instance (e.g., `docker start web-api`).
Boss Challenge 17: Containerized Hotfix & Git Deployment
PRODUCTION OUTAGE: The production web service in container `web-api` is failing health checks because `server.js` was modified with the wrong port. 1. Check the failure logs using `docker logs web-api`. 2. Inspect the repository changes using `git status` and `git diff`. 3. Stage the fix by running `git add server.js`. 4. Commit the fix with `git commit -m "Fix port binding for production"`. 5. Restart the containerized service using `docker restart web-api` to apply the hotfix.
Who Am I and Where Am I?.
コマンドリファレンス
達成目標チェックリスト
公開されたヒント
File Explorer
BashQuestとは?
完全無料のオンラインLinuxターミナル練習プラットフォーム。仮想ファイルシステム上で本物のシェルコマンドを実行し、即座にフィードバックを受け取れます。
BashQuestとは?
BashQuestは、実践的なコマンドライン教育のために作られた無料のオンラインLinuxターミナル練習プラットフォームです。動画を見るだけの受動的な学習とは異なり、実際にキーボードでコマンドを入力して習得します。
体系的な学習目標を備えた高機能なオンラインLinux環境です。100%安全で、ブラウザ内で完結します。
開発の背景
Linuxを学び始めたとき、誤ったコマンドでシステムを壊してしまうのではないかと不安でした。仮想マシンをインストールすることなく、誰でもゼロリスクで学べる最高の環境を作りたいと考えました。
反復練習こそがマスターへの近道です。コマンド入力、出力の確認、修正のサイクルを通じて本物のマッスルメモリー(身体感覚)が身につきます。
即時フィードバック付きの無料オンラインLinuxターミナル練習
コマンドを打った直後に結果を確認することで、知識が定着します。BashQuestはブラウザ上でリアルタイムに検証される仮想Linux環境を提供します。
効果的な学習のための仮想Linuxターミナル
体系的な学習目標を備えた高機能なオンラインLinux環境です。100%安全で、ブラウザ内で完結します。
ハンズオン練習が定着率を高める理由
反復練習こそがマスターへの近道です。コマンド入力、出力の確認、修正のサイクルを通じて本物のマッスルメモリー(身体感覚)が身につきます。
学べる内容
段階的なカリキュラムで、Linux管理の17のコアスキルを習得できます:
ファイルシステムの基本
ファイル操作
パイプとフィルタリング
リダイレクトとセキュリティ
スーパーユーザーとパッケージ
ディスクとシステムリソース
プロセス管理
ネットワークのトラブルシューティング
ファイル検索とコマンド探索
サービスとSystemd
ターミナルでのテキスト編集
シェルスクリプトと自動化
高度なテキスト処理
環境変数とシェル設定
アーカイブ・バックアップ・チェックサム
リモートアクセスとユーザー管理
GitとLinuxコンテナ
Linux Webツール & ユーティリティ
chmodパーミッション計算、cron設定生成、正規表現テスト、コマンド検索を行うWebツール群です。
Chmod calculator
Octal & symbolic output
chmod 000 [file]Cron job explainer
Plain-English translation
Command synthesizer
Pick a task, get the command
Select a task above to see the command.
—🛠️ Custom Quest & Lab Builder
Design & share custom quests