Debianリファレンス

青木 [FAMILY Given]

本Debianリファレンス(第2版) (2009-06-26 15:13:16 UTC) はシステムインストール後のユーザ案内書として、Debian システムの広範な概論を提供します。本書は非開発者を対象にシェルコマンド例を通してシステム管理の多くの局面を説明します。

概要

This book is free; you may redistribute it and/or modify it under the terms of the GNU General Public License of any version compliant to the Debian Free Software Guidelines (DFSG). (日本語による参考説明:本書はフリーです; Debianフリーソフトウェアガイドライン(DFSG)に適合するいかなるバージョンのGNU General Public Licenseの条件の下ででも再配布や改変をすることを許可します。)


目次

序章
1. 免責事項
2. Debianとはなにか
3. 本書について
3.1. 編集指針
3.2. 前提条件
3.3. 文書様式
3.4. Popcon
3.5. パッケージサイズ
3.6. バグ報告
4. 新規ユーザへの引用文
1. GNU/Linuxチュートリアル
1.1. コンソールの基礎
1.1.1. シェルプロンプト
1.1.2. Xの下でのシェルプロンプト
1.1.3. rootアカウント
1.1.4. rootシェルプロンプト
1.1.5. GUIのシステム管理ツール
1.1.6. 仮想コンソール
1.1.7. コマンドプロンプトからの退出方法
1.1.8. シャットダウンの方法
1.1.9. まともなコンソールの回復
1.1.10. 初心者向け追加パッケージの提案
1.1.11. 追加のユーザアカウント
1.1.12. sudoの設定
1.1.13. お遊びの時間
1.2. Unix-likeファイルシステム
1.2.1. Unixファイルの基礎
1.2.2. ファイルシステムの内側
1.2.3. ファイルシステムのパーミッション
1.2.4. 新規作成ファイルのパーミッションのコントロール:umask
1.2.5. ユーザのグループ(group)のパーミッション
1.2.6. タイムスタンプ
1.2.7. リンク
1.2.8. 名前付きパイプ(FIFO)
1.2.9. ソケット
1.2.10. デバイスファイル
1.2.11. 特別なデバイスファイル
1.2.12. procfsとsysfs
1.3. ミッドナイトコマンダー(MC)
1.3.1. MCのカスタム化
1.3.2. MCの始動
1.3.3. MCのファイルマネージャ
1.3.4. MC のコマンドライントリック
1.3.5. MCの内部エディタ
1.3.6. MCの内部ビューア
1.3.7. MCの自動起動機能
1.3.8. MCのFTP仮想ファイルシステム
1.4. 基本のUnix的作業環境
1.4.1. loginシェル
1.4.2. Bashのカスタム化
1.4.3. 特別のキーストローク
1.4.4. Unix流のマウス操作
1.4.5. ページャ
1.4.6. テキストエディタ
1.4.7. デフォルトのテキストエディタの設定
1.4.8. Vimのカスタム化
1.4.9. シェル活動の記録
1.4.10. 基本Unixコマンド
1.5. シェルプロンプト
1.5.1. コマンド実行と環境変数
1.5.1.1. "$LANG"変数
1.5.1.2. "$PATH"変数
1.5.1.3. "$HOME"変数
1.5.2. コマンドラインオプション
1.5.3. シェルグロブ
1.5.4. コマンドの戻り値
1.5.5. 典型的なコマンドシーケンスとシェルリディレクション
1.5.6. コマンドエリアス
1.6. Unix的テキスト処理
1.6.1. Unixテキストツール
1.6.2. 正規表現
1.6.3. 置換表現
1.6.4. 正規表現を使ったグローバル置換
1.6.5. テキストファイルからのデータ抽出
1.6.6. コマンドをパイプするためのスクリプト断片
2. Debianパッケージ管理
2.1. Debainパッケージ管理の前提条件
2.1.1. パッケージ設定
2.1.2. 基本的な注意事項
2.1.3. 永遠のアップグレード人生
2.1.4. Debianアーカイブの基本
2.1.5. パッケージ依存関係
2.1.6. パッケージ管理のイベントの流れ
2.1.7. パッケージ管理のトラブルへの応急対処法
2.2. 基本的パッケージ管理操作
2.2.1. コマンドラインによる基本的なパッケージ管理操作
2.2.2. aptitudeのインタラクティブな使用
2.2.3. aptitudeのキーバインディング
2.2.4. aptitudeの下でのパッケージの表示
2.2.5. aptitudeを使った探索方法
2.2.6. aptitudeのregex式
2.2.7. aptitudeによる依存関係の解決
2.2.8. パッケージアクティビティーログ
2.2.9. Aptitudeの長所
2.3. aptitude操作例
2.3.1. regexにマッチするパッケージ名のパッケージをリスト
2.3.2. regexマッチをして閲覧
2.3.3. パッケージを本当に完全削除
2.3.4. 自動/手動インストールの状態の整理
2.3.5. aptitudeを使ったシステム全体のアップグレード
2.4. 高度なパッケージ管理操作
2.4.1. コマンドラインによる高度なパッケージ管理操作
2.4.2. インストールされたパッケージファイルの検証
2.4.3. パッケージの問題に対する防御
2.4.4. パッケージメタデータの検索
2.5. Debianパッケージ管理の内部
2.5.1. アーカイブのメタデータ
2.5.2. トップレベルの"Release"ファイルと信憑性
2.5.3. アーカイブレベルの"Release"ファイル
2.5.4. パッケージメタデータの取得
2.5.5. APTに関するパッケージ状態
2.5.6. aptitudeに関するパッケージ状態
2.5.7. 取得したパッケージのローカルコピー
2.5.8. Debianパッケージファイル名
2.5.9. dpkgコマンド
2.5.10. update-alternativeコマンド
2.5.11. dpkg-statoverrideコマンド
2.5.12. dpkg-divertコマンド
2.6. 壊れたシステムからの回復
2.6.1. 古いユーザの設定との非互換性
2.6.2. 重複するファイルを持つ相異なるパッケージ
2.6.3. 壊れたパッケージスクリプトの修正
2.6.4. dpkgコマンドを使っての救済
2.6.5. パッケージセレクションの回復
2.7. パッケージ管理のヒント
2.7.1. Debianパッケージの選択方法
2.7.2. 混合したアーカイブソースからのパッケージ
2.7.3. 候補バージョンの調整
2.7.4. VolatileとBackports.org
2.7.5. パッケージの自動ダウンロードとアップグレード
2.7.6. APTのよるダウンロードバンド幅の制限
2.7.7. 緊急ダウングレード
2.7.8. 誰がパッケージをアップロードしたのか?
2.7.9. equivsパッケージ
2.7.10. 安定版システムへのパッケージ移植
2.7.11. APTのためのプロキシサーバー
2.7.12. 小さな公開パッケージアーカイブ
2.7.13. システム設定の記録/コピー
2.7.14. 外来のバイナリパッケージを変換やインストールする
2.7.15. dpkgを使わずにパッケージを開梱
2.7.16. パッケージ管理の追加参考文書
3. システムの初期化
3.1. ブートストラッププロセスの概要
3.2. 1段目: BIOS
3.3. 2段目: ブートローダ
3.4. 3段目: ミニDebianシステム
3.5. 4段目: 通常のDebianシステム
3.5.1. runlevelの意味
3.5.2. runlevelの設定
3.5.3. runlevel管理例
3.5.4. 各initスクリプトのデフォルトのパラメータ
3.5.5. ホスト名
3.5.6. ネットワークインターフェースの初期化
3.5.7. ネットワークサービスの初期化
3.5.8. システムメッセージ
3.5.9. カーネルメッセージ
3.5.10. udevシステム
3.5.11. カーネルモジュール初期化
4. 認証
4.1. 通常のUnix認証
4.2. アカウントとパスワードの情報管理
4.3. 良好なパスワード
4.4. 暗号化されたパスワード作成
4.5. PAM と NSS
4.5.1. PAMとNSSによってアクセスされるコンフィギュレーションファイル
4.5.2. 最新の集中システム管理
4.5.3. 「どうしてGNUのsuはwheelグループをサポートしないのか」
4.5.4. パスワード規則強化
4.6. 他のアクセスコントロール
4.6.1. sudo
4.6.2. SELinux
4.6.3. サーバーのサービスへのアクセスの制限
4.7. 認証のセキュリティ
4.7.1. インターネット経由のセキュアなパスワード
4.7.2. セキュアシェル
4.7.3. インターネットのためのセキュリティ強化策
4.7.4. rootパスワードのセキュリティ確保
5. ネットワークの設定
5.1. 基本的ネットワークインフラ
5.1.1. ドメイン名
5.1.2. ホスト名の解決
5.1.3. ネットワークインターフェース名
5.1.4. LANのためのネットワークアドレス範囲
5.1.5. ネットワーク設定インフラ
5.1.6. ネットワークデバイスサポート
5.2. ネットワーク接続方法
5.2.1. イーサーネットを使ってのDHCP接続
5.2.2. イーサーネットを使っての静的IP接続
5.2.3. pppconfigを使ってのPPP接続
5.2.4. wvdialconfを使った代替PPP接続
5.2.5. pppoeconfを使ったPPPoE接続
5.3. ifupdownを使った基本的なネットワーク設定
5.3.1. 簡略化されたコマンドシンタックス
5.3.2. "/etc/network/interfaces"の基本的なシンタックス
5.3.3. ループバックネットワークインターフェース
5.3.4. DHCPサービスを受けるネットワークインターフェース
5.3.5. 静的IPを使うネットワークインターフェース
5.3.6. ワイアレスLANインターフェースの基本
5.3.7. WPA/WPA2を使うワイアレスLANインターフェース
5.3.8. WEPを使うワイアレスLANインターフェース
5.3.9. PPP接続
5.3.10. 代替のPPP接続
5.3.11. PPPoE接続
5.3.12. ifupdownのネットワーク設定状態
5.3.13. 基本ネットワーク設定
5.3.14. ifupdown-extraパッケージ
5.4. ifupdownを使う上級ネットワーク設定
5.4.1. ifplugdパッケージ
5.4.2. ifmetricパッケージ
5.4.3. 仮想インターフェース
5.4.4. 上級コマンドシンタックス
5.4.5. mappingスタンザ
5.4.6. 手動切り替え可能なネットワーク設定
5.4.7. ifupdownシステムを使うスクリプト
5.4.8. guessnetを使うmapping
5.5. デスクトップのためのネットワーク設定
5.5.1. GUIのネットワーク設定ツール
5.5.2. 自動ネットワーク設定
5.6. 低レベルネットワーク設定
5.6.1. Iproute2コマンド
5.6.2. 安全な低レベルネットワーク操作
5.7. ネットワークの最適化
5.7.1. 最適MTUの発見
5.7.2. MTUの設定
5.7.3. WAN TCPの最適化
5.8. Netfilter
6. ネットワークアプリケーション
6.1. ウエッブブラウザ
6.1.1. ブラウザ設定
6.2. メールシステム
6.2.1. Modern mail service basics
6.2.2. Basic mail software choice
6.2.3. The mail configuration strategy for workstation
6.2.3.1. exim4設定
6.2.3.2. The configuration of postfix with SASL
6.2.3.3. メールアドレス設定
6.2.4. Tips for managing the mail
6.2.4.1. 基本的なMTAの操作
6.2.4.2. Basic MUA — Mutt
6.2.4.3. Redeliver mbox contents
6.2.5. Choices of software for the mail
6.2.5.1. MTA
6.2.5.2. MUA
6.2.5.3. The remote mail retrieval and forward utility
6.2.5.4. MDA with filter
6.2.5.5. POP3/IMAP4 server
6.3. The print server and utility
6.4. The remote access server and utility (SSH)
6.4.1. Basics of SSH
6.4.2. Port forwarding for SMTP/POP3 tunneling
6.4.3. Connecting with fewer passwords — RSA
6.4.4. Dealing with alien SSH clients
6.4.5. Setting up ssh-agent
6.4.6. Troubleshooting SSH
6.5. Other network application servers
6.6. Other network application clients
6.7. The diagnosis of the system daemons
7. The X window system
7.1. 重要パッケージ
7.2. Setting up desktop environment
7.2.1. Debianメニュー
7.2.2. Freedesktop.org menu
7.2.3. Debian menu under GNOME desktop environment
7.3. The server/client relationship
7.4. The X server
7.4.1. The (re)configuration of the X server
7.4.2. The connection methods to the X server
7.5. Starting the X window system
7.5.1. Starting X session with gdm
7.5.2. Customizing the X session (classic method)
7.5.3. Customizing the X session (new method)
7.5.4. Connecting a remote X client via SSH
7.5.5. インターネット経由のセキュアなXターミナル
7.6. Fonts in the X window
7.6.1. 基本的フォント
7.6.2. Additional fonts
7.6.3. CJK fonts
7.7. X applications
7.7.1. X office applications
7.7.2. X utility applications
7.8. The X trivia
7.8.1. Keymaps and pointer button mappings in X
7.8.2. Classic X clients
7.8.3. The X terminal emulator — xterm
7.8.4. Running X clients as root
8. I18N and L10N
8.1. The keyboard input
8.1.1. The input method support with SCIM
8.1.2. An example for Japanese
8.1.3. Disabling the input method
8.2. The display output
8.3. ロケール
8.3.1. Basics of encoding
8.3.2. Rationale for UTF-8 locale
8.3.3. ロケールの再設定
8.3.4. Configuring system with "$LANG"
8.3.5. Specific locale only under X Window
8.3.6. Filename encoding
8.3.7. Localized messages and translated documentation
8.3.8. Effects of the locale
9. System tips
9.1. screenプログラム
9.1.1. The use scenario for screen(1)
9.1.2. Key bindings for the screen command
9.2. Data recording and presentation
9.2.1. ログデーモン
9.2.2. Log analyzer
9.2.3. Recording the shell activities cleanly
9.2.4. Customized display of text data
9.2.5. Customized display of time and date
9.2.6. Colorized shell echo
9.2.7. Colorized commands
9.2.8. Recording the graphic image of an X application
9.2.9. 設定ファイルの変更記録
9.3. Data storage tips
9.3.1. パーティション設定
9.3.2. Accessing partition using UUID
9.3.3. ファイルシステム設定
9.3.4. Filesystem creation and integrity check
9.3.5. Optimization of filesystem by mount options
9.3.6. Optimization of filesystem via superblock
9.3.7. ハードディスクの最適化
9.3.8. Using SMART to predict harddisk failure
9.3.9. Expand usable storage space via LVM
9.3.10. Expand usable storage space by mounting another partition
9.3.11. Expand usable storage space using symlink
9.3.12. Expand usable storage space using aufs
9.4. Data encryption tips
9.4.1. Removable disk encryption with dm-crypt/LUKS
9.4.2. Encrypted swap partition with dm-crypt
9.4.3. Automatically encrypting files with eCryptfs
9.4.4. Automatically mounting eCryptfs
9.5. Monitoring, controlling, and starting program activities
9.5.1. Time a process
9.5.2. スケジューリングのプライオリティー
9.5.3. psコマンド
9.5.4. topコマンド
9.5.5. List files opened by a process
9.5.6. Trace program activities
9.5.7. Identify processes using files or sockets
9.5.8. Repeating a command with a constant interval
9.5.9. Repeating a command looping over files
9.5.10. Starting a program from GUI
9.5.11. Customizing program to be started
9.5.12. Kill a process
9.5.13. Schedule tasks once
9.5.14. Schedule tasks regularly
9.5.15. Alt-SysRq
9.6. System maintenance tips
9.6.1. Who is logged on
9.6.2. Warn everyone
9.6.3. Hardware identification
9.6.4. ハードウエア設定
9.6.5. System and hardware time
9.6.6. ターミナルの設定
9.6.7. The sound infrastructure
9.6.8. Disable the screen saver
9.6.9. Disable the sound (beep)
9.6.10. 使用メモリ
9.6.11. System security and integrity check
9.7. カーネル
9.7.1. Linux kernel 2.6
9.7.2. Kernel headers
9.7.3. Kernel and module compile
9.7.4. Kernel source compile: Debian standard method
9.7.5. Module source compile: Debian standard method
9.7.6. Kernel source compile: classic method
9.7.7. Non-free hardware drivers
9.8. 仮想化システム
9.8.1. 仮想化ツール
9.8.2. Chrootシステム
9.8.3. Setting up login for chroot
10. データ管理
10.1. 共有とコピーとアーカイブ
10.1.1. Archive and compression tools
10.1.2. Copy and synchronization tools
10.1.3. アーカイブのための慣用句
10.1.4. Idioms for the copy
10.1.5. Idioms for the selection of files
10.1.6. Backup and recovery
10.1.7. Backup utility suites
10.1.8. An example script for the system backup
10.1.9. A copy script for the data backup
10.1.10. Removable mass storage device
10.1.11. Sharing data via network
10.1.12. アーカイブ媒体
10.2. バイナリデータ
10.2.1. Make the disk image file
10.2.2. Writing directly to the disk
10.2.3. View and edit binary data
10.2.4. Mount the disk image file
10.2.5. Manipulating files without mounting disk
10.2.6. データファイルの回復と事故の証拠解析
10.2.7. Make the ISO9660 image file
10.2.8. Writing directly to the CD/DVD-R/RW
10.2.9. Mount the ISO9660 image file
10.2.10. Split a large file into small files
10.2.11. Clear file contents
10.2.12. Dummy files
10.2.13. Erase entire harddisk
10.2.14. Undelete deleted but still open file
10.2.15. Searching all hardlinks
10.2.16. Invisible disk space consumption
10.3. Data security infrastructure
10.3.1. Gnupgのためのキー管理
10.3.2. Using GnuPG with files
10.3.3. Using GnuPG with Mutt
10.3.4. Using GnuPG with Vim
10.3.5. The MD5 sum
10.4. Source code merge tools
10.4.1. Extract differences for source files
10.4.2. Merge updates for source files
10.4.3. 3 way merge updates
10.5. Version control systems
10.5.1. Native VCS commands
10.5.2. CVS
10.5.2.1. Installing a CVS server
10.5.2.2. Use local CVS server
10.5.2.3. Use remote CVS pserver
10.5.2.4. Anonymous CVS (download only)
10.5.2.5. Use remote CVS through ssh
10.5.2.6. Create a new CVS archive
10.5.2.7. Work with CVS
10.5.2.8. Export files from CVS
10.5.2.9. Administer CVS
10.5.2.10. File permissions in repository
10.5.2.11. Execution bit
10.5.3. Subversion
10.5.3.1. Installing a Subversion server
10.5.3.2. Setting up a repository
10.5.3.3. Configuring Apache2
10.5.3.4. Subversion usage examples
10.5.3.5. Create a new Subversion archive
10.5.3.6. Working with Subversion
10.5.4. Git
10.5.4.1. Before using Git
10.5.4.2. Gitリファレンス
10.5.4.3. Git commands
10.5.4.4. Git for recording configuration history
11. データ変換
11.1. Text data conversion tools
11.1.1. To convert a text file with iconv
11.1.2. To convert file names with iconv
11.1.3. EOL conversion
11.1.4. TAB conversion
11.1.5. Editors with auto-conversion
11.1.6. Plain text extraction
11.1.7. Highlighting and formatting plain text data
11.2. XML data
11.2.1. Basic hints for XML
11.2.2. XML processing
11.2.3. The XML data extraction
11.3. Printable data
11.3.1. Ghostscript
11.3.2. Merge two PS or PDF files
11.3.3. Printable data utilities
11.3.4. Printing with CUPS
11.4. Type setting
11.4.1. roff typesetting
11.4.2. TeX/LaTeX
11.4.3. Pretty print a manual page
11.4.4. Creating a manual page
11.5. The mail data conversion
11.5.1. Mail data basics
11.6. Graphic data tools
11.7. Miscellaneous data conversion
12. Programming
12.1. シェルスクリプト
12.1.1. POSIX shell compatibility
12.1.2. シェル変数
12.1.3. Shell conditionals
12.1.4. シェルループ
12.1.5. The shell command-line processing sequence
12.1.6. Utility programs for shell script
12.1.7. Shell script dialog
12.1.8. Shell script example with zenity
12.2. Make
12.3. C
12.3.1. Simple C program (gcc)
12.3.2. Debugging with gdb
12.3.2.1. 基本的なgdb実行
12.3.2.2. Debianパッケージのデバグ
12.3.2.3. Obtaining backtrace
12.3.2.4. Advanced gdb commands
12.3.2.5. Debugging X Errors
12.3.3. ライブラリーへの依存の確認
12.3.4. Debugging with memory leak detection tools
12.3.5. Disassemble binary
12.3.6. Flex — a better Lex
12.3.7. Bison — a better Yacc
12.4. Autoconf
12.4.1. Compile and install a program
12.4.2. Uninstall program
12.5. Perl short script madness
12.6. Web
12.7. Static code analysis tools
12.8. ソースコード変換
12.9. Debianパッケージ作成
A. 補遺
A.1. Debian迷路
A.2. 著作権の経緯
A.3. 文書のフォーマット

表目次

1.1. 興味あるテキストモードのプログラムパッケージのリスト。
1.2. 有用な文書パッケージのリスト。
1.3. 重要ディレクトリの使い方のリスト。
1.4. "ls -l"の出力の最初の文字のリスト
1.5. chmod(1)コマンドで用いられるファイルパーミッションの数字モード。
1.6. umask値の例。
1.7. ファイルアクセスのためにシステムが供給する特記すべきグループのリスト。
1.8. 特定コマンド実行のためにシステムが供給する特記すべきグループのリスト。
1.9. タイムスタンプのタイプのリスト。
1.10. デバイスのタイプ
1.11. スペシャルなデバイスファイルのリスト。
1.12. MCのキーバインディング
1.13. キー入力へのMCの反応
1.14. シェルプログラムのリスト。
1.15. Bashのキーバインディングのリスト。
1.16. Unix流のマウス操作のリスト
1.17. 基本のUnixコマンドのリスト。
1.18. ロケールの値の3つの部分
1.19. 推奨ロケールのリスト。
1.20. "$HOME"の値のリスト。
1.21. シェルグロブパターン
1.22. コマンドの終了コード。
1.23. シェルコマンドの慣用句。
1.24. 事前定義されたファイルデスクリプタ
1.25. BREとEREのメタ文字。
1.26. 置換表現
1.27. コマンドをパイプするためのスクリプト断片のリスト。
2.1. Debianのパッケージ管理ツールのリスト。
2.2. Debianアーカイブサイトのリスト。
2.3. Debianアーカイブコンポーネントのリスト。
2.4. スイーツとコード名の関係。
2.5. パッケージ依存関係のリスト。
2.6. 特定パッケージの問題解決のためのキーとなるウエッブサイトのリスト。
2.7. aptitudeapt-get /apt-cacheを使うコマンドラインによるパッケージ管理操作
2.8. aptitude(8)に関する特記すべきコマンドオプション。
2.9. aptitudeのキーバインディングのリスト。
2.10. aptitudeの表示のリスト。
2.11. 標準パッケージ画面の分類。
2.12. aptitudeのregex式のリスト。
2.13. パッケージアクティビティーのログファイル
2.14. 高度なパッケージ管理操作のリスト
2.15. Debianアーカイブのメタデータの内容。
2.16. Debianパッケージの名前の構造。
2.17. Debianパッケージ名の各部分に使用可能な文字。
2.18. dpkgに関する特記すべきファイル。
2.19. 各パッケージソースタイプ毎のデフォルトPin-Priority値のリスト
2.20. Debianアーカイブ専用のプロキシツールのリスト
3.1. ブートローダのリスト
3.2. GRUBパラメータの意味。
3.3. runlevelsとその意味のリスト。
3.4. カーネルエラーレベルのリスト
4.1. 3つのpam_unix(8)に関する重要なコンフィギュレーションファイル。
4.2. "/etc/passwd"の2番目のエントリーの内容。
4.3. アカウント情報管理のためのコマンドリスト。
4.4. パスワード生成ツールのリスト。
4.5. 注目すべきPAMとNSSシステムのリスト。
4.6. PAMがアクセスするコンフィギュレーションファイルのリスト。
4.7. インセキュアとセキュアな、サービスやポートのリスト
4.8. セキュリティ強化策のためのツール表
5.1. ネットワークアドレス範囲のリスト
5.2. ネットワーク設定ツールのリスト。
5.3. 典型的なネットワーク接続方法と接続経路のリスト。
5.4. ネットワーク接続設定のリスト。
5.5. ネットワーク接続の省略語のリスト。
5.6. pppconfigを使ってのPPP接続のための設定ファイルのリスト。
5.7. wvdialconfでPPP接続する際の設定ファイルリスト。
5.8. pppoeconfを用いてPPPoE接続する際の設定ファイルのリスト。
5.9. ifupdownを使う基本的なネットワーク設定コマンドのリスト。
5.10. "/etc/network/interfaces"のスタンザのリスト
5.11. WLANの略語のリスト。
5.12. ネットワークデバイスの用語法のリスト。
5.13. ifupdownを使う上級ネットワーク設定コマンドのリスト。
5.14. ifupdownシステムが引き渡す環境変数のリスト。
5.15. 型遅れとなったnet-toolsコマンドと新しいiproute2コマンド等との翻訳表。
5.16. 低レベルネットワークコマンドのリスト。
5.17. ネットワーク最適化ツールのリスト。
5.18. 最適MTU値の基本的なガイドライン
5.19. ファイアーウォールツールのリスト。
6.1. ウェッブブラウザのリスト。
6.2. ブラウザプラグインのリスト。
6.3. List of popular mail system for workstation.
6.4. List of important postfix manual pages
6.5. List of mail address related configuration files.
6.6. List of basic MTA operation.
6.7. List of MTA.
6.8. List of MUA.
6.9. List of remote mail retrieval and forward utilities.
6.10. フィルタ付きのMDAのリスト。
6.11. List of POP3/IMAP4 servers.
6.12. プリントサーバーとユーティリティのリスト。
6.13. リモートアクセスサーバーとユーティリティのリスト
6.14. List of SSH authentication protocols and methods.
6.15. SSH設定ファイルのリスト。
6.16. List of SSH client startup examples.
6.17. List of free SSH clients for other platforms.
6.18. List of other network application servers.
6.19. ネットワークアプリケーションのリスト。
6.20. List of popular RFCs.
7.1. List of key (meta)packages for X window.
7.2. List of server/client terminology.
7.3. List of connection methods to the X server.
7.4. Table of packages to support X window font systems.
7.5. Table of corresponding PostScript Type 1 fonts.
7.6. Table of corresponding TrueType fonts.
7.7. Table of key words used in CJK font names to indicate font types.
7.8. List of basic X office applications
7.9. List of basic X utility applications
8.1. List of keyboard reconfiguration methods.
8.2. List of input method supports with scim.
9.1. List of programs to support interrupted network connections.
9.2. screenキーバインディングのリスト。
9.3. List of system log analyzers.
9.4. Display examples of time and date for the "ls -l" command for lenny.
9.5. グラフィックイメージの操作ツールのリスト。
9.6. List of packages to record configuration history in VCS.
9.7. ディスクパーティション管理パッケージのリスト
9.8. List of filesystem management packages
9.9. List of data encryption utilities.
9.10. List of tools for monitoring and controlling program activities
9.11. List of nice values for the scheduling priority.
9.12. List of ps command styles.
9.13. topのコマンドのリスト。
9.14. List of frequently used signals for kill command.
9.15. List of SAK command keys.
9.16. List of hardware identification tools.
9.17. List of hardware configuration tools.
9.18. サウンドパッケージのリスト。
9.19. List of commands for disabling the screen saver.
9.20. List of memory sizes reported.
9.21. システムセキュリティや整合性確認のためのツールリスト
9.22. Debianシステム上でカーネルの再コンパイルためにインストールする重要パッケージのリスト
9.23. List of virtualization tools
10.1. アーカイブと圧縮のツールのリスト。
10.2. List of copy and synchronization tools.
10.3. バックアップスイートのユーティリティのリスト。
10.4. List of packages which permit normal users to mount removable devices without a matching "/etc/fstab" entry.
10.5. List of filesystem choices for removable storage devices with typical usage scenarios.
10.6. List of the network service to chose with the typical usage scenario.
10.7. バイナリデータを閲覧や編集するパッケージのリスト。
10.8. List of packages to manipulate files without mounting.
10.9. データファイルの回復と事故の証拠解析のリスト。
10.10. データセキュリティインフラツールのリスト。
10.11. List of GNU Privacy Guard commands for the key management
10.12. 信頼性コードの意味のリスト。
10.13. List of gnu privacy guard commands on files
10.14. ソースコードマージツールのリスト。
10.15. List of version control system tools.
10.16. Comparison of native VCS commands.
10.17. Assumption for the CVS archive.
10.18. Notable options for CVS commands (use as first argument(s) to cvs(1)).
10.19. gitパッケージとコマンドのリスト。
11.1. テキストデータ変換ツールのリスト。
11.2. List of encoding values and their usage.
11.3. List of EOL conversion tools.
11.4. List of TAB conversion commands from bsdmainutils and coreutils packages.
11.5. 平文テキストデータ抽出ツールのリスト。
11.6. 平文テキストデータをハイライトするツールのリスト。
11.7. XMLで事前定義されているエントリーのリスト。
11.8. List of XML tools.
11.9. List of DSSL tools.
11.10. List of XML data extraction tools.
11.11. List of XML pretty print tools.
11.12. List of Ghostscript PostScript interpreters.
11.13. プリントできるデータのユーティリティのリスト。
11.14. List of type setting tools.
11.15. マンページ作成を補助するパッケージのリスト。
11.16. メールデータ変換を補助するパッケージのリスト。
11.17. グラフィックデータツールのリスト。
11.18. List of miscellaneous data conversion tools.
12.1. プログラムをすることを補助するパッケージのリスト。
12.2. List of typical bashisms.
12.3. シェル変数のリスト。
12.4. List of shell parameter expansions.
12.5. List of key shell parameter substitutions.
12.6. List of file comparison operators in the conditional expression.
12.7. List of string comparison operators in the conditional expression.
12.8. List of user interface programs.
12.9. makeの自動変数のリスト。
12.10. make変数の展開のリスト。
12.11. 上級のgdbコマンドのリスト
12.12. List of memory leak detection tools
12.13. List of Yacc-compatible LALR parser generators
12.14. 静的コード分析ツールのリスト。
12.15. ソースコードの変換ツールのリスト。

序章

このDebianリファレンス(第2版)(2009-06-26 15:13:16 UTC)はシステムインストール後のユーザ向け案内書としてDebianのシステム管理に関する概論の提供を目指しています。

本書が対象とする読者は、GNU/Linuxシステムがどう機能するかを理解するのに、シェルスクリプトぐらいは学ぶ気はあるが、全てのCのソースまで読む気がない人です。

1. 免責事項

一切保証は致しません。全ての商標はそれぞれの商標の所有者の財産です。

Debianシステム自体は動く標的です。このため最新状況を反映した正確な記述は困難です。現行の不安定版のDebianシステムを用いて本書は記していますが、皆様が読まれる時点ではすでに記載内容が古くなっているでしょう。

本書はあくまで二次的参考文献として扱ってください。本書は正式の案内書を置き換えません。著者及び本書への貢献者は本書中の誤謬や欠落や曖昧さが引き起こす結果に一切責任を負いません。

2. Debianとはなにか

Debianプロジェクトはフリーなオペレーティングシステムを作ろうという共通目的を持った個人の集団です。そのディストリビューションは次の特徴があります:

  • ソフトウェアの自由へのコミットメント: Debian社会契約とDebianフリーソフトウエアガイドライン(DFSG)
  • インターネット上の分散型の無償ボランティア活動: http://www.debian.org
  • 多数のプリコンパイルされた高品質のソフトウエア。
  • セキュリティアップデートへの平易なアクセス提供による、安定性とセキュリティの重視。
  • 不安定版unstableやテスト版testingアーカイブによる、最新のソフトウエアへの円滑なアップグレードの重視。
  • 多数のサポートされたハードウエアーアーキテクチャー。

Debianの中のフリーソフトウエア構成要素は、GNULinuxBSDXISCApacheGhostscriptCommon Unix Printing System SambaGNOMEKDEMozillaOpenOffice.orgVimTeXLaTeXDocBookPerlPythonTclJavaRubyPHPBerkeley DBMySQLPostgreSQLEximPostfixMuttFreeBSDOpenBSDPlan 9やその他の多くの独立のフリーソフトウエアのプロジェクトに由来します。Debianはこの多種多様なフリーソフトウエアを1つのシステムにまとめ上げます。

3. 本書について

3.1. 編集指針

本書の作成にあたり次の編集指針を守りました:

  • 他に良い文書があれば(著者裁量で)詳述しません
  • 概論を提供し枝葉末節は省略します(全体像)
  • 簡潔を心がけました(KISS)
  • 非GUIツールとコンソールを重視します。(シェル例示を使用)
  • 車輪の再発明をしません。(既存の参考文献へのポインターの利用)
  • 客観的であるようにしまう。(popcon等の利用)

私はシステムの階層的側面やシステムの低レベルを明らかにしようとしました。

3.2. 前提条件

読者はサポート情報を次より自ら取得して下さい(重要性の高いものからの順に列挙):

  • 一般的情報はhttp://www.debian.orgにあるDebianサイト。
  • "/usr/share/doc/<package_name>"ディレクトリ下にある文書。
  • Unixスタイルのmanページ: "dpkg -L <package_name> |grep '/man/man.*/'"。
  • GNUスタイルのinfoページ: "dpkg -L <package_name> |grep '/info/'"。
  • バグレポート: http://bugs.debian.org/<package_name>
  • 変化中の事や特定案件に関しては、http://wiki.debian.org/にあるDebianのWiki。
  • http://tldp.org/ にあるLinux文書プロジェクト(TLDP)のHOWTO文書。
  • http://www.unix.org/にあるOpen GroupのThe UNIX System Home PageにあるSingle UNIX Specification、
  • http://wikipedia.org/にあるWikipediaのフリーの百科事典。
[注意] 注意

詳細な文書を読むには、"-doc"をサフィックスとする対応する文書パッケージをインストールする必要があるかもしれません。

3.3. 文書様式

次のような、bash(1)シェルコマンド例示と点の後ろの箇条書き形式で本書は書かれています。

# <rootアカウントからのコマンド>
$ <ユーザアカウントからのコマンド>
  • <なすべき事の叙述>

これらのシェルプロンプトは使われるアカウントを区別します。これはちょうど環境変数として: "PS1='\$'"と"PS2=' '"を設定した場合に相当します。これらの環境変数値はあくまで本書の読みやすさのためで、実際のインストール済みシステではほとんど見かけません。

[注意] 注意

"PS1='\$'"と"PS2=' '"という環境変数値の意味はbash(1)を参照下さい。

本文中に引用されるコマンドの断片はダブルクォーテションマーク間にタイプライタフォントで書き"aptitude safe-upgrade"のように表現されます。

本文中に設定ファイルから引用された文字データはダブルクォーテションマーク間にタイプライタフォントで書き"deb-src"のように表現されます。

コマンドはその名前をタイプライタフォントで書き、場合によってはその後ろにmanページのセクション番号を括弧中に入れて書きbash(1)のように表現されます。読者は次の様にタイプして情報を得るように心がけてください。

$ man 1 bash

manページはその名前をタイプライタフォントで書き、その後ろにmanページのセクション番号を括弧中に入れて書きsources.list(5)のように表現されます。読者は次の様にタイプして情報を得るように心がけてください。

$ man 5 sources.list

infoページはダブルクォーテションマーク間にタイプライタフォントというコマンドの断片形式で書き"info make"のように表現されます。読者は次の様にタイプして情報を得るように心がけてください。

$ info make

ファイル名はダブルクォーテションマーク間にタイプライタフォントで書き"/etc/passwd"のように表現されます。読者は次の様にタイプして情報を得るように心がけてください。

$ sensible-pager "/etc/passwd"

ディレクトリ名はダブルクォーテションマーク間にタイプライタフォントで書き"/etc/init.d/"のように表現されます。読者は次の様にタイプして情報を得るように心がけてください。

$ mc "/etc/init.d/"

パッケージ名はその名をタイプライタフォントで書き"vim"のように表現されます。読者は次の様にタイプして情報を得るように心がけてください。

$ dpkg -L vim
$ apt-cache show vim
$ aptitude show vim

文書は、その場所のファイル名でダブルクォーテションマーク間にタイプライタフォントで書き"/usr/share/doc/sysv-rc/README.runlevels.gz"や"/usr/share/doc/base-passwd/users-and-groups.html"のように表現されたり、その場所のURLhttp://www.debian.orgのように表現されます。読者は次の様にタイプして情報を得るように心がけてください。

$ zcat "/usr/share/doc/sysv-rc/README.runlevels.gz" | sensible-pager
$ sensible-browser "/usr/share/doc/base-passwd/users-and-groups.html"
$ sensible-browse "http://www.debian.org"

環境変数は、頭に"$"がついた名前をダブルクォーテションマーク間にタイプライタフォントで書き、"$TERM"のように表現されます。読者は次の様にタイプして情報を得るように心がけてください。

$ echo "$TERM"

3.4. Popcon

Popconのデータは各パッケージの客観的人気の指標として提示されいます。それがダウンロードされた日付は2009-06-21 15:05:53 UTCで、 96434を越すバイナリパッケージ数と19のアーキテクチャーにまたがる84969つの提出レポートからなります。

[注意] 注意

amd64の不安定版unstableアーカイブは現在高々25441つのパッケージしか含みません。Popconデータは多くの古い設置システムからのレポートを含みます。

"votes"を意味する"V:"が前についたPopconの数は"100 * (PCで最近実行されたパッケージに関するpopcon提出)/(全popcon提出)"として計算される。

"installs"を意味する"I:"が前についたPopconの数は"100 * (PCにインストールされているパッケージに関するpopcon提出)/(全popcon提出)"として計算される。

[注意] 注意

Popconの数字はパッケージの重要性の絶対指標と考えるべきでない。統計を曲げる多くの因子があります。例えば、Popconに参加しているシステムの一部は"/bin"などのディレクトリをシステム性能向上のために"noatime"オプションでマウントすることで当該システムから"vote"することを実質的に禁止しているかもしれません。

3.5. パッケージサイズ

各パッケージの客観的指標としてパッケージサイズデータも提供されます。それは"apt-cache show"や"aptitude show"コマンドが(現在のamd64アーキテクチャー上のunstableリリース上で)表示する"Installed-Size:"です。サイズはKiB(Kibibyte = 1024バイト単位)で表示されます。

[注意] 注意

小さなパッケージサイズのパッケージはunstableリリース中の当該パッケージが内容のある他パッケージを依存関係でインストールするためのダミーパッケージだからかもしれません。

3.6. バグ報告

何か問題を発見した場合には、debian-referenceパッケージに対してreportbug(1)を用いてバグ報告をしてください。プレーンテキストバージョンかソースに対する"diff -u"による修正提案を含めてください。

4. 新規ユーザへの引用文

新規ユーザを啓蒙するDebianのメーリングリストで見つけた興味深い引用文を記します:

  • "This is Unix. It gives you enough rope to hang yourself." 「これはUnixです。首を括るのに十分なロープをあてがってくれますよ。」 --- Miquel van Smoorenburg <miquels at cistron.nl>
  • "Unix IS user friendly... It's just selective about who its friends are." 「Unixはユーザフレンドリーです... 誰にフレンドリーにするかに人見知りするだけです。」 --- Tollef Fog Heen <tollef at add.no>

第1章 GNU/Linuxチュートリアル

コンピュータシステムを学ぶことは新しい外国語を学ぶことに似ていると考えます。チュートリアルブックは有用ですが、実際に自ら使って学ぶことが必要です。円滑なスタートが出きるように、いくつかの基本的なポイントを説明します。

Debian GNU/Linux の強力なデザインは マルチユーザマルチタスク という Unix オペレーティングシステムに由来します。これら Unix と GNU/Linux の特徴や類似点の強力さを活用することを覚えましょう。

Unix対象の文書を避けたり、GNU/Linuxに関する文書だけに頼ることは、有用な情報を見逃すことになるので止めましょう。

一般的なシステム管理に関する良好なオンラインリソースは、Debianのnon-freeアーカイブにrutebookパッケージ (popcon: I:0.2)としてある"Ruteユーザのためのチュートリアルと解説書(Rute User's Tutorial and Exposition)" が提供しています。

[注意] 注意

Unix 的システムをコマンドラインツールで少々使った経験があれば、私がここで説明することはすべてご存知でしょう。リアリティーチェックと記憶を呼び戻すのにこれを使ってください。

1.1. コンソールの基礎

1.1.1. シェルプロンプト

X Windowシステムgdm等のディスプレイマネージャとともにインストールした場合以外には、システム起動の際に文字のloginスクリーンが現れます。あなたのホスト名がfooと仮定すると、loginプロンプトは次です:

foo login:

GNOMEKDEのようなGUI環境をインストールした場合には、Ctrl-Alt-F1とすることでloginプロンプトが出て、Alt-F7とすることでGUI環境に戻れます(詳細は下記の「仮想コンソール」参照)。

loginプロンプトであなたのユーザ名(例えばpenguin)を打鍵しEnterキーを押します。さらにあなたのパスワードを打鍵しEnterキーを再び押します。

[注意] 注意

Unixの伝統に従い、Debianシステムではユーザ名とパスワードに関して大文字小文字の区別をします。ユーザ名は通常小文字のみから選ばれます。最初のユーザアカウントは通常インストールの際に作られます。追加のユーザアカウントはrootによってadduser(8)を用いて作られます。

"/etc/motd" (本日のメッセージ:Message Of The Day)に保存されている歓迎メッセージとコマンドプロンプトで次のように表示しシステムが起動されます。

Debian GNU/Linux lenny/sid foo tty1
foo login: penguin
Password:
Last login: Sun Apr 22 09:29:34 2007 on tty1
Linux snoopy 2.6.20-1-amd64 #1 SMP Sun Apr 15 20:25:49 UTC 2007 x86_64

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
foo:~$

ここで、歓迎メッセージの主要部分は"/etc/motd.tail"ファイルを編集することでカスタマイズできます。最初の行は"uname -snrvm"用いたシステム情報から生成されます。

これであなたはシェルの中にいます。シェルはあなたからのコマンドを解釈します。

1.1.2. Xの下でのシェルプロンプト

インストールの際に"Desktop environment"タスクを選定しGNOMEgdmとともにX Windowシステムをインストールした場合には、システムの起動するとグラフィカルなloginプロンプトのスクリーンが表示されます。あなたのユーザ名とパスワードを入力することで非特権ユーザアカウントにloginできます。タブ(tab)を用いたりマウスの第一クリックを用いるとユーザ名とパスワードの間を行き来できます。

gnome-terminal(1)やrxvt(1)やxterm(1)のようなx-terminal-emulatorプログラムをXの下で起動するとシェルプロンプトが得られます。GNOMEデスクトップ環境下では、"Applications" → "Accessories" → "Terminal"とクリックしてもうまくいきます。

次の「仮想コンソール」も参照ください.

デスクトップ環境(例えばfluxbox)次第ではメニューの起点がよく分からないことがあります。そんな時はスクリーンの中央を(右)クリックしてメニューが表示されることを期待しましょう。

1.1.3. rootアカウント

rootアカウントはスーパーユーザとか特権ユーザとも呼ばれます。このアカウントからは次のようなシステム管理活動ができます:

  • ファイルのパーミッションによらずシステム上の任意ファイルに関しての、読み・書き・削除
  • システム上のいかなるファイルに関して、ファイルの所有者やパーミッション設定
  • システム上の非特権ユーザのパスワードを設定
  • パスワード無しに任意アカウントへのlogin

rootアカウントの権限を使うには、この無制限の権限ゆえ配慮と責任ある行動が求められます。

[警告] 警告

rootのパスワードを他人に決して教えてはいけない。

[注意] 注意

ファイル(Debianシステムにとってはファイルの一種であるCD-ROM等のハードウエアデバイスも含む)のパーミッションは、非rootユーザによるそのファイルの使用やアクセスをできなくなくすることがあります。この様な状況の下ではrootアカウントを使うことが簡便なテスト法ですが、問題解決はファイルのパーミッションとユーザのグループのメンバーシップを適切に設定する必要があります(「ファイルシステムのパーミッション」参照)。

1.1.4. rootシェルプロンプト

rootのパスワードを使ってrootのシェルプロンプトを使えるようにする基本的な方法を次に記します。

  • 文字ベースのloginプロンプトで、単にrootと入力します。
  • GNOMEデスクトップ環境下で、"Applications" → "Accessories" → "Root Terminal"とクリックします。
  • 何らかのユーザのシェルプロンプトから、"su -l"と入力します。(現ユーザの環境を一切引き継がない。)
  • 何らかのユーザのシェルプロンプトから、"su"と入力します。(現ユーザの環境をある程度引き継ぐ。)

1.1.5. GUIのシステム管理ツール

デスクトップのメニューがGUIのシステム管理ツールを適切な権限とともに自動的に起動しない場合、gnome-terminal(1)やrxvt(1)やxterm(1)のようなXターミナルエミュレータのrootシェルプロンプトから起動できます。

[警告] 警告

gdm(1)等のディスプレイマネージャのプロンプトにrootと入力して、Xディスプレイ/セッションマネージャをrootアカウントのもとで決して起動してはいけません。

[警告] 警告

クリチカルな情報が表示されている際には、あなたのXスクリーンを覗き見られるかもしれないのでリモートの信頼できないGUIプログラムを決して実行してはいけません。

1.1.6. 仮想コンソール

デフォルトのDebianシステムでは、6つの切り替え可能なVT100様の文字コンソールがあり、Linuxホスト上で直接コマンドシェルを起動できるようになっています。GUI環境下でない場合は、Left-Alt-keyF1F6の中の一つのキーを同時に押すことで仮想コンソール間の切り替えができます。仮想ターミナルそれぞれに独立したアカウントでログインすることができ、。マルチユーザ環境を提供します。このマルチユーザ環境はUnixの偉大な機能で、癖になります。

X Windowシステムの下では、Ctrl-Alt-F1キーを押す、つまりleft-Ctrl-keyleft-Alt-keyF1-keyキーを同時に押すと文字コンソール1にアクセスできます。通常仮想コンソール7で実行されているX WindowシステムへはAlt-F7を押すことにより戻れます。

これとは別の方法もあります。今と違う仮想ターミナルへ、例えば仮想ターミナル1への変更は次でできます:

# chvt 1

1.1.7. コマンドプロンプトからの退出方法

コマンドプロンプトでCtrl-D、つまりleft-Ctrl-keyd-keyの同時押しをするとシェルでのアクティビティーを終了できます。文字コンソールの場合は、こうするとloginプロンプト戻ります。これらのコントロール文字は通常"control D"と大文字を使って表記されますが、Shiftキーを押す必要はありません。またCtrl-Dに関する簡略表記^Dも使われます。この代わりに"exit"とタイプすることができます。

x-terminal-emulator(1)にあっては、このようにすることでx-terminal-emulator のウインドーが閉じることができます。

1.1.8. シャットダウンの方法

ファイル操作の際にパーフォーマンス向上のためにメモリへのデータのキャッシュがされる他の現代的なOSと同様に、Debianシステムでも電源を安全に切る前に適切なシャットダウン手順を取る必要があります。これはすべてのメモリ上の変更を強制的にディスクに書き出しすことで、ファイルの完全性を維持するためです。ソフトウエアによる電源コントロールができる場合、シャットダウン手続きはシステムの電源を自動的に落とします。(これがうまくいかない時には、シャットダウン手続きの後で数秒間電源ボタンを押す必要があるかもしれません。)

通常のマルチユーザモード下では、rootコマンドプロンプトから次によってシステムのシャットダウンをします:

# shutdown -h now

シングルユーザモード下では、rootコマンドプロンプトから次によってシステムのシャットダウンをします:

# poweroff -i -f

この他に、"/etc/inittab"に"ca:12345:ctrlaltdel:/sbin/shutdown -t1 -a -h now"と書かれていれば、Ctrl-Alt-Delete(left-Ctrl-keyleft-Alt-KeyDeleteの同時押し)を入力するシャットダウン方法もあります。

1.1.9. まともなコンソールの回復

例えば"cat <some-binary-file>"のような変な事をした後でスクリーンが無茶苦茶になった場合、コマンドプロンプトに"reset"と入力してください。このときコマンドを入力してもスクリーンには読み取れる表示がされないかもしれません。"clear"とすればスクリーンが消去できます。

1.1.10. 初心者向け追加パッケージの提案

デスクトップ環境タスク抜きの最小限インストレーションDebianシステムですら基本的なUnix機能は提供されますが、コマンドラインやcursesに基づくmcvim等のいくつかの文字ターミナルパッケージをaptitude(8)を使って追加インストールすることを初心者の最初の一歩としてお薦めします。

# aptitude update
...
# aptitude install mc vim sudo
...

既にこれらのパッケージがインストールされている場合には何もインストールされません。

表1.1 興味あるテキストモードのプログラムパッケージのリスト。

パッケージ popcon サイズ 説明
mc V:12, I:27 6364 テキストモードの全画面ファイルマネージャ
sudo V:44, I:74 592 ユーザに限定的なroot権限を与えるプログラム
vim V:14, I:30 1740 UnixテキストエディタVi IMproved(改良版Vi)、プログラマーのためのテキストエディタ(標準版)
vim-tiny V:18, I:90 828 UnixテキストエディタVi IMproved(改良版Vi)、プログラマーのためのテキストエディタ(軽量版)
emacs21 V:3, I:7 8176 GNUプロジェクトEmacs、Lispに基づく拡張可能なテキストエディタ(21版)
emacs22 V:4, I:7 11032 GNUプロジェクトEmacs、Lispに基づく拡張可能なテキストエディタ(22版)
w3m V:23, I:85 1968 テキストモードWWWブラウザ
gpm V:3, I:5 564 テキストコンソール上のUnix式のカットアンドペースト(daemon)

いくつかの参考資料を読むのも良いことです。

表1.2 有用な文書パッケージのリスト。

パッケージ popcon サイズ 説明
doc-debian I:83 376 Debianプロジェクトの文書、(Debian FAQ)他
debian-policy I:2 2740 Debianポリシーマニュアルと関連文書
developers-reference I:1.2 1348 Debian開発者のためのガイドラインと情報
maint-guide I:0.9 644 Debian新メンテナ向けガイド
debian-history I:0.4 2544 Debianプロジェクトの歴史
debian-faq I:45 1190 Debian FAQ(よくある質問集)
doc-linux-text I:83 8616 Linux HOWTOとFAQ(テキスト版)
doc-linux-html I:1.0 62564 Linux HOWTOとFAQ(HTML版)
sysadmin-guide I:0.3 964 Linuxシステム管理者ガイド
rutebook I:0.2 8264 Linux: Ruteユーザのためのチュートリアルと解説書(non-free)

これらのパッケージはrootのシェルプロンプトから次のコマンドを発行すればインストールできます。

# aptitude install package_name

1.1.11. 追加のユーザアカウント

次の練習のためにあなたのメインのユーザアカウントを使いたくない場合には、例えばfishという追加のユーザアカウントを作成できます。rootシェルプロンプトで次のように入力します。

# adduser fish
  • すべての質問に返事をする

こうすることでfishという名前の新しいアカウントが作られます。練習の後で、このユーザとそのホームディレクトリは次のようのすれば削除できます:

# deluser --remove-home fish

1.1.12. sudoの設定

ラップトップPC上のデスクトップのDebianシステム等のような典型的単一ユーザワークステーションでは次のような単純なsudo(8)の設定をして、非特権ユーザ(例えばpenguin)に管理者権限を(rootパスワードではなく)ユーザ自身のパスワードで与えることがよくあります。

# echo "penguin  ALL=(ALL) ALL" >> /etc/sudoers

このトリックの使用は、単一ユーザワークステーション上であなた自身が管理者でユーザである際のみに限るべきです。

[警告] 警告

システムセキュリティ上非常に悪い事態を招くので、マルチユーザワークステーション上の通常ユーザアカウントに対してこの様な設定をしてはいけません。

[注意] 注意

上記例のようなpenguinのパスワードとアカウントはrootパスワードやrootアカウント同様の保護が必要です。

[注意] 注意

この文脈上の管理者権限はワークステーションに関するシステム管理業務をする権限を与えられた人に属します。そのような権限と能力を持っていなければ、あなたの会社の管理部門の管理職や上司とはいえこのような権限を与えてはいけません。

[注意] 注意

特定デバイスや特定ファイルへのアクセスの権限を与えるには、sudo(8)をつかって得たroot権限を用いるのではなく、groupを使って限定的アクセス与えることを考えるべきです。

[注意] 注意

sudo(8)を使ってもう少し工夫された注意深い設定をすれば、共有システム上の他のユーザにrootパスワードを教えること無く限定的管理権限を許可することができます。こうすることは、誰が何をしたかを明らかにするので、複数の管理者がいるホストにおける責任の所在を明らかにします。ただ、誰にもそんな権限を与えたく無いかもしれません。

1.1.13. お遊びの時間

非特権ユーザアカウントを使う限り全くリスク無くDebianシステムでお遊びをする準備万端です。

何故なら、たとえデフォルトのインストール後ですらDebianシステムは非特権ユーザがシステムに損害を与えられないように的確なファイルパーミッションが設定されているからです。もちろん悪用可能な穴が残っているかもしれませんが、こんな問題まで心配する人はこのセクションを読んでいるべきではなく、Securing Debian Manualを読むべきです。

DebianシステムをUnix的システムとして以下で学びましょう:

1.2. Unix-likeファイルシステム

GNU/Linuxや他のUnix的オペレーティングシステムでは、ファイルディレクトリに整理されています。すべてのファイルやディレクトリは、"/"を根(root)に持つ一本の大きな木(ツリー)のようにアレンジされています。

この様なファイルやディレクトリはいくつかのデバイスに展開することができます。あるデバイス上にあるファイルシステムを大きなファイルツリーにマウントするのにmount(8)が使われます。その逆に、それを切り離すのにumount(8)が使われます。最近のLinuxカーネルでは、mount(8)をオプションとともに用いると、ファイルツリーの一部を別のところと結びつけたり、共有・非共有・従属・バインド不可としてファイルシステムをマウントもできます。各ファイルシステムごとの使用可能なマウントオプションは"/share/doc/linux-doc-2.6.*/Documentation/filesystems/"にあります。

Unixシステム上のディレクトリは、一部の他システム上ではフォルダと呼ばれます。Unixシステム上では"A:"のようなドライブというコンセプトが無いこと覚えておいてください。単一のファイルシステムがあって、そこにすべてが含まれています。これはWindowsと比べた際の大きな利点です。

1.2.1. Unixファイルの基礎

Unixファイルの基礎は以下です:

  • ファイル名は大文字と小文字を区別します。"MYFILE"と"MyFile"は異なるファイルです。
  • rootディレクトリはフィルシステムの根(root)を意味して、単に"/"と記載されます。これをrootユーザのhomeディレクトリ"/root"とは混同しないでください。
  • 全てのディレクトリには"/"以外の文字・記号からなる名前がついています。rootディレクトリは例外で、その名前は"/"("スラッシュ"とか"rootディレクトリ"と読まれます)でその名前を変えることはできません。
  • 各ファイルやディレクトリは、たどっていくとファイルに到達するディレクトリの列が示される、完全に記述したファイル名とか絶対ファイル名とかパスにより指定されます。これらの3つの表現は同義語です。
  • 全ての完全に記述したファイル名は"/"ディレクトリで始まり、ファイル名中の各ディレクトリやファイル名の間には"/"がはさまります。最初の"/"は ディレクトリ名です。その他の"/"は、次のサブディレクトリとの区別をします。そして最後には実際のファイルの名前がきます。ちょっと混乱しそうですので、次の完全に記述したファイル名 の例をご覧ください: "/usr/share/keytables/us.map.gz"。 一方このベース名である、"us.map.gz"だけをファイル名と呼ぶ人もあります。
  • root ファイルシステムは"/etc/"や"/usr/"のような複数の枝を持ちます。これらのサブディレクトリもまた"/etc/init.d/"や"/usr/local/"のように、さらにサブディレクトリに枝別れします。これらの全体をまとめてディレクトリツリーと呼びます。絶対ファイル名はツリーの根元("/")から枝の先 (ファイル) までの経路として考えることもできます。また、あたかもディレクトリツリーを家系図のように人が話すのを聞いたことがあるでしょう。あたかもそれぞれのサブディレクトリにがあるとし、パスはファイルの完全な祖先の系図のように表現します。root ディレクトリではない他の場所から始まる相対パスもあります。ディレクトリ"../"は親ディレクトリを参照していることを覚えておきましょう。このような呼び方はディレクトリのような構造を持つ他の階層的ツリー状のデータ構造体でもよく使われます。
  • ハードディスクのような物理デバイスに対応したパス名の要素は存在しません。ここが、パス名に"C:\"のようなデバイス名が含まれるRT-11CP/MOpenVMSMS-DOSAmigaOSMicrosoft Windowsと違う点です。(但し、通常のファイルシステム中に物理デバイスを示すディレクトリ項目はあります。「ファイルシステムの内側」参照。)
[注意] 注意

ほとんど全ての文字や記号をファイル名中に使えますが、実際そうすることは賢明ではありません。スペースやタブや改行や他の特殊文字:{ } ( ) [ ] ' ` " \ / > < | ; ! # & ^ * % @ $はコマンドラインで特別な意味を持つので避けるべきです。名前の中の単語間には、ピリオドやハイフンや下線を選んで区別しましょう。各語頭を"LikeThis"のように語頭を大文字にすることもできます。経験を積んだLinuxのユーザはファイル名中にスペースが入ることを避けます。

[注意] 注意

"root"と言う言葉は"rootユーザ"と言う意味でも"rootディレクトリ"意味でも使われます。それがいずれかは使われている文脈から明かです。

[注意] 注意

パスと言う言葉は上述の完全に記述したファイル名に関して使われるばかりではなくコマンドサーチパスにも使われます。どちらの意味かは文脈から明かです。

ファイル階層について詳細に学ぶ最も良い方法は、Filesystem Hierarchy Standard("/usr/share/doc/debian-policy/fhs/fhs-2.3.txt.gz"やhier(7))に記述されています。手始めとして次の事実を覚えるべきです。

表1.3 重要ディレクトリの使い方のリスト。

ディレクトリ 使い方
/ "/"だけだとrootディレクトリを表します。
/etc/ ここはシステム全体の設定ファイルを置く場所です。
/var/log/ ここはシステムのログファイルを置く場所です。
/home/ ここは全ての非特権ユーザのホームディレクトリがあるディレクトリです。

1.2.2. ファイルシステムの内側

Unix の伝統に従い、Debian/Linux システムはハードディスクや他のストレージデバイス上に存在する物理データを表すファイルシステムを提供し、コンソールスクリーンやリモートのシリアルコンソールなどのハードウェアデバイスとの相互作用が"/dev/"の下に統一された形式で表されています。

Debian/Linuxシステム上の、各々のファイルやディレクトリや名前付きパイプ(2つのプログラムがデータを共有する方法)や物理デバイスは、それぞれの所有者(owner)やデータが所属するグループ(group)や最終アクセス時間などの付帯属性(attribute)を記述するinodeと呼ばれるデータ構造を持ちます。 Debian GNU/Linux システムでの inode 構造 の正確な定義を知るには、"/usr/include/linux/fs.h" をご覧ください。 ほとんど全てをファイルシステム表現しようというアイデアはUnixの発明でしたし、現代的なLinuxカーネルはこのアイデアを一歩進めています。コンピュータ上で実行されているプロセス情報さえファイルシステム中に見つけられます。

このような物理的実体と内部プロセスの抽象的かつ統一された表現は非常にパワフルなので、多くの全く異なるデバイスに同じコマンドを使用して同種の操作が行えます。実行中のプロセスに繋がった特殊なファイルにデータを書き込むことでカーネルが如何に動作するかまで変更できます。

[ティップ] ティップ

ファイルツリーや物理的実体の間の関係を確認する必要がある際には、mount(8)を引数無しで実行してください。

1.2.3. ファイルシステムのパーミッション

Unix的システムのファイルシステムのパーミッションは次の3つの影響されるユーザのカテゴリのために定義されています:

  • ファイルを所有するユーザ(user)(u)
  • ファイルが所属するグループ(group)中の他ユーザ(g)
  • "世界"や"全員"とも呼ばれる、全他ユーザ(other)(o)

ファイルでは、それぞれに対応するパーミッションは次のようになります:

  • 読み(read) (r): ファイル内容確認可能
  • 書き(write) (w): ファイル内容変更可能
  • 実行(execute) (x): ファイルをコマンド実行可能

ディレクトリでは、対応するパーミッションはそれぞれ次のようになります:

  • 読み(read) (r): ディレクトリ内容リスト可能
  • 書き(write) (w): ディレクトリへのファイルの追加削除可能
  • 実行(execute) (x): ディレクトリ内のファイルへのアクセス可能

ここで、ディレクトリに関する実行(execute)許可とはディレクトリ内のファイルへの読みを許可するのみならず、サイズや変更時間のようなアトリビュート閲覧を許可します。

ファイルやディレクトリのパーミッション情報他を表示するには、ls(1)が使われます。"-l"オプション付きでこれを実行すると、次の情報がこの順序で表示されます:

  • ファイルのタイプ(最初の文字)
  • ファイルのアクセスパーミッション(次の9文字。ユーザとグループと他者の順にそれぞれに対して3文字から構成されている)
  • ファイルへのハードリンク数
  • ファイルを所有するユ-ザー(user)の名前
  • ファイルが所属するグループ(group)
  • ファイルのサイズ(文字数、バイト)
  • ファイルの日時(mtime)
  • ファイルの名前

表1.4 "ls -l"の出力の最初の文字のリスト

文字 意味
- 通常ファイル
d ディレクトリ
l シムリンク
c 文字デバイス名
b ブロックデバイス名
p 名前付きパイプ
s ソケット

rootアカウントからchown(1)を使用することでファイルの所有者を変更します。ファイルの所有者又はrootアカウントからchgrp(1)を使用することでファイルのグループを変更します。ファイルの所有者又はrootアカウントからchmod(1)を使用することでファイルやディレクトリのアクセス権を変更します。fooファイルの操作の基本的文法は次の通り:

# chown <newowner> foo
# chgrp <newgroup> foo
# chmod  [ugoa][+-=][rwxXst][,...] foo

例えば、ディレクトリツリーの所有者をユーザfooに変更し、グループbarで共有する場合、rootアカウントから次のコマンドを実行します:

# cd /some/location/
# chown -R foo:bar .
# chmod -R ug+rwX,o=rX .

更に特殊なパーミッションビットが3つ存在します:

  • セットユーザID (ユーザのxに代えてsS)。
  • セットグループID (グループのxに代えてsS)。
  • スティッキビット (他ユーザのxに代えてtT)。

ここで、これらのビットの"ls -l"のアウトプットはこれらの出力によってかくされた実行ビットが非設定(unset)の場合大文字となります。

セットユーザIDを実行ファイルにセットすると、ユーザはファイルの所有者ID(例えば、root) を使って実行ファイルを実行することを許可されます。同様に、セットグループIDを実行ファイルにセットすると、ユーザはファイルのグループID(例えば、root) を使って実行ファイルを実行することを許可されます。これらの設定はセキュリティを破壊するリスクを引き起こすので、これらのビットを有効にするには特別な注意が必要です。

セットグループIDsをディレクトリに対して有効にすると、ディレクトリに作成した全ファイルがディレクトリのグループに所属するというBSD的ファイル生成手法が有効になります。

スティッキビットをディレクトリに対して有効にすると、ディレクトリにあるファイルがファイルの所有者以外から削除されるのを防ぎます。"/tmp"やグループの書き込み可能なディレクトリなどのworld-writable なディレクトリにあるファイルの内容を安全にするためには、書き込みパーミッションを無効にするだけでなく、ディレクトリにスティッキビットもセットする必要があります。さもなければ、ディレクトリに書き込みできるユーザにより、ファイルが削除され、同じ名前で新しいファイルが作成されることを許してしまいます。

ファイルパーミッションの興味ある例を次にいくつか示します。

$ ls -l /etc/passwd /etc/shadow /dev/ppp /usr/sbin/exim4
crw------- 1 root root   108, 0 2007-04-29 07:00 /dev/ppp
-rw-r--r-- 1 root root     1427 2007-04-16 00:19 /etc/passwd
-rw-r----- 1 root shadow    943 2007-04-16 00:19 /etc/shadow
-rwsr-xr-x 1 root root   700056 2007-04-22 05:29 /usr/sbin/exim4
$ ls -ld /tmp /var/tmp /usr/local /var/mail /usr/src
drwxrwxrwt 10 root root  4096 2007-04-29 07:59 /tmp
drwxrwsr-x 10 root staff 4096 2007-03-24 18:48 /usr/local
drwxrwsr-x  4 root src   4096 2007-04-27 00:31 /usr/src
drwxrwsr-x  2 root mail  4096 2007-03-28 23:33 /var/mail
drwxrwxrwt  2 root root  4096 2007-04-29 07:11 /var/tmp

chmod(1)を用いて、ファイルパーミッションを記述するためのもう一つの数字モードが存在します。この数字モードは8進数を使った3桁から4桁の数字を用います。

表1.5 chmod(1)コマンドで用いられるファイルパーミッションの数字モード。

数字 意味
1桁目(任意) セットユーザID (=4)とセットグループID (=2)とスティキービット (=1)の和
2桁目 ユーザに関して、読み(read) (=4)と書き(write) (=2)と実行(execute) (=1)ファイル許可の和
3桁目 グループに関して、同上
4桁目 ユーザに関して、同上

これは複雑に聞こえるかもしれませんが、実際は本当にシンプルです。"ls -l"コマンドの出力の最初の数列(2〜10列)を見て、それをファイルパーミッションのバイナリ表記(2進数)("-"を"0"、"rwx"を"1""-")として読むと、この数字モードの値はファイルパーミッションの8進数表現として意味を持ちます。例えば、次を試してみてください:

$ touch foo bar
$ chmod u=rw,go=r foo
$ chmod 644 bar
$ ls -l foo bar
-rw-r--r-- 1 penguin penguin 17 2007-04-29 08:22 bar
-rw-r--r-- 1 penguin penguin 12 2007-04-29 08:22 foo
[ティップ] ティップ

シェルスクリプトから"ls -l"で表示される情報にアクセスする必要がある際には、test(1)やstat(1)やreadlink(1)のような適切なコマンドの使用を考えるべきです。シェル組込みコマンドの"["や"test"を使うのも手です。

1.2.4. 新規作成ファイルのパーミッションのコントロール:umask

新規作成ファイルのやディレクトリに適用されるパーミッションはumaskシェル組込みコマンドを使うことにより制限できます。dash(1)かbash(1)かbuiltins(7)をご覧ください。

 (file permissions) = (requested file permissions) & ~(umask value)

表1.6 umask値の例。

umask 使い方 作成されるファイルパーミッション 作成されるディレクトリパーミッション
0022 ユーザのみにより書込み可 -rw-r--r-- -rwxr-xr-x
0002 グループにより書込み可 -rw-rw-r-- -rwxrwxr-x

Debianシステムはユーザ専用グループ(UPG)方式がデフォルト方式です。新しいユーザがシステムに追加される毎にUPGは作成されます。UPGはそのグループを作成したユーザと同じ名前を持ち、そのユーザがUPGの唯一のメンバーです。UPG方式では、全ユーザが各自専用のグループを持つのでumaskを0002と設定しても安全です。(一部Unix系システムでは全一般ユーザを1つのusersグループに所属させることがよく行われます。そのような場合には安全のため0022とumaskを設定しましょう。)

1.2.5. ユーザのグループ(group)のパーミッション

グループのパーミッションを特定ユーザに適用するには、"sudo vigr"を用いてそのユーザをグループのメンバーにする必要があります。

[注意] 注意

もし"auth optional pam_group.so"行が"/etc/pam.d/common-auth"に書き加えれ、"/etc/security/group.conf"に対応する設定がされていれば、実際のユーザのグループメンバーシップは動的に割り当てられます。(4章認証参照。)

ハードウエアデバイスはDebianシステム上では一種のファイルでしかありません。CD-ROMやUSBメモリスティックのようなデバイスをユーザアカウントからアクセスするのに問題があった場合にはそのユーザを適切なグループのメンバーにしましょう。

いくつかのシステムが供給するグループはそのメンバーにroot権限無しに特定のファイルやデバイスにアクセスすることを可能にします。

表1.7 ファイルアクセスのためにシステムが供給する特記すべきグループのリスト。

グループ アクセスできるファイルやデバイス
dialout シリアルポート ("/dev/ttyS[0-3]")への全面的かつ直接のアクセス。
dip 信頼できるピアーにダイヤルアップIP接続をするためのシリアルポートへの制限付きアクセス。
cdrom CD-ROMやDVD+/-RWのドライバ。
audio 音声デバイス。
video 映像デバイス。
scanner スキャナ。
adm システムモニタのログ。
staff 下級管理業務のためのディレクトリ:"/usr/local"、"/home"。

[ティップ] ティップ

モデムの設定をしたりどこにでも電話したり等するにはdialoutグループに所属する必要があります。もし信頼できるピアーに関する事前定義された設定ファイル"/etc/ppp/peers/"がrootによって作成されていると、dipグループに属するだけでpppd(8)やpon(1)やpoff(1)コマンドを用いてダイヤルアップIP接続が作成できます。

いくつかのシステムが供給するグループはそのメンバーにroot権限無しに特定のコマンドを実行することを可能にします。

表1.8 特定コマンド実行のためにシステムが供給する特記すべきグループのリスト。

グループ 実行可能なコマンド
sudo パスワード無しにsudoを実行。
lpadmin プリンターのデータベースからプリンターを追加・変更・削除するコマンドの実行。
plugdev USBメモリのような着脱可能なデバイスに関してpmount(1)を実行。

システムが供給するユーザやグループの完全なリストは、base-passwdパッケージが供給する"/usr/share/doc/base-passwd/users-and-groups.html"の中にある最新バージョンの"Users and Groups"文書を参照ください。

ユーザやグループシステムを管理するコマンドはpasswd(5)やgroup(5)やshadow(5)やnewgrp(1)やvipw(8)やvigr(8)やpam_group(8)を参照ください。

1.2.6. タイムスタンプ

GNU/Linuxファイルのタイムスタンプには3種類あります。

表1.9 タイムスタンプのタイプのリスト。

タイプ 意味
mtime ファイル内容変更時間(ls -l)
ctime ファイル状態変更時間(ls -lc)
atime ファイル最終アクセス時間 (ls -lu)

ctimeはファイル作成日時でないことに注意しましょう。

  • ファイルが上書きされると、ファイルのmtimectimeatimeの属性すべてが変更されます。
  • ファイルの所有者や許可の変更をすると、ファイルのctimeatime アトリビュートを変えます。
  • ファイルを読むとファイルのatimeが変更されます。Debianシステム上のファイルを単に読むだけでinode中のatime情報を更新する書込みオペレーションが通常引き起こされることを覚えておいてください。ファイルシステムを"noatime"や"relatime"オプションを用いてマウントすることでシステムはこのようなオペレーションをしなくなるので、ファイルへの読みアクセスを高速化できます。ハードディスクの活動を抑えパワーの節約ができるのでこの様な設定はラップトップに推奨されます。mount(8)参照下さい。

既存ファイルのタイムスタンプを変更するにはtouch(1)コマンドを使ってください。

タイムスタンプに関して、現代の英語ロケール("en_US.UTF-8")では古い英語ロケール("C")と違った文字列がlsコマンドから出力されます。

$ LANG=en_US.UTF-8  ls -l foo
-rw-r--r-- 1 penguin penguin 3 2008-03-05 00:47 foo
$ LANG=C  ls -l foo
-rw-r--r-- 1 penguin penguin 3 Mar  5 00:47 foo
[ティップ] ティップ

"ls -l"の出力のカスタマイズは「Customized display of time and date」参照下さい。

1.2.7. リンク

"foo"というファイルを異なるファイル名"bar"に結びつけるのには2つの方法があります。

  • ハードリンクは既存のファイルに対する重複した名前です(ln foo bar)。
  • シンボリックリンクまたは"シムリンク"は名前により他のファイルを指し示す特別なファイルです(ln -s foo bar)。

リンク数の変化とrmコマンドの結果の微妙な違いについての次の例をご覧ください。

$ echo "Original Content" > foo
$ ls -li foo
2398521 -rw-r--r-- 1 penguin penguin 17 2007-04-29 08:15 foo
$ ln foo bar     # hard link
$ ln -s foo baz  # symlink
$ ls -li foo bar baz
2398521 -rw-r--r-- 2 penguin penguin 17 2007-04-29 08:15 bar
2398538 lrwxrwxrwx 1 penguin penguin  3 2007-04-29 08:16 baz -> foo
2398521 -rw-r--r-- 2 penguin penguin 17 2007-04-29 08:15 foo
$ rm foo
$ echo "New Content" > foo
$ ls -li foo bar baz
2398521 -rw-r--r-- 1 penguin penguin 17 2007-04-29 08:15 bar
2398538 lrwxrwxrwx 1 penguin penguin  3 2007-04-29 08:16 baz -> foo
2398540 -rw-r--r-- 1 penguin penguin 12 2007-04-29 08:17 foo
$ cat bar
Original Content
$ cat baz
New Content

ハードリンクは同一ファイルシステム内に作れ、ls(1)コマンドに"-i"オプションを使って表示されるinode番号が同じです。

シンボリックリンクは上の例に示したように、常にファイルアクセスパーミッション"rwxrwxrwx"を持ちますので、シンボリックリンクが指すファイルのアクセスパーミッションが有効ファイルアクセスパーミッションとなります。

[注意] 注意

もし特段の理由がないなら複雑なシンボリックリンクやハードリンクを作らない方が一般的には良いでしょう。シンボリックリンクの論理的組み合わせがファイルシステム中でループになっているという悪夢を引き起こすかもしれません。

[注意] 注意

もしハードリンクを使う特段の理由がなければ、ハードリンクよりシンボリックリンクを使う方が一般的には良いでしょう。

"."ディレクトリは、それ自身が中にあるディレクトリとリンクしていますので、新しいディレクトリリンク数は2から始まります。".."ディレクトリは親ディレクトリとリンクしているので、ディレクトリのリンク数は新しいサブディレクトリの増加に伴い増加します。

もし最近あなたがWindowsからLinuxに移動してきたなら、Unixのファイル名のリンクはWindows上でもっとも似ている"shortcuts"との比較で如何にうまくできているかにすぐ気づくでしょう。ファイルシステム中に実装されているのでアプリケーションからはリンクされたファイルなのかオリジナルなのかの区別がつきません。ハードリンクの場合は実際全く違いはありません。

1.2.8. 名前付きパイプ(FIFO)

名前付きパイプは、パイプのように働くファイルです。何かをファイルに入れると、もう一方の端からそれが出てきます。こうしてこれはFIFOまたはFirst-In-First-Out(先入れ先出し)と呼ばれます。つまり、最初にパイプに入れられたものが最初にもう一方の端から出てきます。

名前付きパイプに書き込んむ場合、パイプに書き込んむプロセスは情報がパイプから読み出されるまで終了しません。名前付きパイプから読み出す場合、読み出すプロセス何か読み込むものが無くなるまで終了するのを待ちます。パイプのサイズは常に 0 です。 -- 名前付きパイプはデータを保存せず、 シェルの"|"のように2つのプロセスをリンクするだけです。しかし、このパイプは名前を持つので、2つのプロセスは同じコマンドラインになくても良いし、同じユーザにより実行される必要さえありません。パイプはUnixの非常に影響力ある発明でした。

次を実行して試してください:

$ cd; mkfifo mypipe
$ echo "hello" >mypipe & # put into background
[1] 8022
$ ls -l mypipe
prw-r--r-- 1 penguin penguin 0 2007-04-29 08:25 mypipe
$ cat mypipe
hello
[1]+  Done                    echo "hello" >mypipe
$ ls mypipe
mypipe
$ rm mypipe

1.2.9. ソケット

ソケットはインターネットのコミュニケーションやデータベースやオペレーティングシステム自身によって頻繁に使われます。ソケットは名前つきパイプ(FIFO)に似ており、異なるコンピュータ間でさえプロセス間の情報交換を可能にします。ソケットにとって、これらのプロセスは同時に実行する必要も、同じ祖先プロセスの子供である必要もありません。これはプロセス間通信(IPC)の終端点です。ネットワーク越しで異なるホストの間で情報の交換をすることも可能です。2つの典型的なソケットは、インターネットソケットUnixドメインソケットです。

[ティップ] ティップ

"netstat -an"を実行すると特定のシステム上のソケットの全般状況がよく分かります。

1.2.10. デバイスファイル

デバイスファイルは、システム上のハードディスク、ビデオカード、ディスプレイ、キーボードなどの物理デバイス又は仮想デバイス等を意味します。仮想デバイスの例として"/dev/console"として表されるコンソールがあります。

表1.10 デバイスのタイプ

デバイスのタイプ 意味
文字デバイス 一度に1つの文字づつアクセスする、デバイスから書き込みや読み込みを行うデータの最小単位が文字(バイト)であるデバイスです。
ブロックデバイス ブロックと呼ばれる複数の文字を含む比較的大きな大きな単位でアクセスされるデバイスです。ハードディスクはブロックデバイスです。

デバイスファイルの読み書きが可能ですが、人間にとっては意味不明のバイナリデータがファイル中に多分含まれています。データを直接デバイスファイルに書き込むことは時々ハードウェアの接続に関するトラブルシュートに役立ちます。例えば、プリンタデバイス"/dev/lp0"にテキストファイルをダンプしたり、 適切なシリアルポート"/dev/ttyS0"にモデムコマンドを送ることができます。しかし、注意深くやらないと、大災害をもたらすことがあります。くれぐれも気をつけてください。

[注意] 注意

通常のプリンターへのアクセスはlp(1)を使いましょう。

ls(1)を次のように実行するとデバイスノード番号が表示されます:

$ ls -l /dev/hda /dev/ttyS0 /dev/zero
brw-rw---- 1 root cdrom   3,  0 2007-04-29 07:00 /dev/hda
crw-rw---- 1 root dialout 4, 64 2007-04-29 07:00 /dev/ttyS0
crw-rw-rw- 1 root root    1,  5 2007-04-29 07:00 /dev/zero

上記で:

  • "/dev/hda"はメジャーデバイス番号3とマイナーデバイス番号0を持ちます。これはdiskグループに所属するユーザにより、読み書きアクセスが可能です。
  • "/dev/ttyS0" はメジャーデバイス番号4とマイナーデバイス番号64を持ちます。これはdialoutグループに所属するユーザにより、読み書きアクセスが可能です。
  • "/dev/zero" はメジャーデバイス番号1とマイナーデバイス番号5を持ちます。これは誰によっても読み書きアクセスが可能です。

Linux 2.6システムでは、"/dev/"の下のファイルはudev(7)メカニズムで自動的に生成されます。

1.2.11. 特別なデバイスファイル

いくつかの特別なデバイスファイルがあります。

表1.11 スペシャルなデバイスファイルのリスト。

デバイスファイル アクション レスポンス
/dev/null 読み "行末(EOF)文字"を返します。
/dev/null 書き 底なしのデータのゴミ捨て場です。
/dev/zero 読み "\0 (NUL)文字"を返します(ASCIIの数字のゼロとは違います)。
/dev/random 読み 真の乱数発生機から真のエントロピーのあるランダムな文字を返す。(遅い)
/dev/urandom 読み 暗号学的にセキュアな擬似乱数発生機からランダムな文字を返す。
/dev/full 書き ディスクフル(ENOSPC)エラーを返す。

以上はシェルのリディレクションとともによく使われます。(「典型的なコマンドシーケンスとシェルリディレクション」参照)。

1.2.12. procfsとsysfs

procfssysfsは"/proc"や"/sys"上にマウントされる仮想ファイルシステムであり、カーネルの内部データ構造をユーザスペースにさらけ出します。言い換えると、オペレーティングシステムのオペレーションへの便利なのぞき窓となると言う意味で仮想といえます。

"/proc"ディレクトリ中には、システム上で実行されている各プロセスに対応したそのプロセスID(PID)の名前がついたサブディレクトリ他があります。プロセス情報をアクセスするps(1)のようなシステムユーティリティはこのディレクトリ構造からその情報を得ています。

"/proc/sys/"の下のディレクトリには実行時のカーネル変数を変更するインターフェースがあります。(専用のsysctl(8)コマンドもしくはその起動/設定ファイル"/etc/sysctrl.conf"によっても同様のことができます。)

[注意] 注意

Linuxカーネルが"Too many open files"とエラーを出力することがあります。rootのシェルから、例えば"echo "65536" > /proc/sys/fs/file-max"等と"file-max"の値をより大きな値に増加することで解決できます。(古いカーネルではこれが必要でした。)

特にあるファイル - "/proc/kcore" - に気づくと、パニックになる人がよくいます。これは一般に巨大です。これは(おおよそ)コンピュータのメモリの内容のコピーです。これは kernel をデバッグするのに用いられます。コンピュータのメモリを指す仮想ファイルなので、そのサイズに関して心配する必要は全くありません。

"/sys"の下のディレクトリはカーネルから引き出されたデータ構造、その属性、それらの関連を含んでいます。一部カーネル変数を実行時に変更する機構もまた含まれたりします。

linux-doc-2.6.*パッケージで供給されるLinuxカーネル文書("/usr/share/doc/linux-doc-2.6.*/Documentation/filesystems/*")中の"proc.txt(.gz)"や"sysfs.txt(.gz)"や関連する他の文書を参照下さい。

1.3. ミッドナイトコマンダー(MC)

Midnight Commander (MC)はLinux コンソールや他の端末環境のためのGNU製"スイス軍ナイフ"です。標準Unixコマンドを習うよりもより簡単なメニューを使ったコンソール経験が初心者にもできます。

"mc"と名づけられた Midnight Commanderパッケージをインストールする必要があります。

$ sudo aptitude install mc

Debian システムを探検するためにmc(1)コマンドを使いましょう。これは学習するための最良の方法です。カーソルキーとエンターキーを使うだけでいくつかの主要な場所を探検してください。

  • "/etc"とサブディレクトリ。
  • "/var/log"とサブディレクトリ。
  • "/usr/share/doc"とサブディレクトリ。
  • "/sbin"と"/bin"。

1.3.1. MCのカスタム化

終了時に作業ディレクトリをMCに変更させそのディレクトリへcdさせるためには、"~/.bashrc"を次を含むように変更しましょう:

. /usr/share/mc/bin/mc.sh

この理由はmc(1) ("-P"オプション項目) を参照下さい(今言っていることがよく分からないなら、これは後日しても大丈夫です。)

1.3.2. MCの始動

MCは次のようにして始動できます:

$ mc

MCを使うとメニューを通じた最小限のユーザの努力で全てのファイル操作の面倒が見られます。ヘルプ表示を出すには、ただF1を押すだけです。カーソルキーとファンクションキーの操作だけでMCを使えます。

[注意] 注意

gnome-terminal(1)のようなコンソールでは、ファンクションキーのキーストロークがコンソールプログラムに横取りされる事があります。gnome-terminalの場合、"Edit" → "Keyboard Shortcuts"とするとこの機能を無効にできます。

もし文字化け表示がされる文字エンコーディング問題に出会った際には、MCのコマンドラインに"-a"を加えると解消する事があります。

これでもMCの表示の問題が解消しない際には、「ターミナルの設定」を参照下さい。

1.3.3. MCのファイルマネージャ

2つのディレクトリパネルがありそれぞれファイルリストを含むのが標準です。他の便利なモードとしては、右側のウィンドウを"information" とセットしてファイルアクセス権情報などを表示するモードがあります。次にいくつかの不可欠なキーストロークを示します。gpm(8)デーモンを実行すると、Linuxの文字ターミナルでマウスも使えます。(MC で通常の挙動のカットアンドペーストをさせるには、shiftキーを押してください。)

表1.12 MCのキーバインディング

キー キーバインディング
F1 ヘルプメニュー
F3 内部ファイルビューア
F4 内部エディタ
F9 プルダウンメニューを有効にする
F10 MCを終了する
Tab 二つのウィンドウの間を移動する
InsertもしくはCtrl-T コピーのような複数ファイル操作のため、ファイルにマークをする
Del ファイルの削除 (気をつけましょう -- MCを安全削除モードに設定)
カーソルキー 自明

1.3.4. MC のコマンドライントリック

  • cdコマンドは選択されたスクリーンに表示されたディレクトリを変更します。
  • Ctrl-EnterAlt-Enterはファイル名をコマンドラインにコピーします。コマンドライン編集と一緒にcp(1)やmv(1)コマンドで御使用ください。
  • Alt-Tabはシェルファイル名の自動展開の選択肢を表示します。
  • MCの引数で両ウインドウの開始ディレクトリを指定できます。例えば"mc /etc /root"。
  • Esc + n-keyFn (つまり、Esc + 1F1、等々、Esc + 0F10)
  • Escをキーの前に押すのはAltをキーと同時に押すのと同様の効果があります。つまり、Esc + cAlt-Cと同じです。Escはメタキーとよばれ時々"M-"と表記されます。

1.3.5. MCの内部エディタ

MC の内部エディタは興味深いカットアンドペースト機構を持ちます。F3キーを押すと、選択範囲の開始としてマークし、次にF3を押すと、選択範囲の終了としてマークし、選択範囲を強調します。そしてカーソルを動かすことができます。F6を押すと、選択範囲はカーソルの位置に移動します。F5を押すと、選択範囲はコピーされ、カーソルの位置に挿入されます。F2を押すとファイルをセーブします。F10を押すと選択範囲はなくなります。ほとんどのカーソルキーは直感的に働きます。

このエディタは直接ファイルに関しても起動できます:

$ mc -e filename_to_edit
$ mcedit filename_to_edit

これはマルチモードエディタではありませんが、複数の Linux コンソール上で使用すると同じ効果を発揮させされます。ウィンドウ間のコピーを行うには、 Alt-<n>キーを押して仮想コンソールを切替えて、"File→Insert file"や"File→Copy to file"を用いてファイルの一部を他のファイルに動かします。

この内部エディタはお好きな他の外部エディタと置き換えが可能です。

また、多くのプログラムは使用するエディタを決定するために環境変数"$EDITOR"や"$VISUAL"を使用します。最初vim(1)やnano(1)が使いにくい場合には"~/.bashrc"に次に示す行を追加してエディタを"mcedit"に設定するのも一計です。

...
export EDITOR=mcedit
export VISUAL=mcedit
...

できればこれは"vim"に設定することを推奨します。

vim(1)が使いにくい場合には、mcedit(1)をほとんどのシステム管理業務のために使い続けられます。

1.3.6. MCの内部ビューア

非常に小さなビューアです。文書内の単語を検索するための素晴らしいツールです。私は"/usr/share/doc"ディレクトリ内のファイルに対していつもこれを使います。これは 大量にあるLinux情報を閲覧するための最速の方法です。このビューアはこのように直接起動できます。

$ mc -v path/to/filename_to_view
$ mcview path/to/filename_to_view

1.3.7. MCの自動起動機能

ファイルの上でEnterを押すと、適切なプログラムがファイル内容を処理します(「Customizing program to be started」参照)。これは非常に便利な MC の機能です。

表1.13 キー入力へのMCの反応

ファイルタイプ enterキーへの反応
実行ファイル コマンド実行
manファイル ビューアソフトに内容をパイプする
htmlファイル ウエッブブラウザに内容をパイプする
"*.tar.gz"や"*.deb"ファイル サブディレクトリであるかのように内容を表示

これらのビューアや仮想ファイルの機能を有効にするためには、閲覧可能なファイルには実行可能と設定されていてはいけません。chmod(1)コマンドを使うか、MC のファイルメニュー経由で状態を変更してください。

1.3.8. MCのFTP仮想ファイルシステム

MCをInternet越しでのFTPを用いたファイルアクセスに使えます。F9を押してメニューに行き、"p"を押してFTP仮想ファイルシステムを有効にします。"username:passwd@hostname.domainname"の形式でURLを入力すると、あたかもローカルにあるかのようにリモートディレクトリを取得します。

"[http.us.debian.org/debian]"をURLとしてDebianアーカイブを閲覧しましょう。

1.4. 基本のUnix的作業環境

MCはほとんど全てのことを可能にしますが、シェルプロンプトから実行されるコマンドラインツールの使用方法について学び、Unix的な作業環境に親しむのは非常に重要なことです。

1.4.1. loginシェル

ログインシェルはchsh(1)を使えば選択できます。

表1.14 シェルプログラムのリスト。

パッケージ popcon サイズ POSIXシェル 説明
bash V:91, I:99 1336 はい Bash:GNU Bourne Again SHell(事実上の標準シェル)
tcsh V:8, I:55 736 いいえ TENEX C Shell:拡張バージョンのBerkeley csh
dash V:3, I:12 236 はい DebianのAlmquistシェル。シェルスクリプトに好適。
zsh V:2, I:5 12752 はい Z shell:多くの拡張された標準シェル。
pdksh V:0.3, I:1.2 464 はい A public domain version of the Kornシェル.
csh V:0.6, I:1.8 404 いいえ OpenBSDのCシェル、Berkeley cshの1バージョン。
sash V:0.2, I:1.0 836 はい 組み込みコマンド付きの独立シェル。(標準の"/bin/sh"には向きません。)
ksh V:0.4, I:1.5 2860 はい 真のAT&TバージョンのKornシェル
rc V:0.09, I:0.7 204 いいえ AT&T Plan 9rcシェルの実装。
posh V:0.01, I:0.14 232 はい ポリシー準拠の通常シェル。pdkshの派生。

このチュートリアル章内では、インタラクティブなシェルは常にbashです。

1.4.2. Bashのカスタム化

bash(1)の動作は"~/.bashrc"でカスタマイズできます。例えば次を"~/.bashrc"に加えます:

# CD upon exiting MC
. /usr/share/mc/bin/mc.sh

# set CDPATH to good one
CDPATH=.:/usr/share/doc:~/Desktop/src:~/Desktop:~
export CDPATH

PATH="${PATH}":/usr/sbin:/sbin
# set PATH so it includes user's private bin if it exists
if [ -d ~/bin ] ; then
  PATH=~/bin:"${PATH}"
fi
export PATH

EDITOR=vim
export EDITOR
[ティップ] ティップ

bashに関する更なるカスタマイズ方法は、9章System tips中の「Colorized commands」等にあります。

1.4.3. 特別のキーストローク

Unix的環境下では、特別の意味を持ったいくつかのキーストロークがあります。通常のLinuxの文字ターミナルでは左側のCtrlAltキーのみが期待にそって機能することに配慮下さい。次に特記すべき暗記するべきキーストロークを記します。

表1.15 Bashのキーバインディングのリスト。

キー キーバインディング
Ctrl-U カーソルの前の1行を消去します。
Ctrl-H カーソルの前の1文字を削除します。
Ctrl-D 入力を終了します。(シェルを使用中の場合、シェルを終了します)
Ctrl-C 実行中のプログラムを終了します。
Ctrl-Z 一時的にプログラムをバックグラウンドジョブに入れ停止します。
Ctrl-S スクリーンへの出力を停止します。
Ctrl-Q スクリーンへの出力を再開します。
Ctrl-Alt-Del システムをリブート/停止します、inittab(5)を参照下さい。
Left-Altキー (もしくは、Windowsキー) Emacsおよび同様のUIでのメタキー
Up-arrow bashでコマンド履歴検索を開始します。
Ctrl-R bashでインクリメンタルなコマンド履歴検索を開始します。
Tab bashのコマンドラインでファイル名の入力を完結します。
Ctrl-V Tab bashのコマンドラインでTabを展開することなく入力します。

[ティップ] ティップ

ターミナルのCtrl-S機能はstty(1)で無効にできます。

1.4.4. Unix流のマウス操作

Unix流のマウス操作は3ボタンマウスが基本です。

表1.16 Unix流のマウス操作のリスト

アクション レスポンス
マウスの左クリックアンドドラッグ 選択とクリップボードへのコピー。
左クリック 選択開始点の選択。
右クリック 選択終了点の選択とクリップボードへのコピー。
中クリック クリップボードをカーソル位置に挿入。

最近のホイールマウスの真ん中のホイールは中マウスボタンと見なされ、中クリックに使えます。2ボタンマウス状況では左右のボタンの同時押しが中クリックとして使えます。Linuxの文字コンソールでマウスを使うにはgpm(8)をデーモンで実行する必要があります。

1.4.5. ページャ

less(1)は機能拡張されたページャ(ファイル内容のブラウザ)です。"h" と入力するとヘルプが表示されます。これは、more(1) よりもはるかに機能があり、"eval $(lesspipe)"または"eval $(lessfile)"とシェルの開始スクリプト中で実行することで更に機能拡充されます。詳しくは、"/usr/share/doc/lessf/LESSOPEN"を参照下さい。"-R"オプションを用いると生の option allows raw文字出力が許可され、ANSIカラーエスケープシーケンスが有効になります。less(1)参照下さい。

1.4.6. テキストエディタ

Unix的システムで人気のある、VimEmacsプログラムのいずれかのバリアントに習熟するべきです。

著者としてはVimコマンドに慣れることは正しいことだと考えています。なぜならViエディタはLinux/Unixの世界では必ず存在するからです。(実際はオリジナルのviか、新しいnviがどこででも見つけられるプログラムです。これにもかかわらずVimを著者が初心者のために選んだのは、より強力かつ動作が充分似ているのと、F1キーを通じてヘルプが表示されるからです。)

これとは違い、EmacsXEmacsをエディタとして選ぶのも、特にプログラムをするには、非常に良い選択です。Emacsには、ニュースリーダ機能、ディレクトリの編集機能、メール機能他の、過多な機能があります。プログラミングやシェルスクリプトの編集に使うときは、作業中のフォーマットをインテリジェントに認識し助力をしようとします。Linux上で必要なプログラムはEmacsだけと考える人もいます。Emacsを今10分間学ぶことは将来何時間もの節約になります。Emacsを学ぶ際にはGNUのEmacsマニュアルを持っておくことを高く推薦します。

これら全てのプログラムには練習しながら学べるようにチュータリングプログラムが普通付いてきます。Vimを"vim"とタイプして起動し、F1キーを押しましょう。最初の35行を読みましょう。カーソルを"|tutor|"に移動しCtrl-]を押してオンラインの訓練コースを始めましょう。

[注意] 注意

VimやEmacsのような良いエディタは、正しいフォント設定がされたUTF-8ロケールの下の正しいオプションを使ったx-terminal-emulatorを使うと、UTF-8や他のエギゾチックなエンコーディングのテキストを正しく扱えます。マルチバイトテキストに関するそれぞれの文書を参照下さい。

1.4.7. デフォルトのテキストエディタの設定

Debianにはいくつかの異なったエディタがあります。上述のようにvimパッケージをインストールすることを推薦します。

Debianではシステムのデフォルトのエディタへの統一されたアクセスを"/usr/bin/editor"コマンドを通じて提供しているので、他のプログラム(例えばreportbug(1)等)が起動できます。設定変更は:

$ sudo update-alternatives --config editor

著者が"/usr/bin/vim.tiny"より"/usr/bin/vim.basic"を初心者に推薦するのはシンタクスハイライトをサポートしているからです。

[ティップ] ティップ

多くのプログラムは"$EDITOR"か"$VISUAL"という環境変数を使ってどのエディタを使うかを決めます(「MCの内部エディタ」「Customizing program to be started」参照)。Debianシステムの整合性のために、これらを"/usr/bin/editor"と設定しましょう。(歴史的には"$EDITOR"は"ed"で、"$VISUAL"は"vi"でした。)

1.4.8. Vimのカスタム化

vim(1)の挙動は"~/.vimrc"を使ってカスタマイズできます。例えば著者は次を使ってます:

" -------------------------------
" Local configuration
"
set nocompatible
set nopaste
set pastetoggle=<f2>
syn on
if $USER == "root"
 set nomodeline
 set noswapfile
else
 set modeline
 set swapfile
endif
" filler to avoid the line above being recognized as a modeline
" filler
" filler

1.4.9. シェル活動の記録

シェルコマンドの出力はスクリーンから押し出されると永久に無くなってしまうかもしれません。シェルでの活動を後で見直せるようにファイルに記録しておくのは良いことです。この種の記録は何らかのシステム管理作業をする際には非常に重要です。

シェル活動の記録の基本方法はscript(1)の下で実行することです。

$ script
Script started, file is typescript
  • 何らかのシェルコマンドの実行 …
  • Ctrl-Dを押してscriptから脱出。
$ vim typescript

「Recording the shell activities cleanly」参照下さい。

1.4.10. 基本Unixコマンド

基本的Unixコマンドを学びましょう。ここでは一般的意味で"Unix"を使っています。いかなるUnixクローンのOSも等価なコマンドを提供します。Debianシステムも例外ではありません。今一部コマンドが思うように機能しなくても心配しないで下さい。エアリアスがシェルで使われた場合は、対応するコマンドの出力は変わります。次は順番に実行すると言う意味の例ではありません。

非特権ユーザのアカウントから次のコマンドを全て実行しましょう:

表1.17 基本のUnixコマンドのリスト。

コマンド 説明
pwd カレント/ワーキングディレクトリの名前を表示。
whoami 現在のユーザ名を表示します。
id 現在のユーザのアイデンティティ(名前とuidとgidと関連するgroup)を表示します。
file <foo> "<foo>"ファイルのファイルタイプを表示します。
type -p <commandname> "<commandname>"コマンドのファイルの位置を表示します。
which <commandname> , ,
type <commandname> "<commandname>"コマンドに関する情報を表示します。
apropos <key-word> "<key-word>"に関連したコマンドを見つけます。
man -k <key-word> , ,
whatis <commandname> "<commandname>"コマンドに関する1行の説明を表示します。
man -a <commandname> "<commandname>"コマンドに関する説明を表示します。(Unixスタイル)
info <commandname> "<commandname>"コマンドに関する比較的長い説明を表示します。(GNUスタイル)
ls ディレクトリの内容をリストします。(非ドットファイルおよびディレクトリ)
ls -a ディレクトリの内容をリストします。(全ファイルおよびディレクトリ)
ls -A ディレクトリの内容をリストします。(ほとんど全ファイルおよびディレクトリ、".."と"."をスキップ)
ls -la ディレクトリの内容を詳細情報とともにリストします。
ls -lai ディレクトリの内容をinode番号と詳細情報とともにリストします。
ls -d 現ディレクトリの中の全ディレクトリをリストします。
tree ファイルツリーの内容を表示します。
lsof <foo> "<foo>"ファイルのオープンの状態をリスト。
lsof -p <pid> プロセスID: "<pid>"によってオープンされたファイルをリストします。
mkdir <foo> 現ディレクトリ中に"<foo>"という新規ディレクトリを作る。
rmdir <foo> 現ディレクトリ中の"<foo>"というディレクトリを削除します。
cd <foo> 現ディレクトリ中もしくは"$CDPATH"変数中にリストされたディレクトリ中の"<foo>"というディレクトリにディレクトリを変更します。
cd / ディレクトリをrootディレクトリに変更します。
cd 現在のユーザのホームディレクトリにディレクトリを変更します。
cd /<foo> 絶対ディレクトリパス"/<foo>"にディレクトリを変更する。
cd .. 親ディレクトリにディレクトリを変更します。
cd ~<foo> ユーザ"<foo>"のホームディレクトリにディレクトリを変更します。
cd - 一つ前のディレクトリにディレクトリを変更します。
</etc/motd pager "/etc/motd"の内容をデフォルトのページャで表示します。
touch <junkfile> 空ファイル"<junkfile>"を作成します。
cp <foo> <bar> 既存のファイル"<foo>"を新規ファイル"<bar>"にコピーします。
rm <junkfile> ファイル"<junkfile>"を削除します。
mv <foo> <bar> 既存のファイル"<foo>"の名前を新しい名前"<bar>"に変更します。ディレクトリ"<bar>"が存在してはいけません。
mv <foo> <bar> 既存のファイル"<foo>"を新しい場所"<bar>/<foo>"に移動します。ディレクトリ"<bar>"が存在しなければいけない。
mv <foo> <bar>/<baz> 既存のファイル"<foo>"を新しい場所の新しい名前のファイル"<bar>/<baz>"に移動します。ディレクトリ"<bar>"が存在しなければいけないが、ディレクトリ"<bar>/<baz>"は存在してはいけない。
chmod 600 <foo> 既存のファイル"<foo>"を他の人から読みも書きもできないようにします。(全ての人にとって実行不可)
chmod 644 <foo> 既存のファイル"<foo>"を他の人からは読めるが書けるようにします。(全ての人にとって実行不可)
chmod 755 <foo> 既存のファイル"<foo>"を他の人からは読めるが書けるようにします。(全ての人にとって実行可能)
find . -name <pattern> シェルで"<pattern>"にマッチするファイル名を探す。(比較的遅い)
locate -d . <pattern> シェルで"<pattern>"にマッチするファイル名を探す。(定期的に生成されるデータベースを使い比較的早い)
grep -e "<pattern>" *.html 現ディレクトリにある".html"で終わる全ファイルから"<pattern>"のパターンを検索し、該当する全ファイルを表示します。
top フルスクリーンを用いてプロセス情報を表示します。"q"を押して終了します。
ps aux | pager 起動中の全プロセスの情報をBSDスタイルの出力を用いて表示します。
ps -ef | pager 起動中の全プロセスの情報をSystem-Vスタイルの出力を用いて表示。
ps aux | grep -e "[e]xim4*" "exim"もしくは"exim4"の起動中の全プロセスを表示。
ps axf | pager 起動中の全プロセスの情報をASCIIアート出力を用いて表示。
kill <1234> プロセスID"<1234>"により識別されるプロセスを殺す。
gzip <foo> Lempel-Zivコーディング(LZ77)を用いて"<foo>"を圧縮し"<foo>.gz"を作成します。
gunzip <foo>.gz "<foo>.gz"を解凍して"<foo>"を作成します。
bzip2 <foo> Burrows-Wheelerブロックソートテキスト圧縮アルゴリズムとHuffmanコーディングを用いて"<foo>"を圧縮し"<foo>.bz2"を作成します。(gzipより高圧縮率)
bunzip2 <foo>.bz2 "<foo>.bz2"を解凍して"<foo>"を作成します。
tar -xvf <foo>.tar "<foo>.tar"アーカイブからファイルを展開します。
tar -xvzf <foo>.tar.gz gzip圧縮された"<foo>.tar.gz"アーカイブからファイルを展開します。
tar -xvf -j <foo>.tar.bz2 "<foo>.tar.bz2"アーカイブからファイルを展開します。
tar -cvf <foo>.tar <bar>/ フォルダ"<bar>/"の内容を"<foo>.tar"アーカイブにアーカイブします。
tar -cvzf <foo>.tar.gz <bar>/ フォルダ"<bar>/"の内容を"<foo>.tar.gz"アーカイブに圧縮アーカイブします。
tar -cvjf <foo>.tar.bz2 <bar>/ フォルダ"<bar>/"の内容を"<foo>.tar.bz2"アーカイブに圧縮アーカイブします。
zcat README.gz | pager 標準のページャを用いて圧縮された"README.gz"の内容を表示します。
zcat README.gz > foo "README.gz"の内容を解凍してファイル"foo"を作成します。
zcat README.gz >> foo 圧縮された "README.gz"の内容をファイル"foo"の末尾に追加します。(ファイルが存在しない場合は事前に作成される。)

[注意] 注意

Unixは"."で始まるファイル名を隠す伝統があります。それらは伝統的には特定の設定情報やユーザの嗜好を含むファイルです。

[注意] 注意

cdコマンドに関してはbuiltins(7)を参照下さい。

[注意] 注意

最小限のDebianシステムのデフォルトのページャはmore(1)で、スクロールバックができません。lessパッケージを"aptitude install less"と言うコマンドラインでインストールすると、less(1)が デフォルトのページャになりカーソルキーでスクロールバック出来るようになります。

[注意] 注意

上記の"ps aux | grep -e "[e]xim4*""コマンド中に現れる正規表現中の"["と"]"はgrepが自分自身にマッチするのを避けることを可能とします。正規表現中の"4*"は数字"4"の0回以上の繰り返しを意味するので、grepが"exim"と"exim4"の両方にマッチすることが可能になります。 "*"はシェルのファイルネームのグロブでも正規表現ででも使われますが、これらの意味は異なります。grep(1)から正規表現を学びましょう。

上記のコマンドを訓練として用いて、ディレクトリを渡り歩き、システムの中を覗き込んでください。コンソールのコマンドに関して質問がある場合は、必ずマニュアルページを読んでみてください。例えば、これらのコマンドは良い開始点でしょう:

$ man man
$ man bash
$ man builtins
$ man grep
$ man ls

マンページのスタイルは慣れるのに少々大変かもしれません。なぜなら特に比較的古い非常に伝統的なマンページは比較的言葉が少ないからです。しかし一旦慣れるとその簡潔さの良さが分かります。

GNUやBSD由来を含む多くのUnix的なコマンドは次のように起動すると簡単なヘルプ情報を表示します。(場合によっては一切の引数無しで):

$ <コマンド名> --help
$ <コマンド名> -h

1.5. シェルプロンプト

Debianシステムの使い方が少し分かったでしょう。Debianシステム上でのコマンド実行のメカニズムを掘り下げましょう。初心者のためにちょっと簡略化してみました。正確な説明はbash(1)を参照下さい。

シンプルなコマンドは、次のシーケンスとなります:

  1. 変数代入(任意)
  2. コマンド名
  3. 引数(任意)
  4. リダイレクト(任意:>>><<<等。)
  5. 制御演算子(任意:&&||と<改行>と;&())

1.5.1. コマンド実行と環境変数

環境変数の値はUnixコマンドの挙動を変えます。

環境変数のデフォルト値はPAMシステムが初期設定されます。その後次のような何らかのアプリケーションプログラムにより再設定されているかもしれません。

  • gdmのようなディスプレイマネージャによって再設定される。
  • "~/bash_profile"や"~/.bashrc"にあるシェル起動コードの中でシェルにより再設定される。

1.5.1.1. "$LANG"変数

"$LANG"変数に与えられる完全なロケール値は3つの部分からなります:"xx_YY.ZZZZ"。


言語コードと国コードは"info gettext"中の該当記述を参照下さい。

最近のDebianシステム上では、十分な理由と必要な知見をもって歴史的なコードセットを特段希望しない限り、常にコードセットをUTF-8と設定すべきです。

ロケールの詳細に関しては、「ロケール」を参照下さい。

[注意] 注意

"LANG=en_US"は、"LANG=C"でも、"LANG=en_US.UTF-8"でもありません。それは"LANG=en_US.ISO-8859-1"です(「Basics of encoding」参照)。

表1.19 推奨ロケールのリスト。

言語(地域) 推奨ロケール
英語(米国) en_US.UTF-8
英語(英国) en_GB.UTF-8
フランス語(フランス) fr_FR.UTF-8
ドイツ語(ドイツ) de_DE.UTF-8
イタリア語(イタリア) it_IT.UTF-8
スペイン語(スペイン) es_ES.UTF-8
カタラン語(スペイン) ca_ES.UTF-8
スウェーデン語(スウェーデン) sv_SE.UTF-8
ポルトガル語(ブラジル) pt_BR.UTF-8
ロシア語(ロシア) ru_RU.UTF-8
中国語(中華人民共和国) zh_CN.UTF-8
中国語(台湾_R.O.C.) zh_TW.UTF-8
日本語(日本) ja_JP.UTF-8
韓国語(大韓民国) ko_KR.UTF-8
ベトナム語(ベトナム) vi_VN.UTF-8

典型的なコマンドの実行は次のようなシェル行のシーケンスを用います:

$ date
Sun Jun  3 10:27:39 JST 2007
$ LANG=fr_FR.UTF-8 date
dimanche 3 juin 2007, 10:27:33 (UTC+0900)

以上で、date(1)プログラムはフォアグラウンドのジョブとして実行されます。環境変数"$LANG"は:

  • 最初のコマンドに関しては、システムのデフォルトロケール(設定次第ですがここでは"en_US.UTF-8")に設定されています。
  • 2番目のコマンドに関しては、"fr_FR.UTF-8"(システム上に存在すればフランス語のUTF-8ロケール)に設定されています。

ほとんどのコマンド実行は頭に環境変数定義をつけないのが普通です。上記の例の代わりに次のように実行します:

$ LANG=fr_FR.UTF-8
$ date
dimanche 3 juin 2007, 10:27:33 (UTC+0900)

ここで確認できるように、コマンドの出力は環境変数に影響されフランス語の出力となっています。もし環境変数を(例えばシェルスクリプトを呼んでいて)サブプロセスに引き継ぎたい際には、次のように環境変数を"export"(エクスポート)しなければいけません。

$ export LANG
[ティップ] ティップ

バグ報告をする際には、非英語環境を使っているなら、プログラムを"LANG=en_US.UTF-8"の下で実行し確認することが望ましいです。

"$LANG"とこれに関連した環境変数に関しては、locale(5)とlocale(7)を参照下さい。

[注意] 注意

特段必要がなければ"$LC_*"変数を避けて、"$LANG"変数のみを用いてシステム環境設定する事をお薦めします。

1.5.1.2. "$PATH"変数

シェルにコマンドを打ち込んだ際に、シェルは"$PATH"環境変数にリストされたディレクトリのリストから検索します。"$PATH"環境変数の値は、シェルの検索パスとも呼ばれます。

標準のDebianインストールでは、ユーザアカウントの"$PATH"環境変数には"/sbin"や"/usr/sbin"が含まれないかもしれません。例えば、ifconfigコマンドは"/sbin/ifconfig"とフルパスを使って実行する必要があります。(類似のipコマンドは"/bin"にあります。)

Bashシェルの"$PATH"環境変数は、"~/.bash_profile"か"~/.bashrc"ファイルで変更できます。

1.5.1.3. "$HOME"変数

多くのコマンドはユーザ特定の設定をホームディレクトリに保存し、その内容でコマンドの挙動が変わります。ホームディレクトリは"$HOME"環境変数で指定されます:

表1.20 "$HOME"の値のリスト。

プログラム実行状況 "$HOME"の値
initプロセスが実行するプログラム(デーモン) /
通常のrootシェルから実行されるプログラム /root
通常のユーザシェルから実行されるプログラム /home/<normal_user>
通常のユーザのGUIデスクトップメニューから実行されるプログラム /home/<normal_user>
"sudo program"を用いてrootとして実行されるプログラム /home/<normal_user>
"sudo -H program"を用いてrootとして実行されるプログラム /root

[ティップ] ティップ

シェルは、"~/"を現ユーザのホームディレクトリである"$HOME/"へと展開します。シェルは、"~foo/"をユーザfooのホームディレクトリである"/home/foo/"へと展開します。

1.5.2. コマンドラインオプション

プログラムコマンドによっては引数があります。引数は"-"か"--"で始まり、オプションと呼ばれ、コマンドの挙動をコントロールします。

$ date
Mon Oct 27 23:02:09 CET 2003
$ date -R
Mon, 27 Oct 2003 23:02:40 +0100

上記で、コマンドライン引数"-R"がdate(1)の挙動をRFC2822準拠の日付文字列出力と変えています。

1.5.3. シェルグロブ

ファイル名を全てタイプせずにファイルのグループをコマンド処理したいことがよくあります。シェルのグロブ(ワイルドカードとも時々呼ばれる)を用いたファイル名のパターン展開を用いるとこのニーズに答えられます。

表1.21 シェルグロブパターン

シェルグロブパターン マッチ
* "."で始まらない任意のファイル(部分)名にマッチします。
.* "."で始まる任意のファイル(部分)名にマッチします。
? 任意の 1 文字にマッチします。
[…] 括弧中の 1 文字にマッチします。
[a-z] "a"と"z"の範囲にある文字とマッチする。
[^…] 括弧内( "^"以外)に含まれる文字以外の文字にマッチ。

例えば、次の例を試してみて、自分で考えてみましょう:

$ mkdir junk; cd junk; .[^.]*touch 1.txt 2.txt 3.c 4.h .5.txt ..6.txt
$ echo *.txt
1.txt 2.txt
$ echo *
1.txt 2.txt 3.c 4.h
$ echo *.[hc]
3.c 4.h
$ echo .*
. .. .5.txt ..6.txt
$ echo .*[^.]*
.5.txt ..6.txt
$ echo [^1-3]*
4.h
$ cd ..; rm -rf junk

詳細はglob(7)を参照下さい。

[注意] 注意

通常のシェルのファイル名の展開と違い、find(1)が"-name"テスト他でシェルパターン"*"をテストする際にはファイル名先頭の"."ともマッチします。(新POSIX機能)

[注意] 注意

BASHはshopt組み込みオプションで"dotglob"や"noglob"や"nocaseglob"や"nullglob"や"nocaseglob"や"extglob"などとすることでグロブ挙動を色々変更できます。bash(1)参照下さい。

1.5.4. コマンドの戻り値

各コマンドは終了ステータスを戻り値(変数:"$?")として返します。

表1.22 コマンドの終了コード。

コマンドの終了状態 戻り値の数値 戻り値の論理値
成功 ゼロ、0
失敗 非ゼロ、-1

つまり:

$ [ 1 = 1 ] ; echo $?
0
$ [ 1 = 2 ] ; echo $?
1
[注意] 注意

シェルの論理的な観点では、成功は、0(ゼロ)の値を持つ論理的として扱われることに注意してください。少々これは非直感的なのでここで再確認する必要があります。

1.5.5. 典型的なコマンドシーケンスとシェルリディレクション

次に挙げるシェルコマンドの慣用句を覚えてみましょう。

表1.23 シェルコマンドの慣用句。

コマンドの慣用句(1行入力) 説明
command & commandバックグラウンドでサブシェルの中で実行されます。
command1 | command2 command1の標準出力がcommand2の標準入力に継ぎ込まれます。両方のコマンドが同時進行で実行されるかもしれません。
command1 2>&1 | command2 command1の標準出力と標準エラー出力がcommand2の標準入力に継ぎ込まれます。両方のコマンドが同時進行で実行されるかもしれません。
command1 ; command2 command1を実行し、後に続いてcommand2が実行されます。
command1 && command2 command1が実行されます。もし成功したら、後に続いてcommand2が実行されます。
command1 || command2 command1が実行されます。もし成功しなかったら、後に続いてcommand2が実行されます。command1 command2のどちらかが正常終了した場合に正常終了を返します。
command > foo commandの標準出力をfooファイルにリダイレクト (上書き) します。
command 2> foo commandの標準エラー出力をfooファイルにリダイレクト (上書き) します。
command >> foo commandの標準出力をfooファイルにリダイレクト (追記) します。
command 2>> foo commandの標準エラー出力をfooファイルにリダイレクト (追記) します。
command > foo 2>&1 commandの標準出力と標準エラー出力をfooファイルにリダイレクトします。
command < foo commandの標準入力をfooファイルからリダイレクトします。
command << delimiter commandの標準入力を"終端文字列"に出会うまでのこれに続く行からリダイレクトします。(ヒアドキュメント)
command <<- 終端文字列 commandの標準入力を"終端文字列"に出会うまでのこれに続く行からリダイレクトします。行頭のタブ文字は入力から落とされます。(ヒアドキュメント)

Debianシステムはマルチタスクシステムです。バックグラウンドジョブを使うと単一シェルの下で複数プログラムを実行可能にします。バックグラウンドジョブの管理にはシェル内部組み込みコマンドのjobsfgbgkillを使います。bash(1)マンページ中の"SIGNALS"と"JOB CONTROL"セクションやbuiltins(1)を参照下さい。

リディレクションの簡単な例を試してみましょう:

$ </etc/motd pager
$ pager </etc/motd
$ pager /etc/motd
$ cat /etc/motd | pager

4つ全ての例が全く同じ表示をしますが、最後の例は余計なcatコマンドを実行するので理由なくリソースの無駄遣いをします。

シェルではexec組み込みコマンドを任意のファイルディスクリプタとともに使いファイルをオープンすることができます。

$ echo Hello >foo
$ exec 3<foo 4>bar  # open files
$ cat <&3 >&4       # redirect stdin to 3, stdout to 4
$ exec 3<&- 4>&-    # close files
$ cat bar
Hello

上記で、"n<&-"と"n>&-" はファイルディスクリプタ"n"をクローズするという意味です。

ファイルデスクリプタの0-2は事前定義されています。

表1.24 事前定義されたファイルデスクリプタ

デバイス 説明 ファイルデスクリプタ
stdin 標準出力 0
stdout 標準出力 1
stderr 標準エラー出力 2

1.5.6. コマンドエリアス

良く使うコマンドにエイリアスを設定できます。例えば:

$ alias la='ls -la'

こうすると、"la"が"ls -la"の短縮形として機能し、全てのファイルを長いリスト形式でリストします。

既存の全エアリアスは次のようにするとリストできます:

$ alias

type内部コマンドを使うと正確なパスやコマンドの正体を識別できます。例えば:

$ type ls
ls is hashed (/bin/ls)
$ type la
la is aliased to ls -la
$ type echo
echo is a shell builtin
$ type file
file is /usr/bin/file

上記で、lsは最近探索されましたが"file" は最近探索されていませので、"ls"は"ハッシュされた"つまりシェルには"ls"コマンドの場所を高速アクセスのために内部記録していると表示されます。

[ティップ] ティップ

「Colorized commands」参照下さい。

1.6. Unix的テキスト処理

Unix的作業環境では、テキスト処理はテキストを標準テキスト処理ツールの連鎖パイプを通す行います。これは決定的なUnixの発明です。

1.6.1. Unixテキストツール

Unix的システムでしばしば使われる標準テキスト処理ツールがいくつかあります。

  • 正規表現無使用:

    • cat(1)はファイルをつなぎ合わせ全てを出力します。
    • tac(1)はファイルをつなぎ合わせ逆順で出力します。
    • cut(1)は行の一部を選択し出力します。
    • head(1)はファイルの最初の部分を選択し出力します。
    • tail(1)はファイルの最後の部分を選択し出力します。
    • sort(1)は行を順番に並び替えます。
    • uniq(1)は順番に並べられたファイルから重複行を削除します。
    • tr(1)は文字を変換削除します。
    • diff(1)は1行ごとにファイルを比較します。
  • 基本正規表現(BRE)使用:

    • egrep(1)はテキストのパターンマッチをします。
    • ed(1)は原始的な行エディタ。
    • sed(1)はストリームエディタ。
    • vim(1)はスクリーンエディタ。
    • emacs(1)はスクリーンエディタ。(ちょっと拡張されたBRE)
  • 拡張正規表現(ERE)使用:

    • egrep(1)はテキストのパターンマッチをします。
    • awk(1)は単純なテキスト処理をします。
    • tcl(3tcl)は考え得る全てのテキスト処理をします:re_syntax(3)。時々tk(3tk)とともに使用されます。
    • perl(1)は考え得る全てのテキスト処理をします。perlre(1).
    • pcregrepパッケージのpcregrep(1) はテキストのパターンマッチをPerl互換正規表現(PCRE)パターンを使ってします。
    • reモジュールとともに使うことでpython(1)は考え得る全てのテキスト処理をします。"/usr/share/doc/python/html/index.html"参照下さい。

もしこれらのコマンドが正確にどう動作するかを確認したいなら、"man command"を使って自分で見つけましょう。

[注意] 注意

ソート順や範囲表現はロケールに依存します。コマンドの伝統的挙動を得たい際には、"LANG=C"をコマンドの前に付けてUTF-8ロケールではなくCロケールでコマンドを使いましょう。(「"$LANG"変数」「ロケール」を参照)。

[注意] 注意

Perl正規表現(perlre(1))とPerl互換正規表現(PCRE)reモジュールで提供されるPython正規表現はEREに多くの共通の拡張をしています。

1.6.2. 正規表現

正規表現は多くのテキスト処理ツールで使われています。シェルグロブに類似していますがより複雑で強力です。

正規表現はマッチするパターンを表現し、テキスト文字とメタ文字からなっています。

メタ文字は特別な意味を持った文字です。上記のようにテキストツールによって、BREEREの2つの主要なスタイルがあります。

表1.25 BREとEREのメタ文字。

BRE ERE 正規表現の意味
\ . [ ] ^ $ * \ . [ ] ^ $ * 共通のメタ文字
\+ \? \( \) \{ \} \|   "\"でエスケープされた、BREのみで用いるメタ文字
  + ? ( ) { } | "\"でエスケープされ無い、EREのみで用いるメタ文字
c c 非メタ文字 "c"をマッチします。
\c \c 当該シーケンスは、c"自身がメタ文字でも"c"というそのままの文字とマッチします。
. . 改行を含めた如何なる文字ともマッチします。
^ ^ 文字列の最初とマッチします。
$ $ 文字列の最後とマッチします。
\< \< 単語先頭とマッチします。
\> \> 単語末尾とマッチします。
\[abc…\] [abc…] この文字リストは"abc…"のいずれかの文字にマッチします。
\[^abc…\] [^abc…] この否定の文字リストは"abc…"以外の文字にマッチします。
r* r* "r"という正規表現の0回以上にマッチ。
r\+ r+ "r"という正規表現の1回以上にマッチ。
r\? r? "r"という正規表現の0回か1回にマッチ。
r1\|r2 r1|r2 "r1"か"r2"という正規表現のいずれかにマッチ。
\(r1\|r2\) (r1|r2) "r1"か"r2"という正規表現のいずれかにマッチし、それを括弧で囲まれた正規表現として扱う。

emacsの正規表現は、ERE同様の"+"と"?"をメタ文字と扱う拡張をしてはありますが、基本的にBREです。これら文字をemacsの正規表現で"\"でエスケープする必要はありません。

例えば、grep(1)をつかうと正規表現を使って文字列探索ができます:

$ egrep 'GNU.*LICENSE|Yoyodyne' /usr/share/common-licenses/GPL
GNU GENERAL PUBLIC LICENSE
GNU GENERAL PUBLIC LICENSE
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
[ティップ] ティップ

「Colorized commands」参照下さい。

1.6.3. 置換表現

置換表現の場合、次の文字には特別な意味があります

表1.26 置換表現

文字 意味
& 正規表現がマッチしたものを示す。(emacsでは\&を使用)
\n n番目の括弧で囲まれた正規表現にマッチしたものを示す。("n" は数字)

Perlの置換表現では、"\n"の代わりに"$n"をつかい、"&"には特段の意味はありません。

例えば:

$ echo zzz1abc2efg3hij4 | \
sed -e 's/\(1[a-z]*\)[0-9]*\(.*\)$/=&=/'
zzz=1abc2efg3hij4=
$ echo zzz1abc2efg3hij4 | \
sed -e 's/\(1[a-z]*\)[0-9]*\(.*\)$/\2===\1/'
zzzefg3hij4===1abc
$ echo zzz1abc2efg3hij4 | \
perl -pe 's/(1[a-z]*)[0-9]*(.*)$/$2===$1/'
zzzefg3hij4===1abc
$ echo zzz1abc2efg3hij4 | \
perl -pe 's/(1[a-z]*)[0-9]*(.*)$/=&=/'
zzz=&=

ここで、括弧で囲まれた正規表現のスタイルと、マッチした文字列が異なるツール上でテキスト置換処理にどう使われるかとに注目下さい。

これらの正規表現は一部エディタ内でカーソルの動きやテキスト置換アクションに対しても使えます。

シェルコマンドラインの行末のバックスラッシュ"\"は改行をホワイトスペース文字としてエスケープするので、シェルコマンドライン入力を次行に継続させます。

これらのコマンドを習うために、関連するマニュアルページを全て読んでください。

1.6.4. 正規表現を使ったグローバル置換

ed(1)コマンドは次のようにすると"file"中に存在する全ての"FROM_REGEX"を"TO_TEXT"で置換する:

$ ed file <<EOF
,s/FROM_REGEX/TO_TEXT/g
w
q
EOF

vim(1)コマンドはex(1)コマンドを使い次のようにすると"file"中に存在する全ての"FROM_REGEX"を"TO_TEXT"で置換する:

$ vim '+%s/FROM_REGEX/TO_TEXT/gc' '+w' '+q' file
[ティップ] ティップ

上記の"c"フラグをにより各置換毎に対話型の確認をします。

複数ファイル("file1"と"file2"と"file3")をvim(1)やperl(1)で同様に正規表現を用いて処理できます:

$ vim '+argdo %s/FROM_REGEX/TO_TEXT/ge|update' '+q' file1 file2 file3
[ティップ] ティップ

上記の"e"フラグをにより"No match"エラーでマッピングが停止することを防ぎます。

$ perl -i -p -e 's/FROM_REGEX/TO_TEXT/g;' file1 file2 file3

perl(1)の例中で、"-i"はその場での編集、"-p"はファイルに関する暗黙的なループを意味します。

[ティップ] ティップ

"-i"の代わりに"-i.bak"という引数を用いるとオリジナルファイル名に".bak"をつけたファイル名でオリジナルファイルが保管されます。複雑な置換のエラーからの復帰が簡単にできます。

[注意] 注意

ed(1)やvim(1)はBREですが、perl(1)はEREです。

1.6.5. テキストファイルからのデータ抽出

2004年以前の元Debianリーダの名前と就任日がスペースで分割されたフォーマットでリストされている"DPL"と呼ばれるファイルを考えてみましょう。

Ian     Murdock   August  1993
Bruce   Perens    April   1996
Ian     Jackson   January 1998
Wichert Akkerman  January 1999
Ben     Collins   April   2001
Bdale   Garbee    April   2002
Martin  Michlmayr March   2003
[ティップ] ティップ

最新のDebianのリーダーの歴史に関しては、"A Brief History of Debian"を参照下さい。

こういったタイプのファイルからデータを抽出するのはAwk が良く使われます:

$ awk '{ print $3 }' <DPL                   # month started
August
April
January
January
April
April
March
$ awk '($1=="Ian") { print }' <DPL          # DPL called Ian
Ian     Murdock   August  1993
Ian     Jackson   January 1998
$ awk '($2=="Perens") { print $3,$4 }' <DPL # When Perens started
April 1996

Bash などのシェルもこれらのファイルを解釈するのに使えます:

$ while read first last month year; do
    echo $month
  done <DPL
  • 最初の Awk の例と同じ出力。

ここで、read組込みコマンドは"$IFS"(内部フィールドセパレータ) を用いて行を単語単位で分割します。

"$IFS"を":"に変更すると、"/etc/passwd"をシェルでうまく解読できます:

$ oldIFS="$IFS"   # save old value
$ IFS=':'
$ while read user password uid gid rest_of_line; do
    if [ "$user" = "bozo" ]; then
      echo "$user's ID is $uid"
    fi
  done < /etc/passwd
bozo's ID is 1000
$ IFS="$oldIFS"   # restore old value

(同じことを Awk を使って行うには、フィールドセパレータ設定は"FS=':'"としましょう。)

IFSはパラメータ展開、コマンド置換、数式展開の結果を分割するためにもシェルにより使われます。これはダブルクォートやシングルクォートされた単語内では発生しません。IFSの標準値は<space>と<tab>と<newline>の組合せです。

シェルのIFSトリックを注意深く使ってください。シェルがスクリプトの一部を入力として解釈した場合に、奇妙なことが起きるかもしれません。

$ IFS=":,"                        # use ":" and "," as IFS
$ echo IFS=$IFS,   IFS="$IFS"     # echo is a Bash builtin
IFS=  , IFS=:,
$ date -R                         # just a command output
Sat, 23 Aug 2003 08:30:15 +0200
$ echo $(date -R)                 # sub shell --> input to main shell
Sat  23 Aug 2003 08 30 36 +0200
$ unset IFS                       # reset IFS to the default
$ echo $(date -R)
Sat, 23 Aug 2003 08:30:50 +0200

1.6.6. コマンドをパイプするためのスクリプト断片

次のスクリプトはパイプの一部として素晴らしいことをします。

表1.27 コマンドをパイプするためのスクリプト断片のリスト。

スクリプト断片(1行入力) コマンドの効果
find /usr -print "$HOME"の値。
seq 1 100 1から100までプリント。
| xargs -n 1 <command> パイプからの各項目を引数としてコマンドを繰り返し実行します。
| xargs -n 1 echo パイプからのホワイトスペースで分離された項目を行に分割します。
| xargs echo パイプからの全ての行を1行にマージします。
| grep -e <regex_pattern> <regex_pattern>を含む行を取り出します。
| grep -v -e <regex_pattern> <regex_pattern>を含まない行を取り出します。
| cut -d: -f3 - ":"で区切られた3番目のフィールドを取り出します(passwdファイルなど)。
| awk '{ print $3 }' ホワイトスペースで区切られた3番目のフィールドを取り出します。
| awk -F'\t' '{ print $3 }' タブで区切られた3番目のフィールドを取り出します。
| col -bx バックスペースを削除し、タブをスベースに変換します。
| expand - タブをスベースに変換します。
| sort| uniq 入力をソートし重複箇所を削除します。
| tr 'A-Z' 'a-z' 大文字を小文字に変換します。
| tr -d '\n' 複数の行を1行につなげます。
| tr -d '\r' キャリッジリターンを削除します。
| sed 's/^/# /' 各行頭に"#"を追加します。
| sed 's/\.ext//g' ".ext"を削除します。
| sed -n -e 2p 2番目の行を表示します。
| head -n 2 - 最初の2行を表示します。
| tail -n 2 - 最後の2行を表示します。

1行のシェルスクリプトはfind(1)やxargs(1)を使って非常に複雑な操作を多くのファイルに繰り返し実行できます。「Idioms for the selection of files」「Repeating a command looping over files」を参照下さい。

シェルの対話モードを使うのが複雑過ぎるようになったときには、シェルのスクリプトを書くのも一計です(「シェルスクリプト」参照)。

第2章 Debianパッケージ管理

[注意] 注意

本章は最新安定版リリースがコード名:lennyと言う前提で書かれています。

Debianは、フリーソフトウエアのコンパイル済みバイナリパッケージからなる整合性あるディストリビューションを作り、そのアーカイブを通じてそれらを頒布するボランティア組織です。

Debianのアーカイブは、HTTPやFTP法によるアクセスされるための多くのリモートのミラーサイトとして提供されています。それは、CD-ROM/DVDによっても提供されています。

Debianのパッケージ管理システムは、適切に使われればバイナリパッケージの整合性ある組み合わせがアーカイブからシステムにインストールされるようになっています。現在、amd64アーキテクチャーには25441つのパッケージがあります。

Debianのパッケージ管理システムは、多彩な歴史があり、使用されるフロントエンドのユーザプログラムやバックエンドのアーカイブへのアクセス方法に多くの選択肢があります。現在はDebianのパッケージ管理活動のメインフロントエンドプログラムとしてaptitude(8)を推薦します。

表2.1 Debianのパッケージ管理ツールのリスト。

パッケージ popcon サイズ 説明
aptitude V:26, I:97 9832 ターミナルベースのパッケージマネージャ(現在の標準、aptのフロントエンド)
apt V:90, I:99 5128 アドバンスドパッケージツール(APT)、"http"や"ftp"や"file"というアーカイブへのアクセス方法をdpkgに提供するフロントエンド(apt-get/apt-cacheコマンドを含む)
tasksel V:7, I:93 900 Debianシステムにタスクをインストールするための選択ツール(APTのフロントエンド)
unattended-upgrades V:4, I:26 212 APTの拡張パッケージでセキュリティアップデートの自動インストールを可能にする
dselect V:4, I:57 2060 ターミナルベースのパッケージマネージャ(過去の標準、APTや他の古いアクセス法のフロントエンド)
dpkg V:91, I:99 6864 Debianのためのパッケージ管理システム
dpkg-ftp V:0.08, I:0.5 136 dselectのための古いftp
synaptic V:20, I:48 6104 グラフィカルなパッケージマネージャ(APTのGNOMEフロントエンド)
gnome-apt V:0.3, I:1.9 NOT_FOUND グラフィカルなパッケージマネージャ(APTのGNOMEフロントエンド)
kpackage V:5, I:14 1064 グラフィカルなパッケージマネージャ(APTのKDEフロントエンド)
apt-utils V:52, I:99 460 APTユーティリティプログラム: apt-extracttemplates(1)とapt-ftparchive(1)とapt-sortpkgs(1)
apt-listchanges V:3, I:6 264 パッケージ変更履歴の通知ツール
apt-listbugs V:1.4, I:2 436 APTによる各インストール前にクリチカルバグをリストする
apt-file V:2, I:9 172 APTパッケージ探索ユーティリティ -- コマンドラインインターフェース
apt-rdepends V:0.16, I:0.9 92 パッケージの依存関係を再帰的にリスト

[注意] 注意

aptitudeapt-getコマンドの両方を混用する際に迷惑だったバグ #411123は解決されました。もし本件のためにaptitude(8)を使うことに躊躇しているなら、御再考下さい。

2.1. Debainパッケージ管理の前提条件

2.1.1. パッケージ設定

Debianシステム上でのパッケージ設定の要点は次です:

  • システム管理者による手動の設定は尊重されます。言い換えれば、パッケージ設定システムは利便性のために勝手な設定をしません。
  • 各パッケージは、パッケージ導入プロセスを助けるためのdebconf(7)と呼ばれる標準化されたユーザインターフェースを使用し、それぞれ毎の設定スクリプトとともに提供されます。
  • Debianの開発者はパッケージの設定スクリプトによりユーザのアップグレードが滞りなく進むように最大限の努力を行います。
  • システム管理者にはパッケージされたソフトウエアの全機能が使用可能です。ただしセキュリティリスクのある機能はデフォルトのインストール状態では無効にされています。
  • セキュリティリスクのあるサービスを手動でアクティベートした場合は、リスクの封じ込めはあなたの責任です。
  • システム管理者は難解奇異な設定を手動で有効にできます。ただこんなことをすればポピュラーな一般の補助プログラムとは干渉してしまうかもしれません。

2.1.2. 基本的な注意事項

[警告] 警告

ランダムな混合のスイーツからパッケージを導入してはいけません。コンパイラーのABIとかライブラリー のバージョンとかインタープリターの機能等のシステム管理に関する深い知見が必要なパッケージの整合性がきっと破壊されます。

初心者のDebianシステム管理者はDebianの安定版stableリリースをセキュリティアップデートを適用しながら使うべきです。Debianシステムを非常によく理解するまでは、用心として次の有効なアクションですら避けておくべきと考えます:

  • "/etc/apt/sources.list"の中にテスト版testingとか不安定版unstableとかを含めないようにします。
  • "/etc/apt/sources.list"の中に標準のDebianとDebian以外のUbuntuのようなアーカイブを混在させない、
  • "/etc/apt/preferences"を作成しない。
  • パッケージ管理ツールのデフォルトを影響を理解せずに変更しない。
  • ランダムなパッケージを"dpkg -i <random_package>"でインストールしない。
  • ランダムなパッケージを"dpkg --force-all -i <random_package>"で絶対インストールしない。
  • "/var/lib/dpkg/"の中のファイルを消去や改変しない。
  • ソースから直接コンパイルしたソフトウエアプログラムをインストールする際にシステムファイルを上書きしない。(こういったソフトウエアプログラムは"/usr/local"か"/opt"の中にインストールしましょう。)

上記のアクションで起きるDebianパッケージシステムへのコンパチブルでない効果はシステムを使えなくするかもしれません。

ミッションクリティカルなサーバーを走らせる真剣なDebianシステム管理者は更なる用心をすべきです:

  • 安全な条件下であなたの特定の設定で徹底的にテストすることなくセキュリティアップデートをも含めた如何なるパッケージもインストールをしてはいけません。(Debianは非常に安定なシステムを長期間提供し続けてきているとは言え、最終的にはあなたのシステムへの責任はシステム管理者であるあなた自身が負っています。)

2.1.3. 永遠のアップグレード人生

私が上記で警告したとはいえ、自分自身で管理するデスクトップ環境ではDebianのテスト版testingや不安定版unstableのスイーツを自分のメインのシステムとして使おうと多くの本書の読者が望むことは分かっています。システムは非常に快調に動くし、頻繁に更新されるし、最新の機能が提供されるからです。

[注意] 注意

あなたの業務サーバーには、セキュリティアップデートをした安定版stableスイーツを推薦します。例えばあなたの母親のPCのように、管理に限られた時間しか割けないデスクトップPCに関しても同様の事が言えます。

"/etc/apt/sources.list"の中のディストリビューション文字列を、"testing"とか"unstable"というスイーツ名、もしくは"squeezeとか"sid"というコード名に単に設定するだけで十分です。

testingunstableを使うことは大変楽しいけれど、リスクがついてきます。Debianシステムのunstableスイーツさえおおむね非常に安定に見えますが、Debianシステムのtestingunstableスイーツでは過去パッケージ上の問題をいくつか経験して来てるし、その一部は簡単には解決できないものでした。結構痛い目に会うことになるかもしれませんよ。時々、壊れたパッケージや機能の欠損が数週間続くことが起こります。

Debianパッケージのバグからの早急かつ簡単な回復を確実にするいくつかのアイデアがここにあります:

  • Debianシステムの安定版stableスイーツを別のパーティションにインストールし、システムをヂュアルブータブルにします。
  • レスキューブートのためのインストール用CDを手元に置いておく。
  • apt-listbugsをインストールしてアップグレードの前にDebianバグトラッキングシステム(BTS)をチェックすることを考る。
  • 問題回避するのに十分なだけのパッケージシステムの基盤を学ぶ。
  • chrootか類似の環境を作り事前に最新のシステムを実行します。(任意)

(これらの用心のための方策の何れもできないなら、テスト版testingや不安定版unstableスイーツを使うのにはあなたはきっと準備不足です。)

以下に記すことにより悟りを開けば、アップグレード地獄という果てしない因果応報の葛藤から人は解脱し、Debianの涅槃の境地に到達できます。

2.1.4. Debianアーカイブの基本

Debianアーカイブをシステムユーザの視点から見てみましょう。

[ティップ] ティップ

Debianアーカイブの正式のポリシーはDebianポリシーマニュアル、第2章 - Debianアーカイブに規定されています。

典型的なHTTPアクセスの場合、現在の安定版stable=lennyシステムを例にとると"/etc/apt/sources.list"ファイルの中にアーカイブは次の様に規定されています。

deb http://ftp.XX.debian.org/debian/ lenny main contrib non-free
deb-src http://ftp.XX.debian.org/debian/ lenny main contrib non-free

deb http://security.debian.org/ lenny/updates main contrib
deb-src http://security.debian.org/ lenny/updates main contrib

"ftp.XX.debian.org"はあなたの所在場所に合う、Debianの全世界ミラーサイトリスト中に見つかるミラーサイトのURL、例えば日本なら "ftp.jp.debian.org"、に置き換えなければいけません。これらのサーバーの状況はDebianミラー確認サイトで確認できます。

上記で、次の安定版stableがリリースされて驚かされ無いように、私はスイート名の"stable"でなくコード名の"lenny"を使います。

"/etc/apt/sources.list"の意味はsources.list(5)に記載されていて、要点は:

  • "deb"行がバイナリパッケージのための定義です。
  • "deb-src"行がソースパッケージのための定義です。
  • 一番目の引数は、Debianアーカイブのroot URLです。
  • 二番目の引数は、スイーツ名かコード名のどちらかで与えられるディストリビューション名です。
  • 三番目次の引数は、Debianアーカイブの中の有効なアーカイブのコンポーネント名のリストです。

ソース関連のメタデータにアクセスしないaptitudeのためだけなら"deb-src"行は安全に省略(もしくは"#"を行頭に挿入してコメントアウト)することができます。こうするとアーカイブのメタデータの更新速度が向上します。URLは"http://"や"ftp://"や"file://"等々の何れも可能です。

[ティップ] ティップ

もし上記の例で"lenny"ではなく"sid"が使われる場合には、セキュリティアップデートのための"deb: http://security.debian.org/ ..."行は不要です。安定版stableとテスト版testing(即ちlennysqueeze)にのみセキュリティアップデートがあります。

次は設定ファイル内に用いられるDebianアーカイブサイトのURLとスイーツ名もしくはコード名です。

表2.2 Debianアーカイブサイトのリスト。

アーカイブのURL スイート名(コード名) 目的
http://ftp.XX.debian.org/debian/ stable (lenny) 安定版(lenny)のリリース
http://ftp.XX.debian.org/debian/ testing (squeeze) テスト版(squeeze)のリリース
http://ftp.XX.debian.org/debian/ unstable (sid) 不安定版(sid)のリリース
http://ftp.XX.debian.org/debian/ experimental 実験的プリリリース(任意、開発者専用)
http://ftp.XX.debian.org/debian/ stable-proposed-updates 次回安定版ポイントリリース用のアップデート(任意)
http://security.debian.org/ stable/updates 安定版用のセキュリティアップデート(重要)
http://security.debian.org/ testing/updates テスト版用のセキュリティアップデート(重要)
http://volatile.debian.org/debian-volatile/ volatile スパムフィルタやIMクライアント他用のコンパチブルなアップデート
http://volatile.debian.org/debian-volatile/ volatile-sloppy スパムフィルタやIMクライアント他用のノンコンパチブルなアップデート
http://backports.org/debian/ lenny-backports lennyのためのバックポートされたパッケージ。(非正規、任意)

[注意] 注意

セキュリティアップデートされた純粋な安定版stableリリースのみが最善の安定性を提供します。一部testingunstable由来のパッケージを混用してほとんどstableリリースを走らせることは、純粋なunstableリリースを走らせるよりリスクがあります。stableリリースの下で最新バージョンのいくつかのプログラムが本当に必要なら、debian-volatileプロジェクトbackports.org(「VolatileとBackports.org」参照)サービスからのパッケージを使って下さい。これらのサービスは細心の注意を持って使う必要があります。

[注意] 注意

基本的に、stabletestingunstableのスイーツの内の1つだけを"deb"行に書くべきです。もし、stabletestingunstableのスイーツの何らかの組み合わせを"deb"行に書けば、APTプログラムは、最新のアーカイブのみが有効であるにもかかわらず、実行速度が低下します。"/etc/apt/preferences"ファイルがはっきりとした目的を持って使われている場合(「候補バージョンの調整」)のみ複数のリストに意味があります。

[注意] 注意

stabletestingスイーツのDebianシステムでは、上記の例のようにセキュリティアップデートを有効とするように"/etc/apt/sources.list"の中に"http://security.debian.org/"の行を含めることはいいことです。

各Debianアーカイブは3つのコンポーネントから成り立っています。コンポーネントには"Debianポリシー"ではカテゴリとか"Debian社会契約"ではエリアという別名が使われています。コンポーネントは"Debianフリーソフトウエアガイドライン" (DFSG)に準拠しているかどうかによって分類されています。

表2.3 Debianアーカイブコンポーネントのリスト。

コンポーネント パッケージ数 クライテリア
main 24828 パッケージはDSFGに完全準拠し、non-freeのパッケージに依存していない。(main=主要)
contrib 207 パッケージはDSFGに完全準拠するが、non-freeのパッケージに依存しています。(contrib=寄与)
non-free 406 パッケージはDSFGに完全には準拠しないが、頒布可能で有用です。(non-free=非自由)

ここで、上記にあるパッケージ数はamd64アーキテクチャーに関する数字である。厳密に言うなら、mainコンポーネントのアーカイブのみをDebianシステムと考えるべきです。

Debianアーカイブの構成は、各アーカイブのURLの後ろにdistspoolをつけたURLにブラウザを向ければ学習できます。

ディストリビューションは、スイーツとコード名の2つの方法で言及されます。この他にディストリビューションと言う言葉は多くの文書でスイーツの同義語としても使われています。スイーツとコード名の関係は次のようにまとめられます:

表2.4 スイーツとコード名の関係。

タイミング スイーツ = 安定版 stable スイーツ = テスト版 testing スイーツ = 不安定版 unstable
lennyリリース後 コード名 = lenny コード名 = squeeze コード名 = sid
squeezeリリース後 コード名 = squeeze コード名 = squeeze+1 コード名 = sid

コード名の歴史は、Debian FAQ: 6.3.1 Which other codenames have been used in the past?に記載されています。

比較的厳格なDebianアーカイブの用語法では、"セクション"という言葉はアプリケーションの分野によるパッケージ分類に特化して使われます。(しかし、"mainセクション"という言葉はmainコンポーネントを提供するDebianアーカイブ部分を表現するのにしばしば使われています。)

Debianデベロッパー(DD)が不安定版unstableアーカイブに新たなアップロードを(incomingでの処理を経由して)する度毎に、アップロードするパッケージが最新の不安定版unstableアーカイブの最新のパッケージ集合とコンパチブルであるようにする義務がDDにはあります。

重要なライブラリーのアップグレード他の理由でDDがこのコンパチビリティーを壊す際には、debian-develのメーリングリスト他に通常アナウンスがされます。

Debianのアーカイブ管理スクリプトによって非安定版unstableアーカイブからテスト版testingアーカイブへパッケージ集合が移動される前に、アーカイブ管理スクリプトはパッケージの成熟度(約10日経過)とRCバグレポート状況を確認するばかりでなく、テスト版testingアーカイブの最新パッケージ集合とのコンパチブルであるようにするように努めます。このプロセスがあるので、テスト版testingアーカイブは非常に新しくかつ使いやすいのです。

リリースチームによる徐々のアーカイブ凍結過程を通じて、少々の手動の介入を伴いつつテスト版testingアーカイブは完全に整合性をもったバグの無い状態へと徐々に熟成されます。そして、古いテスト版testingアーカイブのコード名を新たな安定版stableアーカイブへと割り当て、新たなコード名を新たなテスト版testingアーカイブへと割り当てることで、新たな安定版stableがリリースされます。新たなテスト版testingアーカイブの当初の内容は、新たにリリースされた安定版stableアーカイブとまったく同じです。

不安定版unstableもテスト版testingアーカイブもともに一時的に次のような理由で細かな問題発生があるかもしれません:

  • ブロークンなパッケージのアーカイブへのアップロード(主にunstableにて)。
  • 新たなパッケージをアーカイブに受け入れる際の遅れ(主にunstableにて)。
  • アーカイブの同期のタイミング問題(testingunstableの両方にて)。
  • パッケージの除去などのアーカイブへの手動の介入(どちらかといえばtestingにて)、等。

もしこれらのアーカイブを使おうと考えるなら、この種の細かな問題の修復や回避は必須技能です。

[注意] 注意

たとえいつも非安定版unstableやテスト版testingアーカイブを使っていようとも、ほとんどのデスクトップユーザは新たな安定版stableリリースの後約数ヶ月はセキュリティアップデートされた安定版stableアーカイブを使うべきです。この移行期は、非安定版unstableもテスト版testingアーカイブの何れももほとんどの人に良いものではありません。非安定版unstableアーカイブを使おうとすると、核となるパッケージが大アップグレードの嵐に見舞われるので、あなたのシステムをうまく使える状態に保つのは困難です。テスト版testingアーカイブを使おうとしても、安定版stableアーカイブとほとんど同じ内容でセキュリティサポートはありません(Debian testing-security-announce 2008-12)。1ヶ月ほど経てば、非安定版unstableアーカイブなら注意を払えば使えるかもしれません。

[ティップ] ティップ

テスト版testingアーカイブを追跡している際には、除去されたパッケージによって引き起こされる問題は該当するバグ修正のためにアップロードされたパッケージを非安定版unstableアーカイブからインストールすれば通常回避できます。

次の定義はDebianポリシーマニュアル参照:

2.1.5. パッケージ依存関係

Debianシステムはコントロールファイル中のバージョン情報付きのバイナリ依存関係宣言を通して整合性のあるバイナリパッケージの集合を提供します。ここにその少々簡素化しすぎの定義を示します。

表2.5 パッケージ依存関係のリスト。

パッケージ依存関係 意味
Depends これは絶対依存を宣言し、このフィールドにリストされた全てのパッケージは同時または事前にインストールされていなければいけません。
Pre-Depends これは、リストされたパッケージが事前にインストールを完了している必要がある以外は、Dependsと同様です。
Recommends これは強いが絶対でない依存を宣言します。多くのユーザはこのフィールドにリストされたパッケージ全てが導入されていなければ、当該パッケージを望まないでしょう。
Suggests これは弱い依存を宣言します。このパッケージの多くのユーザはこのフィールドにリストされたパッケージを導入すればメリットを享受できるとは言え、それら抜きでも十分な機能が得られます。
Enhances これはSuggests同様の弱い依存を宣言しますが、依存作用の方向が逆です。
Conflicts これは絶対的排他関係を宣言します。このフィールドにリストされた全てのパッケージを除去しない限り当該パッケージを導入できません。
Replaces 当該パッケージによりインストールされるファイルがこのフィールドにリストされたパッケージのファイルを置き換える際にこれを宣言します。
Provides 当該パッケージがこのフィールドにリストされたパッケージのファイルと機能の全てを提供する際にこれを宣言します。

[注意] 注意

正常な設定としてProvidesとConflictsとReplacesとを単一バーチャルパッケージに対し同時宣言することがあります。こうするといかなる時にも当該バーチャルパッケージを提供する実パッケージのうち確実に一つだけがインストールされます。

ソースの依存関係をも含む正式の定義はthe Policy Manual: Chapter 7 - Declaring relationships between packagesにあります。

2.1.6. パッケージ管理のイベントの流れ

パッケージ管理の簡略化されたイベントの流れをまとめると次のようになります。

  • 更新 ("aptitude update"か"apt-get update"):

    1. アーカイブメタデータをリモートアーカイブから取得。
    2. APTが使えるようローカルメタデータを再構築し更新。
  • アップグレード("aptitude safe-upgrade"と"aptitude full-upgrade"か、"apt-get upgrade"と"apt-get dist-upgrade"):

    1. APTシステムは最新バージョンが普通選ばれる候補バージョンを全てのインストール済みパッケージに関して決定します。(例外については「候補バージョンの調整」参照。)
    2. パッケージ依存関係の解決。
    3. もし候補バージョンがインストール済みバージョンとことなる際には、選ばれたバイナリパッケージをリモートアーカイブから取得。
    4. 取得バイナリパッケージの開梱。
    5. preinstスクリプトの実行
    6. バイナリファイルのインストール。
    7. postinstスクリプトの実行。
  • インストール ("aptitude install ..."か"apt-get install ..."):

    1. コマンドラインにリストされたパッケージの選択。
    2. パッケージ依存関係の解決。
    3. 選ばれたバイナリパッケージをリモートアーカイブから取得。
    4. 取得バイナリパッケージの開梱。
    5. preinstスクリプトの実行
    6. バイナリファイルのインストール。
    7. postinstスクリプトの実行。
  • 削除 ("aptitude remove ..."か"apt-get remove ..."):

    1. コマンドラインにリストされたパッケージの選択。
    2. パッケージ依存関係の解決。
    3. prermスクリプトの実行
    4. 設定ファイル以外のインストール済みファイルの削除。
    5. postrmスクリプトの実行。
  • 完全削除 ("aptitude purge ..."か"apt-get purge ..."):

    1. コマンドラインにリストされたパッケージの選択。
    2. パッケージ依存関係の解決。
    3. prermスクリプトの実行
    4. 設定ファイルを含めた インストール済みファイルの削除。
    5. postrmスクリプトの実行。

上記では全体像の理解のためにわざと技術詳細を端折っています。

2.1.7. パッケージ管理のトラブルへの応急対処法

内容が正確な正式文書を読むように心がけるべきです。まずDebianに特定のことが記載された"/usr/share/doc/<package_name>/README.Debian"を最初に読むべきです。また"/usr/share/doc/<package_name>/"の中にある他の文書も参照すべきです。「Bashのカスタム化」に書かれたようなシェル設定がされていれば、次のようにタイプしてください。

$ cd <package_name>
$ pager README.Debian
$ mc

さらに詳しい情報を得るには"-doc"というサフィックスを持った対応する文書パッケージをインストールする必要があるかもしれません。

特定のパッケージで問題を経験した際には、次のサイトを確認してください。

表2.6 特定パッケージの問題解決のためのキーとなるウエッブサイトのリスト。

サイト コマンド
Debianバグトラッキングシステム(BTS)のホームページ。 sensible-browser "http://bugs.debian.org/"
既知のパッケージに関するバグレポート。 sensible-browser "http://bugs.debian.org/<package_name>"
既知のバグ番号に関するバグレポート。 sensible-browser "http://bugs.debian.org/<bug_number>"

"site:debian.org"や"site:wiki.debian.org"や"site:lists.debian.org"等を含む検索語でGoogleを検索します。

バグ報告をする際には、reportbug(1)コマンドを使いましょう。

2.2. 基本的パッケージ管理操作

AptitudeはDebianシステムで現在推薦されるパッケージ管理ツールです。apt-get / apt-cacheをコマンドラインで代替もしますし、またフルスクリーンのインタラクティブなパッケージ管理ツールとしても使えます。

パッケージをインストールしたりパッケージのメタデータを更新するようなパッケージ管理操作にはroot権限が必要です。

2.2.1. コマンドラインによる基本的なパッケージ管理操作

aptitude(8)やapt-get(8) /apt-cache(8)を使うコマンドラインによるパッケージ管理操作を次に記します。

表2.7 aptitudeapt-get /apt-cacheを使うコマンドラインによるパッケージ管理操作

aptitudeシンタックス apt-get/apt-cacheシンタックス 説明
aptitude update apt-get update アーカイブメタデータの更新。
aptitude install foo apt-get install foo "foo"パッケージの候補バージョンをその依存関係とともにインストールします。
aptitude safe-upgrade apt-get upgrade 他のパッケージを削除すること無くインストール済みパッケージの候補バージョンをインストールします。
aptitude full-upgrade apt-get dist-upgrade <パッケージ> 必要なら他のパッケージを削除しながらインストール済みパッケージの候補バージョンをインストールします。
aptitude remove foo apt-get remove foo 設定ファイルを残したまま"foo"パッケージを削除します。
N/A apt-get autoremove 既に必要なくなっている自動済みパッケージを削除します。
aptitude purge foo apt-get purge foo 設定ファイルを含めて"foo"パッケージを完全削除します。
aptitude clean apt-get clean 収集されローカルに貯蔵されたパッケージファイルを完全に消去します。
aptitude autoclean apt-get autoclean 収集されローカルに貯蔵されたパッケージファイルのうち古くなったパッケージを消去します。
aptitude show foo apt-cache show <パッケージ> "foo"パッケージに関する詳細情報を表示します。
aptitude search <regex> apt-cache search <regex> <regex>とマッチするパッケージを探す。
aptitude why <regex> N/A なぜ<regex>とマッチするパッケージがインストールされるのかを説明します。
aptitude why-not <regex> N/A なぜ<regex>とマッチするパッケージがインストールされないのかを説明します。

Debianシステム上の異なったパッケージツールを混用しても問題が起こらなくなりましたが、できるだけaptitudeを使い続けるのが最善です。

"safe-upgrade"/"upgrade"や"full-upgrade"/"dist-upgrade"の違いは新しいバージョンのパッケージが該当する古いバージョンと異なった依存関係がある場合にのみ起こります。"aptitude safe-upgrade"コマンドは新規のパッケージをインストールも削除もしません。

"aptitude why <regex>"は"aptitude -v why <regex>"とすることでさらに詳しい情報を表示します。同様の情報は"apt-cache rdepends <package>"とすることでも得られます。

aptitudeコマンドが最初コマンドラインモードで実行されパッケージ間のコンフリクトのような問題に直面した場合は、プロンプトがでた際に"e"を押すことでフルスクリーンのインタラクティブモードに切り替えられます。

"aptitude"のすぐ後ろにコマンドオプションをつけられます。

表2.8 aptitude(8)に関する特記すべきコマンドオプション。

コマンドオプション 説明
-s コマンド結果のシミュレートをします。
-d インストール/アップグレードをせずにダウンロードだけします。
-D 自動的なインストールや削除の前に簡単な説明を表示します。

詳細はaptitude(8)や"/usr/share/doc/aptitude/README"にある"aptitude user's manual"を参照してください。

[ティップ] ティップ

現在でも存続しているdselectパッケージは、過去のリリースでは推薦されたフルスクリーンのインタラクティブなパッケージ管理ツールでした。

2.2.2. aptitudeのインタラクティブな使用

インタラクティブなパッケージ管理のためにはaptitudeをコンソールのシェルからインタラクティブモードで次のように立ち上げます。

$ sudo aptitude -u
Password:

これによりアーカイブ情報のローカルコピーは更新され、フルスクリーンのパッケージリストがメニュー付きで表示されます。Aptitudeの設定ファイルは"~/.aptitude/config"にあります。

[ティップ] ティップ

userの設定ファイルでなくrootの設定ファイルを使いたい際には、上記の例で"sudo aptitude ..."の代わりに"sudo -H aptitude ..."を使いましょう。

[ティップ] ティップ

Aptitudeはインタラクティブに起動されると次にするアクションを自動的に設定します。その設定が好ましくない場合はメニュー:"Action" → "Cancel pending actions"からリセットすることができます。

2.2.3. aptitudeのキーバインディング

パッケージの状態を閲覧し、"予定のアクション"の設定をこのフルスクリーンモードで各パッケージするための重要なキーは次です:

表2.9 aptitudeのキーバインディングのリスト。

キー キーバインディング
F10もしくくはCtrl-t メニュー
? (より詳細な)キーの意味のヘルプの表示
F10 → ヘルプ → ユーザマニュアル ユーザマニュアルの表示
u パッケージアーカイブ情報の更新
+ パッケージをアップグレードまたはインストールするとマークします。
- パッケージを削除するとマークします。(設定ファイルは温存)
_ パッケージを完全削除するとマークします。(設定ファイルも削除)
= パッケージをホールドします。
U 全てのアップグレード可能なパッケージをマークします。(full-upgradeとして機能)
g 選ばれたパッケージのダウンロードインストールを開始します。
q 現在のスクリーンを終了し変更を保存します。
x 現在のスクリーンを終了し変更を廃棄します。
Enter パッケージに関する情報閲覧します。
C パッケージの変更履歴の閲覧します。
l 表示されるパッケージの制限を変更します。
/ 最初のマッチを検索します。
\ 最近の検索を繰り返す。

コマンドラインのファイル名の規定や、"l"や"/"を押した後のメニュープロンプトは次に記すaptitudeのregex(正規表現)が使われます。aptitudeのregexは"~n"で始めそれにパッケージ名を続けた文字列を使うことで明示的にパッケージ名とマッチさせられます。

[ティップ] ティップ

ビジュアルインターフェースで全てのインストール済みパッケージを候補バージョンにアップグレードさせるには"U"を押さなければいけません。これをしないと選ばれたパッケージとそれにバージョン付きの依存関係のある特定のパッケージのみがアップグレードされます。

2.2.4. aptitudeの下でのパッケージの表示

インタラクティブなフルスクリーンモードのaptitude(8)は次のようなデフォルトのパッケージリスト形式でパッケージを表示します。

idA   libsmbclient                             -2220kB 3.0.25a-1  3.0.25a-2

この行は左から次のような意味です:

  • "現状"フラグ(1番目の文字)
  • "予定のアクション"フラグ(2番目の文字)
  • "自動"フラグ(3番目の文字)
  • パッケージ名
  • "予定のアクション"に帰属されるディスクスペースの使用の変化
  • パッケージの現バージョン
  • パッケージの候補バージョン
[ティップ] ティップ

"?"を押して表示されるヘルプスクリーンの一番下に全フラグのリストがあります。

現在のローカルの環境設定によって候補バージョンは選ばれます(apt_preferences(5)と「候補バージョンの調整」を参照)。

"表示"メニューの下に数種のパッケージ表示があります。

表2.10 aptitudeの表示のリスト。

表示 分類 状況
パッケージ画面 表2.11「標準パッケージ画面の分類。」参照下さい。(デフォルト) 良好
推奨を監査 何らかのインストール済みパッケージによって推薦されているがインストールされていないパッケージをリストします。 良好
平坦なパッケージリスト パッケージを分類されずにリストする(regexとともに使うため)。 良好
Debtags表示 パッケージのdebtagsのエントリーにより分類し表示します。 十分使える
カテゴリ別表示 パッケージの分類別に分類表示します。 非推奨 (debtagsを使おう!)

標準"パッケージ画面"はパッケージをdselectにいくつかの機能を加えた感じで分類します。

表2.11 標準パッケージ画面の分類。

分類 構成
更新可能なパッケージ セクション → コンポーネント → パッケージ、という構成
新規パッケージ , ,
インストール済みのパッケージ , ,
インストールされていないパッケージ , ,
廃止された、またはローカルで作成されたパッケージ , ,
仮想パッケージ 同一機能を持ったパッケージの集合から特定のパッケージを選択できる。
タスク 特定タスクのパッケージ集合から特定のパッケージを良いとこ取りで選択できる。

2.2.5. aptitudeを使った探索方法

Aptitudeはそのregex式機能を通してパッケージを探索する方法をいくつか提供します。

  • "aptitude search '<aptitude_regex>'"はマッチするパッケージのインストール状態やパッケージ名や短い説明をリストします。
  • "aptitude show '<package_name>'"はパッケージに関する詳細な説明をリストします。
  • マッチングするパッケージに表示を制限: フルスクリーンモードで"l"とタイプ。
  • 最初にマッチングするパッケージを表示: フルスクリーンモードで"/"とタイプ。"n"で前方探索、"\"で後方探索。

<package_name>という文字列は、"~"で始めてregex式と明示されていない限り、パッケージ名との完全な一致検索として扱います。

2.2.6. aptitudeのregex式

aptitudeのregex式はmutt的な拡張ERE(「正規表現」参照)でaptitudeに特定なマッチ規則の拡張は次に示すとおりです:

表2.12 aptitudeのregex式のリスト。

拡張マッチ規則の意味 regex式
パッケージ名とのマッチ ~n<名前のregex>
記述とのマッチ ~d<記述のregex>
タスク名とのマッチ ~t<タスクのregex>
debtagとのマッチ ~G<debtagのregex>
メンテナとのマッチ ~m<maintainerのregex>
パッケージセクションとのマッチ ~s<セクションのregex>
パッケージバージョンとのマッチ ~V<バージョンのregex>
アーカイブ(archive)とのマッチ ~A{sarge,etch,sid}
オリジン(origin)とのマッチ ~O{debian,…}
優先度(priority)とのマッチ ~p{extra,important,optional,required,standard}
必須(essential)パッケージとのマッチ ~E
仮想パッケージとのマッチ ~v
新規パッケージとのマッチ ~N
次のアクションとのマッチ ~a{install,upgrade,downgrade,remove,purge,hold,keep}
インストール済みパッケージとのマッチ ~i
A-マークのついたインストール済みパッケージとマッチ(自動インストール済みパッケージ) ~M
A-マークのついていないインストール済みパッケージとマッチ(管理者が選択したパッケージ) ~i!~M
インストール済みかつアップグレード可能なパッケージとマッチ ~U
削除済みだが完全削除されていないパッケージとマッチ ~c
削除済みか完全削除済みか削除可能なパッケージとマッチ ~g
パッケージ依存関係が壊れたパッケージとマッチ ~b
depends/predepends/conflictの依存関係が壊れたパッケージとマッチ ~B<type>
<term>パッケージに対して<type>の依存関係があるとパッケージのコントロールファイルに記載されたパッケージとマッチ ~D[<type>:]<term>
<term>パッケージに対して<type>の壊れた依存関係があるとパッケージのコントロールファイルに記載されたパッケージとマッチ ~DB[<type>:]<term>
<term>パッケージに対して<type>の依存関係があるパッケージとマッチ ~R[<type>:]<term>
<term>パッケージに対して<type>の壊れた依存関係があるパッケージとマッチ ~RB[<type>:]<term>
他のインストール済みパッケージが依存するパッケージとマッチ ~R~i
他のインストール済みパッケージが一切依存しないパッケージとマッチ !~R~i
他のインストール済みパッケージが依存もしくは推薦するパッケージとマッチ ~R~i|~Rrecommends:~i
フィルタされたバージョンの<term>とマッチ ~S filter <term>
常に全てのパッケージにマッチ(真) ~T
どのパッケージにもマッチしない(偽) ~F

上記で:

  • regex部分は、"^"や".*"や"$"などを使うegrep(1)やawk(1)やperl(1)といった典型的なUnix的テキストツールで使われるEREと同様です。
  • 関係を表す<type>は(depends, predepends, recommends, suggests, conflicts, replaces, provides)の内の一つです。
  • デフォルトの関係は"depends"です。
[ティップ] ティップ

<regex_pattern>がヌル文字列の場合は"~T"をコマンドの直後に使ってください。

近道:

  • "~P<term>" == "~Dprovides:<term>"
  • "~C<term>" == "~Dconflicts:<term>"
  • "…~W term" == "(…|term)"

muttが表現のお手本なので、muttに慣れているユーザはすぐ慣れるでしょう。"User's Manual" ("/usr/share/doc/aptitude/README")中の"SEARCHING, LIMITING, AND EXPRESSIONS"を参照下さい。

[注意] 注意

lennyバージョンのaptitude(8)では、新規の"?broken"のような長形式のregexマッチ形式が、古い"~b"のような短形式のマッチ形式に代えて使えます。そのためチルダ文字"~"二加えてスペース文字" "もregexの終端文字として扱われます。新規の長形式のマッチ形式については"User's Manual"を参照下さい。

2.2.7. aptitudeによる依存関係の解決

aptitudeによるパッケージの選択は、"F10 → Options → Dependency handling"のメニュー設定に従って、"Depends:"リストに規定されたパッケージばかりでは無く"Recommends:"リストに規定されたパッケージも引き込みます。このような自動的にインストールされたパッケージは不要になるとaptitudeが自動的に削除します。

[注意] 注意

lennyリリース以前は、apt-get等の他の標準的なAPTツールは自動的削除機能がありませんでした。

2.2.8. パッケージアクティビティーログ

パッケージアクティビティーの履歴はログファイルで確認できます。

表2.13 パッケージアクティビティーのログファイル

ファイル 内容
/var/log/dpkg.log 全パッケージアクティビティーのdpkgレベルのアクティビティーのログ
/var/log/apt/term.log APTアクティビティーのログ
/var/log/aptitude aptitudeコマンドアクティビティーのログ

これらのログから意味のある理解を迅速に得るのは実際には難しいです。より簡単な方法については「設定ファイルの変更記録」を参照下さい。

2.2.9. Aptitudeの長所

Aptitudeは他のAPT準拠のパッケージシステム(apt-get, apt-cache, synaptic, …)と比べて次の有利な点があります:

  • aptitudeは独自の追加層(/var/lib/aptitude/pkgstates)を使用して自動インストールされ使われなくなったパッケージを自動的に削除します。(新しいlennyでは、他のAPTも同様のことをします。)
  • aptitudeを使うことでパッケージ間のコンフリクト解消や推薦パッケージの追加がしやすくなります。
  • aptitudeを使うことで"廃止された、またはローカルで作成されたパッケージ"の下にリストすることで廃止ソフトウェアを追跡がしやすくなります。
  • aptitudeは"/var/log/aptitudeにその履歴記録を残します。
  • aptitudeを使うことで利用可能な全てのバージョンのパッケージにアクセスできます。
  • aptitudeには特定パッケージを探したり表示を制限するためのかなり強力なregexシステムがあります。
  • フルスクリーンモードのaptitudesu機能がついているので本当に管理権限が必要になるまでは通常のユーザからの実行ができます。

古いetchリリースのバージョンでは、synapticにも履歴記録はありましたが、dpkgの記録に頼らなければapt-getには履歴記録はありませんでした。

何れにせよaptitudeはコンソールでのインタラクティブな使用に好適です。

2.3. aptitude操作例

aptitude(8)操作例を次に示します。

2.3.1. regexにマッチするパッケージ名のパッケージをリスト

次のコマンドはregexにマッチする名前のパッケージをリストします。

$ aptitude search '~n(pam|nss).*ldap'
p libnss-ldap - NSS module for using LDAP as a naming service
p libpam-ldap - Pluggable Authentication Module allowing LDAP interfaces

これはパッケージの正確な名前を探すときに非常に便利です。

2.3.2. regexマッチをして閲覧

"平坦なパッケージリスト"のビューで"l"のプロンプトにregex"~dipv6"を入れるとその意味にマッチするパッケージにビューが制限され、その情報をインタラクティブに閲覧できます。

2.3.3. パッケージを本当に完全削除

削除したパッケージが残した全ての設定ファイルを完全削除できます:

# aptitude search '~c'
  • 結果の確認
# aptitude purge '~c'

同様のことをインタラクティブにすればよりきめの細かい結果が得られます。

"平坦なパッケージリスト"のビューで"l"のプロンプトにregex"~c"を入れるとregexにマッチする"削除されたが完全さ駆除されていない"パッケージにビューが制限されます。トップレベルの見出しの上で"["を押すとregexにマッチする全てのパッケージが表示されます。

次に"インストール済みのパッケージ"等のトップレベルの見出しの上で"_"を押します。その見出しの下のregexにマッチするパッケージだけが完全削除と設定されます。インタラクティブに個々のパッケージの上で"="を押せばそれらのパッケージを完全削除対象から外せます。

このテクニックは非常に便利で、他の多くのコマンドキーでも使えます。

2.3.4. 自動/手動インストールの状態の整理

(非aptitudeのパッケージインストーラー等を使った後で)パッケージの自動/手動インストールの状態を整理する私の方法を次に記します:

  • aptitudeをrootとしてインタラクティブに起動します。
  • "u"と"U"と"f"と"g"とタイプしてパッケージリストを更新しパッケージをアップグレードします。
  • "l"とタイプしてパッケージ表示制限を"~i(~R~i|~Rrecommends:~i)"として、"インストール済みのパッケージ"の上で"M"とタイプして自動インストールされたとします。
  • "l"とタイプしてパッケージ表示制限を"~prequired|~pimportant|~pstandard|~E"として、"インストール済みのパッケージ"の上で"m"とタイプして手動インストールされたとします。
  • "l"とタイプしてパッケージ表示制限を"~i!~M"として、"インストール済みのパッケージ"の上で"["とタイプしてパッケージを見えるようにした後で個々のパッケージの上で"-"とタイプして使っていないパッケージを削除します。
  • "l"とタイプしてパッケージ表示制限を"~i(~R~i|~Rrecommends:~i)"として、"インストール済みのパッケージ"の上で"M"とタイプして自動インストールされたとします。
  • aptitudeを終了。
  • "apt-get -s autoremove|less"とrootから起動して何が使われていないのか確認します。
  • aptitudeとインタラクティブモードで起動して必要なパッケージを"m"でマークします。
  • "apt-get -s autoremove|less"とrootから再起動して削除対象が期待にかなっていることを再確認します。
  • "apt-get autoremove|less"とrootから起動して使用していないパッケージを自動削除します。

"Tasks"の上で"m"を押すのも一案で、大量ファイル除去となる事態が回避できます。

2.3.5. aptitudeを使ったシステム全体のアップグレード

[注意] 注意

新しいリリース等への移行は、Debianでは下記のようにアップグレードできるのですが、新たなシステムをクリーンインストールすることを考えるべきです。こうすると溜めてきたゴミの除去ができる上に最新のパッケージの最良の組み合わせも分かります。もちろん安全な場所に完全なシステムのバックアップ(「Backup and recovery」参照)を事前にしなくてはいけません。異なったパーティションを使ったデュアルブート設定をすることをスムーズな移行をするためにお薦めします。

"/etc/apt/sources.list"ファイルの内容を新しいリリースへと向けるように変更し、"aptitude update; aptitude full-upgrade"コマンドを実行することでシステム全体のアップグレードができます。

安定版stableからテスト版testingや不安定版unstableにアップグレードするには、「Debianアーカイブの基本」にある"/etc/apt/sources.list"例の"lenny"を"squeeze"か"sid"に置き換えます。

一部のパッケージで移行に関して支障をきたすことが実際には起こるかもしれません。これは大体パッケージ依存関係に起因します。アップグレードする差が大きければ大きいほど比較的大きな問題似合う可能性がより大きくなります。以前の安定版stableからリリース後の新しい安定版stableへの移行では新しいリリースノートを読んでそこに記載された手続き通りに完全にすれば問題発生を防げます。

安定版stableからテスト版testingへ移行すると決めた時には頼りにするリリースノートはありません。前回の安定版stableのリリースの後で安定版stableとテスト版testingの差がかなり大きくなっているかもしれません。そうだとアップグレードをする状況は複雑になっています。

メーリングリストから最新情報を収集するとか常識を使うといった予防措置をするべきです。

  • 前回の"リリースノート"を読む。
  • 全システム(特にデータや設定情報)をバックアップします。
  • ブートローダが壊れたときのためにブートできる媒体を確保します。
  • システムを使っているユーザに十分事前に通告します。
  • script(1)を使ってアップグレード活動を記録します。
  • 削除をされないように"aptitude unmarkauto vim"等として、"unmarkauto"を重要なパッケージに適用します。
  • デスクトップタスクにあるパッケージ等を削除して、インストールされたパッケージを減らしてパッケージがコンフリクトする可能性を減らす。
  • "/etc/apt/preferences"ファイルを削除します。(apt-pinningを無効にする)
  • 段階的にアップグレードするように努める:旧安定版oldstable → 安定版stable → テスト版testing → 不安定版unstable
  • "/etc/apt/sources.list"ファイルをアップデートして新しいアーカイブに向けて、"aptitude update"を実行します。
  • "aptitude install perl"等として、新規の中核的パッケージのインストールを必要に応じて先にします。
  • "aptitude full-upgrade -s"コマンドを実行して影響を確認する。
  • "aptitude full-upgrade"コマンドを実行します。
[注意] 注意

stableリリース間でアップグレードする際にDebianのメジャーリリースを飛ばすのは賢明ではない。

[注意] 注意

過去の"リリースノート"ではシステム全体のアップグレードをするのにGCCやLinuxカーネルやinitrd-toolsやGlibcやPerlやAPT tool chain等には特別な配慮が必要でした。

unstableでの毎日のアップグレードは「パッケージの問題に対する防御」を参照下さい。

2.4. 高度なパッケージ管理操作

2.4.1. コマンドラインによる高度なパッケージ管理操作

aptitudeではハイレベル過ぎるとか必要な機能を欠くという他のパッケージ管理操作のリストです。

表2.14 高度なパッケージ管理操作のリスト

アクション コマンド
バグレポートのためのにインストールされたパッケージの状態をリストします。 COLUMNS=120 dpkg -l <パッケージ名パターン>
インストールされたパッケージの内容をリストします。 dpkg -L <パッケージ名>
インストールされたパッケージのmanページをリストします。 dpkg -L <パッケージ名> | egrep '/usr/share/man/man.*/.+'
マッチするファイル名があるインストールされたパッケージをリストします。 dpkg -S <ファイル名パターン>
マッチするファイル名があるアーカイブ中のパッケージをリストします。 apt-file search <ファイル名パターン>
アーカイブ中のマッチするパッケージをリストします。 apt-file list <パッケージ名パターン>
特定パッケージを再設定します。 dpkg-reconfigure <パッケージ名>
もっとも詳細な質問で特定パッケージを再設定します。 dpkg-reconfigure -p=low <パッケージ名>
フルスクリーンメニューからパッケージを再設定します。 configure-debian
部分的にインストールされたパッケージに関してシステムを監査します。 dpkg --audit
全ての部分的にインストールされたパッケージを設定します。 dpkg --configure -a
バイナリパッケージに関して使用可能なバージョンやプライオリティーやアーカイブ情報を表示します。 apt-cache policy <バイナリパッケージ名>
パッケージに関して使用可能なバージョンやアーカイブ情報を表示します。 apt-cache madison <パッケージ名>
バイナリパッケージに関してソースパッケージの情報を表示します。 apt-cache showsrc <バイナリパッケージ名>
パッケージをビルドするのに必要なパッケージをインストールします。 apt-get build-dep <パッケージ名>
(標準アーカイブから)ソースをダウンロードします。 apt-get source <パッケージ名>
(他のアーカイブから)ソースをダウンロードします。 dget <dscファイルのURL>
ソースパッケージの組("*.tar.gz"と"*.diff.gz")からソースツリーをビルドします。 dpkg-source -x <パッケージ名>_<バージョン>-<debianバージョン>.dsc
ローカルのソースツリーからパッケージをビルドします。 debuild binary
カーネルソースツリーからカーネルパッケージをビルドします。 make-kpkg kernel_image
カーネルソースツリーからinitramfsを有効にしてカーネルパッケージをビルドします。 make-kpkg --initrd kernel_image
ローカルパッケージをシステムにインストールします。 dpkg -i <パッケージ名>_<バージョン>-<debianバージョン>_<アーキテクチャー名>.deb
ローカルパッケージ(複数)をシステムにインストールします。 debi <パッケージ名>_<バージョン>-<debianバージョン>_<アーキテクチャー名>.dsc
dpkgレベルのパッケージ選択状態情報を保存します。 dpkg --get-selection '*' >selection.txt
dpkgレベルのパッケージ選択状態情報を設定します。 dpkg --set-selection <selection.txt

[注意] 注意

"dpkg -i …"や"debi …"といった低いレベルのパッケージツールはシステム管理者によって注意深く使われなければいけません。必要なパッケージ依存関係を自動的に面倒見てくれません。Dpkgの"--force-all"や類似のコマンドラインオプション(dpkg(1)参照)はエキスパートだけが使うようにできています。十分にその影響を理解せずに使うとシステム全体を壊してしまうかもしれません。

次に注意下さい:

  • 全てのシステム設定やインストールコマンドはrootから実行なければいけません。
  • regex(「正規表現」参照)を使うaptitudeと異なり、他のパッケージ管理コマンドはシェルグロブ(「シェルグロブ」参照)のようなパターンを使います。
  • apt-fileパッケージに入っているapt-file(1)は事前に"apt-file update"を実行する必要があります。
  • configure-debianパッケージに入っているconfigure-debian(8)はそのバックエンドとしてdpkg-reconfigure(8)を実行します。
  • dpkg-reconfigure(8)はそのバックエンドとしてdebconf(1)を利用するパッケージスクリプトを実行します。
  • "apt-get build-dep"や"apt-get source"や"apt-cache showsrc"コマンドは"/etc/apt/sources.list"の中に"deb-src"エントリーが必要です。
  • dget(1)やdebuild(1)やdebi(1)はdevscriptsパッケージが必要です。
  • "apt-get source"を使った(再)パッケージ化の手続きは「安定版システムへのパッケージ移植」を参照下さい。
  • make-kpkgコマンドはkernel-packageパッケージが必要です(「カーネル」参照)。
  • 一般的なパッケージ化に関しては「Debianパッケージ作成」を参照下さい。
[ティップ] ティップ

ソースパッケージの組としてここで説明したソースパッケージのフォーマット("*.tar.gz"と"*.diff.gz")はまだ主流の1.0フォーマットです。他の新規フォーマットに関しての詳細はdpkg-source(1)を参照下さい。

2.4.2. インストールされたパッケージファイルの検証

debsumsをインストールするとdebsums(1)を使って"/var/lib/dpkg/info/*.md5sums"ファイル中のMD5sum値との比較でインストールされたパッケージファイルを検証できます。MD5sumがどのような仕組かは「The MD5 sum」参照ください。

[注意] 注意

侵入者によってMD5sumのデータベースが改竄されているかもしれないのでdebsums(1)はセキュリティツールとしては限定的有用性しかありません。管理者によるローカルの変更や記憶媒体のエラーによる損傷を点検するぐらいには有用です。

2.4.3. パッケージの問題に対する防御

多くのユーザは新しい機能やパッケージを求めてDebianシステムの非安定版unstableリリースを追いかけることを好みます。こういうことをするとクリティカルなパッケージのバグにシステムが遭遇しやすくなります。

apt-listbugsパッケージをインストールすれば、APTシステムを使ってアップグレードする時にDebianのBTSを自動的にクリティカルなバグに関して点検することで、クリティカルなバグから防御ができます。

apt-listchangesパッケージをインストールすれば、APTシステムを使ってアップグレードする時にNEWS.Debian中の重要ニュースを表示します。

2.4.4. パッケージメタデータの検索

最近はDebianサイトのhttp://packages.debian.org/を訪問するとパッケージメタデータの検索を簡単に出きるようになっていますが、より伝統的な方法を見てみましょう。

grep-dctrl(1)やgrep-status(1)やgrep-available(1)コマンドはDebianのパッケージコントロールファイルの一般的フォーマットに従ういかなるファイルを検索するのにも使えます。

マッチする名前のファイルを含むdpkgでインストールされたパッケージ名を探索するのに"dpkg -S <ファイル名パターン>"が使えます。しかしメンテナスクリプトで生成されるファイルはこれでは見逃されます。

dpkgのメタデータに関するより詳細な検索をする必要がある場合、"/var/lib/dpkg/info/"ディレクトリで"grep -e regexパターン *"コマンドを実行しないといけません。こうすることで次のことが分かります:

  • パターンにマッチする特定ファイルをインストールや作成や改変するパッケージ名。
  • パターンにマッチするインストールの質問文言を聞くパッケージ名。

パッケージ依存関係を再帰的に検索したい際には、apt-rdepends(8)を使いましょう。

2.5. Debianパッケージ管理の内部

Debianのパッケージ管理システムが内部的のどのように機能するのかを学びましょう。何らかのパッケージ問題が発生した際にあなた自身の解決を見出すのに役立つでしょう。

2.5.1. アーカイブのメタデータ

各ディストリビューションのメタデータのファイルは例えば"http://ftp.us.debian.org/debian/"のような各Debianミラーサイトの"dist/<コード名>"の下に保存されています。そのアーカイブ構造はウエッブブラウザで閲覧できます。6つのタイプの重要メタデータがあります:

表2.15 Debianアーカイブのメタデータの内容。

ファイル 場所 内容
Release ディストリビューションのトップ アーカイブの説明との整合性情報
Release.gpg ディストリビューションのトップ アーカイブキーで署名された"Release"ファイルに関する署名ファイル
Contents-<アーキテクチャー> ディストリビューションのトップ 該当アーカイブ中全てのパッケージに関する全ファイルリスト
Release 各ディストリビューション/コンポーネント/アーキテクチャーの組み合わせのトップ apt_preferences(5)のルールに利用されるアーカイブの記述。
Packages 各ディストリビューション/コンポーネント/バイナリアーキテクチャーの組み合わせのトップ バイナリパッケージに関してdebian/controlを連結
Sources 各ディストリビューション/コンポーネント/ソースの組み合わせのトップ ソースパッケージに関してdebian/controlを連結

最近のアーカイブではネットワークトラフィックを減らすべく圧縮された差分ファイルとしてこれらのメタデータは保存されています。

2.5.2. トップレベルの"Release"ファイルと信憑性

[ティップ] ティップ

セキュアAPTシステムではトップレベルの"Release"ファイルがアーカイブを署名するのに使われています。

Debianアーカイブの各スイーツには例えば"http://ftp.us.debian.org/debian/dists/unstable/Release"のようなトップレベルの"Release"ファイルがあります。

Origin: Debian
Label: Debian
Suite: unstable
Codename: sid
Date: Sat, 26 Jan 2008 20:13:58 UTC
Architectures: alpha amd64 arm hppa hurd-i386 i386 ia64 m68k mips mipsel powerpc s390 sparc
Components: main contrib non-free
Description: Debian x.y Unstable - Not Released
MD5Sum:
 e9f11bc50b12af7927d6583de0a3bd06 22788722 main/binary-alpha/Packages
 43524d07f7fa21b10f472c426db66168  6561398 main/binary-alpha/Packages.gz
...
[注意] 注意

「Debianアーカイブの基本」の中で"スイーツ(suite)"や"コード名(codename)"や"コンポーネント(component)"を使う理由はこれを見れば分かるでしょう。"ディストリビューション"は"スイーツ"と"コード名"との両方を指したい際に用いられます。

トップレベルの"Release"ファイルの整合性は セキュアaptという暗号学手法インフラストラクチャーによって検証されます。

  • 暗号手法による署名ファイル"Release.gpg"は真正のトップレベルの"Release"ファイルと秘密のDebianアーカイブキーから作成されます。
  • 公開のDebianアーカイブキーは"/etc/apt/trusted.gpg"に取り込むには次のようにします:

  • セキュアAPTシステムはこの"Release.gpg"ファイルと"/etc/apt/trusted.gpg"中の公開アーカイブキーを用いてダウンロードされたトップレベルの"Release"ファイルの整合性を暗号学手法を用いて検証します。

"全てのPackages"と"Sourcesファイルの整合性はそのトップレベルの"Release"ファイル中のMD5sum値を用いて検証します。"パッケージファイルの整合性は"Packages"や"Sources"ファイル中のMD5sum値を用いて検証します。debsums(1)と「インストールされたパッケージファイルの検証」を参照下さい。

暗号学手法を用いた署名の検証はMD5sum値の計算よりも非常にCPUを使うプロセスなので、トップレベルの"Release"ファイルには暗号学手法を用いた署名を使いつつ各パッケージにはMD5sum値を用いることでパーフォーマンスを保ったまま良好なセキュリティが確保できます(「Data security infrastructure」参照)。

2.5.3. アーカイブレベルの"Release"ファイル

[ティップ] ティップ

アーカイブレベルの"Release"ファイルはapt_preferences(5)のルールに利用されます。

"http://ftp.us.debian.org/debian/dists/unstable/main/binary-amd64/Release"や"http://ftp.us.debian.org/debian/dists/sid/main/binary-amd64/Release"等の"/etc/apt/sources.list"中の"deb"行で特定される全てのアーカイブロケーションにはアーカイブレベルの"Release"ファイルがあります。

Archive: unstable
Component: main
Origin: Debian
Label: Debian
Architecture: amd64
[注意] 注意

"Archive:"スタンザには、Debianアーカイブではスイート名("stable"や"testing"や"unstable"等)が使われますが、Ubuntuアーカイブではコード名("dapper"や"feisty"や"gutsy"や"hardy"や"intrepid"等)が使われます。

experimentalvolatile-sloppylenny-backportsのような自動的にインストールされるべきでないパッケージを含むようなアーカイブでは"http://ftp.us.debian.org/debian/dists/experimental/main/binary-amd64/Release"のような追加の行があります:

Archive: experimental
Component: main
Origin: Debian
Label: Debian
NotAutomatic: yes
Architecture: amd64

"NotAutomatic: yes"となっていない通常のアーカイブではデフォルトのPin-Priority値は500ですが、"NotAutomatic: yes"となっている特別なアーカイブではデフォルトのPin-Priority値は1です(apt_preferences(5)と「候補バージョンの調整」参照)。

2.5.4. パッケージメタデータの取得

aptitudeapt-getsynapticapt-fileauto-apt等のAPTツールが使われる際にはDebianアーカイブ情報を含むメタデータのローカルコピーを更新する必要があります。この様なコピーは"/etc/apt/sources.list"中のディストリビューションコンポーネントアーキテクチャーの名前に対応する次のファイル名です(「Debianアーカイブの基本」参照):

  • "/var/lib/apt/lists/ftp.us.debian.org_debian_dists_<ディストリビューション>_Release"
  • "/var/lib/apt/lists/ftp.us.debian.org_debian_dists_<ディストリビューション>_Release.gpg"
  • "/var/lib/apt/lists/ftp.us.debian.org_debian_dists_<ディストリビューション>_<コンポーネント>_source_Sources"
  • "/var/lib/apt/lists/ftp.us.debian.org_debian_dists_<ディストリビューション>_<コンポーネント>_source_Sources"
  • "/var/cache/apt/apt-file/ftp.us.debian.org_debian_dists_<ディストリビューション>_Contents-<アーキテクチャー>.gz" (apt-file用)

最初の4つのタイプのファイルは全ての適切なAPTコマンド間で共有されておりコマンドラインから"apt-get update"や"aptitude update"によって更新されます。もし"/etc/apt/sources.list"中に"deb"行があれば"Packages"メタデータが更新されます。もし"/etc/apt/sources.list"中に"deb-src"行があれば"Sources"メタデータが更新されます。

"Packages"や"Sources"メタデータはバイナリやソースパッケージのファイルの場所を指している"Filename:"スタンザを含んでいます。現在、それらのパッケージはリリース間の移行を滞り無くするために"pool/"ディレクトリツリーの下に置かれています。

"Packages"メタデータのローカルコピーはaptitudeを使ってインタラクティブに検索できます。grep-dctrl(1)という専用の検索コマンドを使うと"Packages"と"Sources"メタデータのローカルコピーを検索できます。

"Contents-<アーキテクチャー>"メタデータのローカルコピーは"apt-file update"で更新でき、他の4つと異なるところにあります。apt-file(1)を参照下さい。(auto-aptでは"Contents-<アーキテクチャー>.gz"のローカルコピーがデフォルトでは異なるところにあります。)

2.5.5. APTに関するパッケージ状態

lenny以降のAPTツールではリモートから取得したメタデータに追加でローカルで生成されるインストール状態情報を"/var/lib/apt/extended_states"に保存して、自動インストールされた全パッケージを全てのAPTツールで追跡するのに用います。

2.5.6. aptitudeに関するパッケージ状態

aptitudeコマンドではリモートから取得したメタデータに追加でローカルで生成されるインストール状態情報を"/var/lib/aptitude/pkgstates"に保存して用いています。

2.5.7. 取得したパッケージのローカルコピー

APTメカニズムでリモートから取得されたパッケージは消去されるまでは"/var/cache/apt/packages"に貯蔵されます。

2.5.8. Debianパッケージファイル名

Debianのパッケージファイルには特定の名前の構造があります。

表2.16 Debianパッケージの名前の構造。

パッケージタイプ 名前の構造
バイナリパッケージ(所謂deb) <パッケージ名>_<エポック>:<アップストリームのバージョン>-<debianのバージョン>-<アーキテクチャー>.deb
debianインストーラーのためのバイナリパッケージ(所謂udeb) <パッケージ名>_<エポック>:<アップストリームのバージョン>-<debianのバージョン>-<アーキテクチャー>.udeb
ソースパッケージ(アップストリームのソース) <パッケージ名>_<エポック>:<アップストリームのバージョン>-<debianのバージョン>.tar.gz
ソースパッケージ(Debianの変更部分) <パッケージ名>_<エポック>:<アップストリームのバージョン>-<debianのバージョン>.diff.gz
ソースパッケージ(内容記述) <パッケージ名>_<エポック>:<アップストリームのバージョン>-<debianのバージョン>.dsc

ここで、

表2.17 Debianパッケージ名の各部分に使用可能な文字。

名前の部分 使用可能文字(regex) 存在
<パッケージ名> [a-z,A-Z,0-9,.,,-] 必須
<エポック>: [0-9]+: 任意
<アップストリームのバージョン> [a-z,A-Z,0-9,.,,-,:] 必須
<debianのバージョン> [a-z,A-Z,0-9,.,,~] 任意

[注意] 注意

パッケージバージョンの順位はdpkg(1)を使って、例えば"dpkg --compare-versions 7.0 gt 7.~pre1 ; echo $?"とすると確認できます。

[注意] 注意

Debianインストーラー(d-i)のバイナリパッケージには、通常のdebではなくudebをファイルエクステンションとして使われます。udebパッケージはポリシー条件を緩和しドキュメントのように必須でない内容を削除した減量debパッケージです。debudebパッケージは同一のパッケージ構造を共有しています。"u"はマイクロと言う意味で使っています。

2.5.9. dpkgコマンド

dpkg(1)はDebianパッケージ管理の最も低レベルのツールです。非常に強力ですから気をつけて使う必要があります。

取得されたパッケージはdpkgによって次の順で処理されます:

  1. debファイルを解凍("ar -x"と等価)
  2. debconf(1)を使ったpreinst
  3. システムにパッケージ内容をインストール("tar -x"と等価)
  4. debconf(1)を使ったpostinst

debconfシステムによってI18NとL10N(8章I18N and L10N)のサポートのある標準化されたユーザとの対話が実現できます。

"<パッケージ名>"というパッケージをインストールする際にdpkgはファイルをいくつか作りスクリプトをいくつか実行します。

表2.18 dpkgに関する特記すべきファイル。

ファイル 内容
/var/lib/dpkg/info/<パッケージ名>.conffiles 設定ファイルのリスト。(ユーザ変更可能)
/var/lib/dpkg/info/<パッケージ名>.list パッケージによりインストールされるファイルやディレクトリのリスト。
/var/lib/dpkg/info/<パッケージ名>.md5sums パッケージによりインストールされるファイルのMD5ハッシュ値のリスト。
/var/lib/dpkg/info/<パッケージ名>.preinst パッケージ導入の前に実行するパッケージスクリプト。
/var/lib/dpkg/info/<パッケージ名>.postinst パッケージ導入の後に実行するパッケージスクリプト。
/var/lib/dpkg/info/<パッケージ名>.prerm パッケージ削除の前に実行するパッケージスクリプト。
/var/lib/dpkg/info/<パッケージ名>.prerm パッケージ削除の前に実行するパッケージスクリプト。
/var/lib/dpkg/info/<パッケージ名>.conffiles debconfシステムのためのパッケージスクリプト。
/var/lib/dpkg/alternatives/<パッケージ名> update-alternativesコマンドが用いる代替情報。
/var/lib/dpkg/available すべてのパッケージの入手可能性情報。
/var/lib/dpkg/diversions dpkg(1)に用いられ、dpkg-divert(8)が設定する迂回情報。
/var/lib/dpkg/statoverride dpkg(1)に用いられ、dpkg-statoverride(8)が設定する状態の上書き情報。
/var/lib/dpkg/status パッケージに関する情報閲覧します。
/var/lib/dpkg/status-old "var/lib/dpkg/status"ファイルの第一世代のバックアップ。
/var/backups/dpkg.status* "var/lib/dpkg/status"ファイルの第二世代以前のバックアップ。

"status"ファイルはdpkg(1)や"dselect update"や"apt-get -u dselect-upgrade"のようなツールによって使われます。

grep-dctrl(1)という専用の検索コマンドを使うと"status"と"available"メタデータのローカルコピーを検索できます。

[ティップ] ティップ

デビアンインストーラー 環境下では、udpkgコマンドがudebパッケージを開けるのに用いられます。udpkgコマンドはストリップダウンされたバージョンのdpkgコマンドです。

2.5.10. update-alternativeコマンド

Debianシステムにはupdate-alternatives(8)を用いて何らかの重畳するプログラムを平和裏にインストールするメカニズムがあります。例えばvimnviの両方のパッケージがインストールされた状況下でviコマンドがvimを選択して実行するようにできます。

$ ls -l $(type -p vi)
lrwxrwxrwx 1 root root 20 2007-03-24 19:05 /usr/bin/vi -> /etc/alternatives/vi
$ sudo update-alternatives --display vi
...
$ sudo update-alternatives --config vi
  Selection    Command
 ----------------------------------------------
      1        /usr/bin/vim
*+    2        /usr/bin/nvi

Enter to keep the default[*], or type selection number: 1

Debianの代替(alternatives)システムは、その選択を"/etc/alternatives/"の中のシムリンクとして保持します。選択プロセスには"/var/lib/dpkg/alternatives/"の中の対応するファイルが使われます。

2.5.11. dpkg-statoverrideコマンド

dpkg-statoverride(8)コマンドで提供される状態の上書きは、パッケージをインストールする際にファイルに関して異なる所有者やモードを使うようdpkg(1)に指示する方法です。もし"--update"が指定されファイルが存在すれば、即座に新たな所有者やモードに設定されます。

[注意] 注意

パッケージが所有するファイルの所有者やモードをシステム管理者がchmodchownコマンドを用いて直接変更しても次のパッケージアップグレードがリセットします。

[注意] 注意

ここでファイルと言いましたが、実際にはdpkgが扱うディレクトリやデバイス等のいかなるファイルシステムオブジェクトであってもいいです。

2.5.12. dpkg-divertコマンド

dpkg-divert(8)コマンドによって提供されるファイル迂回は、ファイルをデフォルトの場所ではなく迂回した場所にインストールするようにdpkg(1)にさせます。dpkg-divertは本来パッケージメインテナンススクリプトのためのものです。システム管理者がこれを使うのはお薦めしません。

2.6. 壊れたシステムからの回復

非安定(unstable)システムを動かす時には、管理者は壊れたパッケージ管理状況から回復できることが望ましいです。

[注意] 注意

ここで説明するいくつかの方法は非常にリスクが高いアクションです。警告しましたよ!

2.6.1. 古いユーザの設定との非互換性

もしデスクトップGUIプログラムが上流の大きなバージョンアップグレードの後に不安定性を経験した際には、そのプログラムが作った古いローカル設定ファイルとの干渉を疑うべきです。もし新規作成したユーザアカウントでそのプログラムが安定なら、この仮説が裏付けられます。(これはパッケージングのバグで、通常パッケージャーによって回避されます。)

安定性を回復するには、対応するローカル設定ファイルを移動しGUIプログラムを再スタートします。後日設定情報を回復するために古い設定ファイルの内容を読む必要があるかもしれません。(あまり慌てて消去しないようにしましょう。)

2.6.2. 重複するファイルを持つ相異なるパッケージ

aptitude(8)やapt-get(1)等の、アーカイブレベルのパッケージ管理システムはパッケージの依存関係を使って重複するファイルを持つファイルのインストールしようとさえしません(「パッケージ依存関係」参照)。

パッケージメインテナによるエラーや、システム管理者による不整合な混合ソースのアーカイブの採用(「混合したアーカイブソースからのパッケージ」参照)があった場合には、パッケージ依存関係が誤って定義される事態が発生するかもしれません。そういう状況下で重複するファイルを持つパッケージをaptitude(8)やapt-get(1)を使ってインストールしようとすると、パッケージを展開するdpkg(1)は既存ファイルを上書きすることなく呼ばれたプログラムにエラーを確実に返します。

[注意] 注意

第三者が作成したパッケージを使うと、root権限で実行されるシステムに関して何でもできるメンテナスクリプトが実行されるので、システムが重大なリスクにさらされます。dpkg(1)はパッケージを展開するするさいに上書きする事を防止するだけです。

そのような壊れたインストール状況は、まず古い問題の原因となっているパッケージ<old-package>をまず削除することで回避できます:

$ sudo dpkg -P <old-package>

2.6.3. 壊れたパッケージスクリプトの修正

パッケージスクリプト内のコマンドが何らかの理由でエラーを返しスクリプトがエラーで終了した場合には、パッケージ管理システムは動作を途中終了するので部分的にインストールされたパッケージのある状況が生まれます。パッケージがその削除スクリプト内にバグを持つ場合には、パッケージが削除不能になりうるので大変厄介です。

"<パッケージ名>"のパッケージスクリプトの問題に関しては、以下を確認する必要があります:

  • "/var/lib/dpkg/info/<パッケージ名>.preinst"
  • "/var/lib/dpkg/info/<パッケージ名>.postinst"
  • "/var/lib/dpkg/info/<パッケージ名>.prerm"
  • "/var/lib/dpkg/info/<パッケージ名>.prerm"

rootからスクリプトの問題源の部分を次のように編集します:

  • 行頭に"#"を挿入、または
  • 行末に"|| true"を挿入します。

全ての部分的にインストールされたパッケージを設定します。

# dpkg --configure -a

2.6.4. dpkgコマンドを使っての救済

dpkgは非常に低レベルのパッケージツールなのでネットワーク接続もないブート不能な非常に劣悪な状況下でも機能します。fooパッケージが壊れていて置き換える必要があると仮定しましょう。

バグの無い古いバージョンのfooパッケージが"/var/cache/apt/archives/"にあるパッケージキャッシュの中に見つかるかもしれません。(ここにみつからなければ、http://snapshot.debian.net/アーカイブからダウンロードしたり、機能している機器のパッケージキャッシュからコピーできます。)

もしブート不可能な場合には、次のようにしてインストールすることもできます:

# dpkg -i /path/to/foo_<old_version>_<arch>.deb
[ティップ] ティップ

システムがそれほど壊れていないなら、「緊急ダウングレード」に書かれているようにして、より高レベルのAPTシステムを通じてシステム全体をダウングレードする手もあります。

ハードディスクからブートできない場合には、他の方法でのブートをするようにしましょう。例えば、次の手順をとります:

  • デビアンインストーラー(debian-installer)のCDを使ってレスキューモードでブートします。
  • ブートできないハードディスク上のシステムを"/target"にマウントします。
  • 古いバージョンのfooパッケージを次のようにしてインストールします。
# dpkg --root /target -i /path/to/foo_<old_version>_<arch>.deb

2番めの例は、たとえハードディスク上のdpkgコマンドが壊れていても機能します。

[ティップ] ティップ

ハードディスク上の別のシステムであれ、GNU/LinuxのライブCDであれ、ブート可能なUSBキードライブであれ、ネットブートであれ、どのように起動されたGNU/Linuxシステムでも同様にして壊れたシステムを救済するのに使えます。

もしこの方法でパッケージをインストールしようとして何らかの依存関係違反のためにうまくいかなくてどうしようもなくなった場合には、dpkgの"--ignore-depends"や"--force-depends"や他のオプションを使って依存関係をオーバーライドすることができます。こうした場合には、後で依存関係を修復するように真剣に取り組む必要があります。詳細はdpkg(8)を参照下さい。

[注意] 注意

システムがひどく壊れた場合には、システムを安全な場所に完全バックアップし(「Backup and recovery」参照)、クリー(see 「Backup and recovery」)ンインストールを実行するべきです。こうすることは時間お節約でもあり最終的に良い結果に結びつきます。

2.6.5. パッケージセレクションの回復

もし何らかの理由で"/var/lib/dpkg/status"の内容が腐った場合には、Debianシステムはパッケージ選択データが失われ大きな打撃を被ります。古い"/var/lib/dpkg/status"ファイルは、"/var/lib/dpkg/status-old"や"/var/backups/dpkg.status.*"としてあるので探しましょう。

"/var/backups/"は多くの重要な情報を保持しているので、これを別のパーティション上に置くのも良い考えです。

ひどく壊れた場合には、システムのバックアップをした後フレッシュに再インストールすることをお薦めします。たとえ"/var/"ディレクトリの中が完全に消去されても、"/usr/share/doc/"ディレクトリ中から新しいインストールのガイドとなる情報を回復できます。

  • 最低源の(デスクトップ)システムを再インストールします。
  • "/path/to/old/system/"に古いシステムを置く
# cd /path/to/old/system/usr/share/doc
# ls -1 >~/ls1.txt
# cd /usr/share/doc
# ls -1 >>~/ls1.txt
# cd
# sort ls1.txt | uniq | less

こうすると、インストールすべきパッケージ名が表示されます。("texmf"のようなパッケージ名以外が一部あるかもしれません。)

2.7. パッケージ管理のヒント

2.7.1. Debianパッケージの選択方法

パッケージの説明や"Tasks"の下のリストを使ってあなたが必要なパッケージをaptitudeで見つけることができます。

2つ以上の似たパッケージに出会いが"試行錯誤"の努力無しにどのパッケージをインストールするか迷った際には、常識を使って下さい。次に示す点は好ましいパッケージの良い指標と考えます。

  • 必須(essential): yes > no
  • コンポーネント(component): メイン(main) > contrib > non-free
  • 優先度(priorities): 必須(required) > 重要(important) > 標準(standard) > 任意(optional) > 特別(extra)
  • タスク(tasks): "デスクトップ環境"のようなタスクにリストされたパッケージ
  • 依存パッケージにより選ばれたパッケージ(例えば、pythonによるpython2.4)
  • popcon: higher in the vote and install number
  • changelog: メンテナによる定期的アップデート
  • BTS: RC bugが無いこと (criticalもgraveもseriousもいずれのバグも無い)
  • BTS: バグレポートに反応の良いメンテナ
  • BTS: 最近修正されたバグの数が多い
  • BTS: wishlist以外のバグが少ない

Debianは分散型の開発モデルのボランティアプロジェクトですので、そのアーカイブには目指すところや品質の異なる多くのパッケージがあります。これらをどうするかは自己判断をして下さい。

2.7.2. 混合したアーカイブソースからのパッケージ

[注意] 注意

安定版(stable)security updatesvolatile updatesのような公式にサポートされた特定の組み合わせ以外は、混合したアーカイブソースからのパッケージをインストールすることを、公式にはDebianディストリビューションとしてサポートしていません。

testingを追跡しながら、unstableにある特定の新規アップストリームバージョンのパッケージを1回だけ取り入れる操作例を次に示します。

  • "/etc/apt/sources.list"ファイルを変更し、単一の"unstable"エントリーのみにします。
  • "aptitude update"を実行します。
  • "aptitude install <パッケージ名>"の実行
  • testingのためのオリジナルの"/etc/apt/sources.list"ファイルを回復します。
  • "aptitude update"を実行します。

この様な手動のアプローチをすると"/etc/apt/preferences"ファイルを作ることもないし、またapt-pinningについて悩むこともありません。でもこれではとても面倒です。

[注意] 注意

混合したアーカイブソースを使うことをDebianが保証していないので、その場合にはパッケージ間の互換性は自分自身で確保しなければいけません。もしパッケージに互換性がないと、システムを壊すことになるかもしれません。この様な技術的要件を判断できる必要があります。ランダムな混合したアーカイブソースを使うことは全く任意の操作ですが、私としてはこの操作はお薦めできません。

異なるアーカイブからパッケージをインストールするための一般ルール:

非バイナリパッケージのインストールは比較的安全です。

  • 文書パッケージ: 特段の要件無し
  • インタープリタプログラムパッケージ: 互換性あるインタープリタ環境が必要

完全に静的にリンクされたバイナリパッケージのインストールは安全です。

バイナリパッケージ(非"Architecture: all")のインストールは、通常多くの障害があり、安全ではありません

  • ライブラリ("libc"等)のバージョン互換性
  • 関連ユーティリティプログラムのバージョン互換性
  • カーネルABI互換性
  • C++のABI互換性
[注意] 注意

壊れたパッケージを短期的に避ける場合以外では、公式にサポートされていないアーカイブからバイナリパッケージをインストールするのは一般的には賢明ではありません。たとえapt-pinning(「候補バージョンの調整」参照)を使った場合にもこれは当てはまります。chrootや類似のテクニック(「Chrootシステム」参照)使って、他のアーカイブからのプログラムを実行するよう検討するべきです。

2.7.3. 候補バージョンの調整

[警告] 警告

lennyaptitude(8)には、"/etc/apt/preferences"ファイルの扱いにバグ(Bug#514930参照)があります。

"/etc/apt/preferences"ファイル無しだと、APTシステムはバージョン文字列を用いて、最新バージョンを候補バージョンとします。これが通常状態でAPTシステムの最も推薦される使い方です。全ての公式にサポートされたアーカイブの組み合わせは、自動的にアップグレードするソースとすべきでないアーカイブはNotAutomaticとマークされていて適切な扱いを受けるので、"/etc/apt/preferences"ファイルを必要としません。

[ティップ] ティップ

バージョン文字列比較ルールは、例えば"dpkg --compare-versions ver1.1 gt ver1.1~1; echo $?"とすれば確認できます(dpkg(1)参照)。

パッケージを混合したアーカイブからのソース(「混合したアーカイブソースからのパッケージ」参照)から定常的にインストールする場合には、apt_preferences(5)に書かれたように適切な項目のある"/etc/apt/preferences"ファイルを作り候補バージョンに関するパッケージ選択ルールを操作することによってこういった複雑な操作を自動化できます。これをapt-pinningと呼びます。

[警告] 警告

初心者のユーザによるapt-pinningの利用は大トラブル発生を間違いなく起こします。本当に必要な時以外はapt-pinningの利用は避けなければいけません。

[注意] 注意

apt-pinningを利用する際には、Debianはパッケージの互換性を保証しないので、ユーザ自身がパッケージの互換性を確保しなければいけません。apt-pinningは全く任意の操作で、著者が使うようにと勧めているわけではありません。

[注意] 注意

アーカイブレベルのReleaseファイル(「アーカイブレベルの"Release"ファイル」参照)がapt_preferences(5)のルールに使われます。だから、apt-pinningはnormal Debian archivessecurity Debian archivesではスイート("suite")名を使って機能します。(これはUbuntuアーカイブとは異なります)。例えば"/etc/apt/preferences"ファイル中で、"Pin: release a=unstable"とはできますが、"Pin: release a=sid"とはできません。

[注意] 注意

非Debianアーカイブをapt-pinningの一部に使う場合には、それが提供されている対象の確認とその信頼性の確認をしましょう。例えば、UbuntuとDebianは混合して使うようにはなっていません。

[注意] 注意

"/etc/apt/preferences"ファイルを作成することなしでも、かなり複雑なシステム操作(「dpkgコマンドを使っての救済」「混合したアーカイブソースからのパッケージ」参照)がapt-pinningを使わずにできます。

単純化したapt-pinningテクニックの説明を次にします。

APTシステムは"/etc/apt/sources.list"ファイル中に規定された使えるパッケージソースから最高のPin-Priorityでアップグレードするパッケージを候補バージョンパッケージとして選択します。パッケージのPin-Priorityが1000より大きい場合には、このアップグレードするというバージョン制約が外れるのでダウングレードできるようになります(「緊急ダウングレード」参照)。

各パッケージのPin-Priority値は"/etc/apt/preferences"ファイル中の"Pin-Priority"項目にて規定されるか、そのデフォルト値が使われます。

表2.19 各パッケージソースタイプ毎のデフォルトPin-Priority値のリスト

デフォルトPin-Priority パッケージソースタイプ
990 ターゲットのリリースアーカイブ
500 通常アーカイブ
100 インストール済みアーカイブ
1 NotAutomaticアーカイブ

ターゲットのリリースアーカイブは次のようにして設定できます:

  • "/etc/apt/apt.conf"中にある、"APT::Default-Release "stable";"等の行によって。
  • "-t"オプションの引数によって、"apt-get install -t testing some-package"等によって。

NotAutomaticアーカイブは次のようにして設定できます:

複数アーカイブソースの<package>に関するPin-Priority値は"apt-cache policy <package>"の出力で表示されます:

  • "Package pin:"で始まる行は、<package>のみとの関連付けが"Package pin: 0.190"等と定義されている場合に、pinのパッケージバージョンを示します。
  • <package>とのみの関連付けが定義されていない場合には、"Package pin:"という行はありません。
  • <package>とのみの関連付けが定義されている場合のPin-Priority値は、全バージョン文字列の右側に"0.181 700"等としてリストされます。
  • <package>とのみの関連付けが定義されていない場合には、全バージョン文字列の右側に"0"が"0.181 0"等としてリストされます。
  • アーカイブのPin-Priority値("/etc/apt/preferences"ファイル中に"Package: *"として定義)はアーカイブへのパスの左側に、"200 http://backports.org etch-backports/main Packages"等としてリストされます。

testingを追跡しながら、unstableにある特定の新規アップストリームバージョンのパッケージが定常的にアップグレードされる、apt-pinningテクニックの例を次に示します。全ての必要なアーカイブを"/etc/apt/sources.list"ファイル中に次のようにリストします:

deb http://ftp.us.debian.org/debian/ testing main contrib non-free
deb http://ftp.us.debian.org/debian/ unstable main contrib non-free
deb http://security.debian.org/ testing/updates main contrib

"/etc/apt/preferences"を次のように設定する:

Package: *
Pin: release a=testing
Pin-Priority: 500

Package: *
Pin: release a=unstable
Pin-Priority: 200

"<package-name>"という名前のパッケージとその依存ファイルをunstableアーカイブからこの設定の下でインストールしたい場合、"-t"オプションを使ってターゲットリリースを切り替える(unstableのPin-Priorityが990になる)次のコマンドを実行します:

$ sudo apt-get install -t unstable <package-name>

この設定では、通常の"apt-get upgrade"や"apt-get dist-upgrade" (もしくはsqueezeの場合、"aptitude safe-upgrade"や"aptitude full-upgrade")の実行は、testingアーカイブからインストールされたパッケージは最新のtestingアーカイブを使ってアップグレードし、unstableアーカイブからインストールされたパッケージは最新のunstableアーカイブを使ってアップグレードします。

[注意] 注意

"/etc/apt/sources.list"ファイルから"testing"の項目を削除しないように注意しましょう。"testing"項目がその中にないと、APTシステムは最新のunstableアーカイブを使ってアップグレードしようとします。

[ティップ] ティップ

著者は上記操作のすぐ後に"/etc/apt/sources.list"ファイルを編集して"unstable"アーカイブ項目をコメントアウトします。こうすることで、最新のunstableアーカイブによってunstableからインストールされたパッケージをアップグレードしなくなりますが、"/etc/apt/sources.list"ファイル中に項目が多すぎてアップデートのプロセスが遅くなることをさけられます。

[ティップ] ティップ

もし"/etc/apt/preferences"ファイル中で"Pin-Priority: 200"の代わりに"Pin-Priority: 20"が用いられた場合は、"/etc/apt/sources.list"ファイルの中の"testing"項目が削除されようと、Pin-Priority値は100のインストール済みパッケージはunstableアーカイブによってアップグレードされる事はありません。

最初の"-t unstable"によるインストール無しに、unstableの特定パッケージを自動的に追跡したい場合、"/etc/apt/preferences"ファイルを作りそのトップにこれらパッケージを明示的に次のようにリストします:

Package: <package-1>
Pin: release a=unstable
Pin-Priority: 700

Package: <package-2>
Pin: release a=unstable
Pin-Priority: 700

...

以上で、各特定パッケージに関してPin-Priority値が設定されます。例えば最新のunstableバージョンのこの"Debianリファレンス"を英語版で追跡するためには、"/etc/apt/preferences"ファイルに次の項目を設定します:

Package: debian-reference-en
Pin: release a=unstable
Pin-Priority: 700

Package: debian-reference-common
Pin: release a=unstable
Pin-Priority: 700
[ティップ] ティップ

このapt-pinningテクニックはstableアーカイブを追跡している際にも有効です。著者の経験では、文書パッケージはunstableアーカイブからインストールしても今までいつも安全でした。

次にunstableを追跡しながらexperimentalにある特定の新規アップストリームバージョンのパッケージを取り込むapt-pinningテクニックの例を示します。すべての必要なアーカイブを"/etc/apt/sources.list"ファイルに次のようにリストします:

deb http://ftp.us.debian.org/debian/ unstable main contrib non-free
deb http://ftp.us.debian.org/debian/ experimental main contrib non-free
deb http://security.debian.org/ testing/updates main contrib

experimentalアーカイブのデフォルトのPin-Priority値は、NotAutomaticアーカイブ(「アーカイブレベルの"Release"ファイル」参照)なので、常に1(<<100)です。experimentalアーカイブにある特定パッケージを次回アップグレード時に自動的に追跡しようとしない限り、"/etc/apt/preferences"ファイル中でexperimentalアーカイブを使うためにPin-Priority値を明示的に設定する必要はありません。

2.7.4. VolatileとBackports.org

stableのためのアップグレードパッケージを提供する、debian-volatile projectbackports.orgアーカイブがあります。

[警告] 警告

lenny-backportsvolatile-sloppy等のNotAutomaticアーカイブの中にあるパッケージ全てを使ってはいけません。あなたの必要性に適合する選択されたパッケージだけを使いましょう。

[注意] 注意

backports.orgは、提供しているパッケージがDebian開発者によってサインされているとはいえ、非Debianアーカイブです。

[注意] 注意

アーカイブレベルのReleaseファイル(「アーカイブレベルの"Release"ファイル」参照)がapt_preferences(5)のルールで使われます。だからvolatile Debianアーカイブではapt-pinningは"コード"名を使って機能します。これは他のDebianアーカイブと異なります。例えばvolatile Debianアーカイブのための"/etc/apt/preferences"の中で、"Pin: release a=lenny"とできますが、"Pin: release a=stable"とはできません。

次にlennyvolatileを追跡しながらlenny-backportsにある特定の新規アップストリームバージョンのパッケージを取り込むapt-pinningテクニックの例を示します。すべての必要なアーカイブを"/etc/apt/sources.list"ファイルに次のようにリストします:

deb http://ftp.us.debian.org/debian/ lenny main contrib non-free
deb http://security.debian.org/ lenny/updates main contrib
deb http://volatile.debian.org/debian-volatile/ lenny/volatile main contrib non-free
deb http://volatile.debian.org/debian-volatile/ lenny/volatile-sloppy main contrib non-free
deb http://backports.org/debian/ lenny-backports main contrib non-free

backports.orgvolatile-sloppyアーカイブのデフォルトのPin-Priority値は、NotAutomaticアーカイブ(「アーカイブレベルの"Release"ファイル」参照)なので、常に1(<<100)です。experimentalアーカイブにある特定パッケージを次回アップグレード時に自動的に追跡しようとしない限り、"/etc/apt/preferences"ファイル中でbackports.orgvolatile-sloppyアーカイブを使うためにPin-Priority値を明示的に設定する必要はありません。

"<package-name>"という名前のパッケージをその依存関係ともどもlenny-backportsアーカイブからインストールしたい時には、"-t"オプションでターゲットリリースを切り替えながら次のコマンドを使います:

$ sudo apt-get install -t lenny-backports <package-name>

特定のパッケージをアップグレードしたいときには、"/etc/apt/preferences"ファイルを作成しその中に全てのパッケージを次のように明示的にリストしなければいけません:

Package: <package-1>
Pin: release o=Backports.org archive
Pin-Priority: 700

Package: <package-2>
Pin: release o=volatile.debian.org
Pin-Priority: 700

...

また、"/etc/apt/preferences"ファイルを次のようにしてもよい:

Package: *
Pin: release a=stable , o=Debian
Pin-Priority: 500

Package: *
Pin: release a=lenny, o=volatile.debian.org
Pin-Priority: 500

Package: *
Pin: release a=lenny-backports, o=Backports.org archive
Pin-Priority: 200

Package: *
Pin: release a=lenny-sloppy, o=volatile.debian.org
Pin-Priority: 200

"apt-get upgrade"と"apt-get dist-upgrade" (もしくは、squeezeでは"aptitude safe-upgrade"と"aptitude full-upgrade")の実行は、stableアーカイブからインストールされたパッケージを最新のstableアーカイブを使ってアップグレードし、他のアーカイブからインストールされたパッケージを最新の"/etc/apt/sources.list"ファイルに記載された全てのアーカイブの最新の対応するアーカイブを使ってアップグレードします。

2.7.5. パッケージの自動ダウンロードとアップグレード

aptパッケージには、パッケージの自動ダウンロードのサポートする専用のcronスクリプト"/etc/cron.daily/apt"が同梱されています。このスクリプトはunattended-upgradesパッケージをインストールすることで自動アップグレード実行の機能拡張をします。これらは、"/usr/share/doc/unattended-upgrades/README"に記述されているように、"/etc/apt/apt.conf.d/02backup"と"/etc/apt/apt.conf.d/50unattended-upgrades"の中のパラメータでカスタマイズできます。

unattended-upgradesパッケージは基本的にstableシステムのセキュリティアップグレードのためです。既存のstableシステムが、自動アップグレードで壊される危険性が、セキュリティアップグレードがすでに閉じたセキュリティホールからの侵入者によりシステムが壊わされる危険性より小さいなら、パラメータを設定して自動アップグレードをするのも一計です:

APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Download-Upgradeable-Packages "1";
APT::Periodic::Unattended-Upgrade "1";

unstableシステムを使っている場合には、自動アップグレードするとシステムはいつの日か確実に壊われるので、それはしたくないでしょう。そんなunstableの場合でも、事前にパッケージをダウンロードするようにパラメータを設定して、インタラクティブなアップグレードをするために時間を節約したいでしょう:

APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Download-Upgradeable-Packages "1";
APT::Periodic::Unattended-Upgrade "0";

2.7.6. APTのよるダウンロードバンド幅の制限

APTによるダウンロードのバンド幅を例えば800Kib/sec (=100kiB/sec)に制限したい場合には、APTのパラメータを次のように設定します:

APT::Acquire::http::Dl-Limit "800";

2.7.7. 緊急ダウングレード

[注意] 注意

Debianでは設計としてはダウングレードを正式にサポートしません。緊急の回復処置の一部としてのみ実行されるべきです。こういう状況であるにもかかわらず、多くの場合にうまく機能することがある知られています。重要なシステムでは回復処置の後に全ての重要データをバックアップし、最初から新しいシステムを再インストールしましょう。

壊れたシステムアップグレードからの回復するために、候補バージョンを操作して新しいアーカイブから古いアーカイブにダウングレードすることがうまくいくかもしれません(「候補バージョンの調整」参照)。これは、何度も"dpkg -i <broken-package>_<old-version>.deb"コマンドを実行する退屈な作業をしないでよくする方法です(「dpkgコマンドを使っての救済」参照)。

unstableからtestingを追跡するようにダウングレードするには、"/etc/apt/sources.list"ファイルを、次から:

deb http://ftp.us.debian.org/debian/ sid main contrib non-free

次へと変更します:

deb http://ftp.us.debian.org/debian/ squeeze main contrib

"/etc/apt/preferences"を次のように設定する:

Package: *
Pin: release a=testing
Pin-Priority: 1010

そして、"apt-get dist-upgrade"を実行して、システム全体にわたってパッケージのダウングレードを強制します。この特殊な"/etc/apt/preferences"ファイルはダウングレード実行後削除してください。

[ティップ] ティップ

依存関係の問題を最小限とすべく、できるだけ多くのパッケージを削除(removeで、完全削除purgeではありません!)しましょう。システムのダウングレードのためには手動でいくつかのパッケージを削除とインストールしなければいけないかも知れません。LinuxカーネルやブートローダやudevやPAMやAPTやネットワーク関係のパッケージやそれらの設定ファイルには特に注意が必要です。

2.7.8. 誰がパッケージをアップロードしたのか?

"/var/lib/dpkg/available"や"/usr/share/doc/package_name/changelog"の中にリストされたメンテナの名前は"誰がパッケージ化活動の背後にいるのか"に関していくばくかの情報を提供しますが、パッケージを実際にアップロードをした人がはっきりしません。devscriptsパッケージ中のwho-uploads(1)はDebianのソースパッケージを実際にアップロードした人を確定します。

2.7.9. equivsパッケージ

ソースからプログラムをコンパイルしてDebianパッケージを置換えたい際には、それを実際にローカルでDebian化してパッケージ(*.deb)して、私的アーカイブを使うのが好ましいです。

しかし、プログラムをソースからコンパイルして"/usr/local"にインストールすることを選んだ際には、パッケージ依存関係を満足させるための最後の手段としてequivsを使う必要があるかもしれません。

Package: equivs
Priority: extra
Section: admin
Description: Circumventing Debian package dependencies
 This is a dummy package which can be used to create Debian
 packages, which only contain dependency information.

2.7.10. 安定版システムへのパッケージ移植

stableシステムの部分アップグレードのためには、その環境内でソースパッケージを使ってパッケージをリビルドするのが好ましいです。こうすることでパッケージ依存関係による大掛かりなアップグレードをしないで済みます。まず、stableシステムの"/etc/apt/sources.list"に次の項目を追加します:

deb-src http://http.us.debian.org/debian unstable  main contrib non-free

次にコンパイルするのに必要なパッケージをインストールしソースパッケージをダウンロードします:

# apt-get update
# apt-get dist-upgrade
# apt-get install fakeroot devscripts build-essential
$ apt-get build-dep foo
$ apt-get source foo
$ cd foo*
  • 必要があればパッケージを調整します。
$ dch -i
  • パッケージバージョンを、"+bp1"を後ろに付けるなどして、先に進めます。
$ debuild
$ cd ..
# debi foo*.changes

2.7.11. APTのためのプロキシサーバー

Debianアーカイブの特定サブセクション全てをミラーするとディスクスペースとネットワークのバンド幅の大いなる無駄遣いですので、LAN上に多くのシステムを管理している際にはAPTのためのローカルのプロキシサーバーを設置することを考えるのは良いことです。APTは、apt.conf(5) とか"/usr/share/doc/apt/examples/configure-index.gz"に説明されたようにして、汎用のsquidのような ウエッブ(http)プロキシサーバー(「Other network application servers」参照)を使うように設定できます。"$http_proxy"環境変数による設定は、"/etc/apt/apt.conf"ファイル中の設定より優先します。

Debianアーカイブ専用のプロキシツールがあります。実際に使う前にBTSをチェック下さい。

表2.20 Debianアーカイブ専用のプロキシツールのリスト

パッケージ popcon サイズ 説明
approx V:0.2, I:0.3 3860 Debianアーカイブファイルのキャッシュプロキシサーバー(コンパイルされたOCamlプログラム)
apt-proxy V:0.4, I:0.5 428 Debianアーカイブプロキシと部分ミラー作成機(Pythonプログラム)
apt-cacher V:0.3, I:0.5 244 Debianパッケージとソースファイルのキャッシュプロキシ(Perlプログラム)
apt-cacher-ng V:0.17, I:0.2 708 ソフトウエアパッケージの頒布ためのキャッシュプロキシ(コンパイルされたC++プログラム)
debtorrent V:0.14, I:0.2 1173 Debianパッケージのためのbittorrentプロキシ(Pythonプログラム)

[注意] 注意

Debianがそのアーカイブ構造を再編した際に、このような専用のプロキシツールはパッケージメンテナによるコードの修正が必要で、一定期間使えなくなることがあります。一方、汎用のウエッブ(http)プロキシは比較的堅牢ですしそのような変化に合わすのも簡単です。

2.7.12. 小さな公開パッケージアーカイブ

近代的なセキュアAPTシステム(「トップレベルの"Release"ファイルと信憑性」参照)と互換性のある小規模のパブリックアーカイブを作る例を次に示します。まず、いくつかの仮定をします:

  • アカウント名: "foo"
  • ホスト名: "www.example.com"
  • 必要なパッケージ: apt-utilsgnupg等のパッケージ。
  • URL: "http://www.example.com/~foo/"は"/home/foo/public_html/index.html"を表示します。
  • パッケージのアーキテクチャ: "amd64"

あなたのサーバーシステム上でのAPTアーカイブの1回だけのセットアップ:

  • サーバーシステム上のFooのアーカイブキーを作成:
$ ssh foo@www.example.com
$ gpg --gen-key
...
$ gpg -K
...
sec   1024D/3A3CB5A6 2008-08-14
uid                  Foo (ARCHIVE KEY) <foo@www.example.com>
ssb   2048g/6856F4A7 2008-08-14
$ gpg --export -a 3A3CB5A6 >foo.public.key
  • Fooのアーカイブキーは"3A3CB5A6"
  • "foo.public.key"ファイルを公開します。
  • "Origin: Foo"というアーカイブツリーを作成します:
$ umask 022
$ mkdir -p ~/public_html/debian/pool/main
$ mkdir -p ~/public_html/debian/dists/unstable/main/binary-amd64
$ mkdir -p ~/public_html/debian/dists/unstable/main/source
$ cd ~/public_html/debian
$ cat > dists/unstable/main/binary-amd64/Release << EOF
Archive: unstable
Version: 4.0
Component: main
Origin: Foo
Label: Foo
Architecture: amd64
EOF
$ cat > dists/unstable/main/source/Release << EOF
Archive: unstable
Version: 4.0
Component: main
Origin: Foo
Label: Foo
Architecture: source
EOF
$ cat >aptftp.conf <<EOF
APT::FTPArchive::Release {
  Origin "Foo";
  Label "Foo";
  Suite "unstable";
  Codename "sid";
  Architectures "amd64";
  Components "main";
  Description "Public archive for Foo";
};
EOF
$ cat >aptgenerate.conf <<EOF
Dir::ArchiveDir ".";
Dir::CacheDir ".";
TreeDefault::Directory "pool/";
TreeDefault::SrcDirectory "pool/";
Default::Packages::Extensions ".deb";
Default::Packages::Compress ". gzip bzip2";
Default::Sources::Compress "gzip bzip2";
Default::Contents::Compress "gzip bzip2";

BinDirectory "dists/unstable/main/binary-amd64" {
  Packages "dists/unstable/main/binary-amd64/Packages";
  Contents "dists/unstable/Contents-amd64";
  SrcPackages "dists/unstable/main/source/Sources";
};

Tree "dists/unstable" {
  Sections "main";
  Architectures "amd64 source";
};
EOF

あなたのサーバーシステム上のAPTアーカイブ内容の繰り返しアップデート:

  • 次に示す内容の"~/.dupload.conf"を設定したクライアントで"dupload -t foo changes_file"を実行することで、全てのパッケージファイルを"~foo/public_html/debian/pool/main/"に置きます:
$cfg{'foo'} = {
  fqdn => "www.example.com",
  method => "scpb",
  incoming => "/home/foo/public_html/debian/pool/main",
  # The dinstall on ftp-master sends emails itself
  dinstall_runs => 1,
};

$cfg{'foo'}{postupload}{'changes'} = "
  echo 'cd public_html/debian ;
  apt-ftparchive generate -c=aptftp.conf aptgenerate.conf;
  apt-ftparchive release -c=aptftp.conf dists/unstable >dists/unstable/Release ;
  rm -f dists/unstable/Release.gpg ;
  gpg -u 3A3CB5A6 -bao dists/unstable/Release.gpg dists/unstable/Release'|
  ssh foo@www.example.com  2>/dev/null ;
  echo 'Package archive created!'";

dupload(1)が起動するpostuploadフックスクリプトがアップロード毎に更新されたアーカイブファイルを作成します。

この小規模のパブリックアーカイブをクライアントシステムのapt行に追加できます:

$ sudo bash
# echo "deb http://www.example.com/~foo/debian/ unstable main" \
   >> /etc/apt/sources.list
# apt-key add foo.public.key
[ティップ] ティップ

もしローカルファイルシステム上にアーカイブがある場合には、上記の代わりに"deb file:///home/foo/debian/ …"が使えます。

2.7.13. システム設定の記録/コピー

パッケージとdebconfの選択状態のローカルコピーを作るには:

# dpkg --get-selections '*' > selection.dpkg
# debconf-get-selections    > selection.debconf

ここで、"*"は"selection.dpkg"が"purge"に関するパッケージ項目も含めるようにします。

これら2ファイルを他のコンピュータに移動し、次のようにしてインストールします:

# dselect update
# debconf-set-selections < myselection.debconf
# dpkg --set-selections  < myselection.dpkg
# apt-get -u dselect-upgrade    # or dselect install

実質的に同じ設定でクラスターとなった多くのサーバーを管理することをお考えの場合には、専用パッケージであるfai等を使って全システムを管理することを考えましょう。

2.7.14. 外来のバイナリパッケージを変換やインストールする

alien(1)を使うと、Red HatのrpmやStampedeのslpやSlackwareのtgzやSolarisのpkgファイルフォーマットをDebianのdebパッケージに変換できます。あなたのシステムにインストールしたパッケージに替えて他のLinuxディストリビューション由来のパッケージを使いたい際には、alienを使って変換しインストールします。alienはLSBパッケージをサポートします。

[警告] 警告

alien(1)はsysvinitlibc6libpam-modules等の必須のシステムパッケージを置き換えるために使うべきではありません。実質的にはalien(1)は、LSB準拠か静的にリンクされたnon-freeのバイナリのみで提供されるパッケージにのみ使われるべきです。フリーソフトの場合は、ソースパッケージを使い本物のDebianパッケージを作るべきです。

2.7.15. dpkgを使わずにパッケージを開梱

現行の"*.deb"パッケージの内容は、どんなUnix的環境でも標準のar(1)とtar(1)を使っうことで、dpkg(1)を使うこと無く開梱できます。

# ar x /path/to/dpkg_<version>_<arch>.deb
# ls
total 24
-rw-r--r-- 1 bozo bozo  1320 2007-05-07 00:11 control.tar.gz
-rw-r--r-- 1 bozo bozo 12837 2007-05-07 00:11 data.tar.gz
-rw-r--r-- 1 bozo bozo     4 2007-05-07 00:11 debian-binary
# mkdir control
# mkdir data
# tar xvzf control.tar.gz -C control
# tar xvzf data.tar.gz -C data

パッケージの内容はmcコマンドを使っても閲覧できます。

2.7.16. パッケージ管理の追加参考文書

以下を参照:

  • aptitude(8)とdpkg(1)とtasksel(8)とapt-get(8)とapt-config(8)とapt-key(8)とsources.list(5)とapt.conf(5)とapt_preferences(5);
  • "/usr/share/doc/apt-doc/guide.html/index.html"と"/usr/share/doc/apt-doc/offline.html/index.html" from the apt-doc package;
  • aptitude-doc-enパッケージに入っている、"/usr/share/doc/aptitude/html/en/index.html"。

正規の詳細なDebianアーカイブに関する2次情報は次にあります:

Debianユーザ向けのDebianパッケージ作成の入門書は次です:

第3章 システムの初期化

Debianシステムが以下に起動され設定されるかの知っていることはシステム管理者として賢明である。正確で詳細な情報がインストールされたパッケージのソースや文書中にあるとは言え、我々ほとんどにとってちょっと大変過ぎます。

著者などの過去の知見に基づきDebianシステムの要点とそれらの設定の簡単な参考となる概論を提供するように勤めました。Debianシステムは動く標的なので、システムの状況が変わっているかもしれません。システムに変更を加える前に、各パッケージの最新文書を参照して下さい。

3.1. ブートストラッププロセスの概要

コンピュータシステムは、電源投入イベントからユーザに機能の完備したオペレーティングシステム(OS)を提供するまでブートストラッププロセスを数段通過します。

単純化のため、デフォルトのインストールをした典型的なPCプラットフォームに限定し議論します。

典型的なブートストラッププロセスは4段ロケットのようです。各段のロケットは次の段のロケットにシステムのコントロールを引き継ぎます。各段は次に対応します:

  • 1段目: BIOS
  • 2段目: ブートローダ
  • 3段目: ミニDebianシステム
  • 4段目: 通常のDebianシステム

もちろん、これらに関して異なる設定をすることはできます。例えば、自分自身で専用カーネルをコンパイルした場合、ミニDebianシステムのステップをスキップできます。自分自身で確認するまでは、あなたのシステムがこの様になっていると決めつけないでください。

[注意] 注意

伝統的なPCプラットフォームでないSUNとかMacintoshシステム等では、ROM上のBIOSやディスク上のパーティション(「パーティション設定」)が非常に異なっているかもしれません。そのような場合にはプラットフォーム特定の文書をどこかで求めて下さい。

3.2. 1段目: BIOS

BIOSは電源投入イベントが引き起こすブートプロセスの1段目です。CPUのプログラムカウンターが電源投入イベントで初期化され、読み出し専用メモリ(ROM)上にあるBIOSが特定のメモリアドレスから実行されます。

BIOSはハードウエアーの基本的な初期化(POST: 電源投入時自己診断)を行い、システムのコントロールをあなたが提供する次のステップにシステムのコントロールを引き継ぎます。BIOSは通常ハードウエアによって供給されます。

BIOS初期画面はどのキーを押すとBIOS設定画面に入ってBIOSの挙動を設定できるかを通常表示しています。よく使われるキーはF1やF2やF10やEscやInsやDelです。もしBIOS初期画面が洒落たグラフィック表示でかくされている場合、Esc等の何らかのキーをおすとこれを無効にできます。こういったキーはハードウエアーに大いに依存します。

BIOSが起動するコードのハードウエア上の場所や優先順位はBIOS設定画面から選択できます。典型的には最初に見つかった選択されたデバイス(ハードディスクやフロッピーディスクやCD-ROM等)の最初の数セクターがメモリ上にロードされこの初期コードが実行されます。この初期コードは次のいずれでもよろしい:

  • ブートローダコード
  • FreeDOSのような踏み石OSのカーネルコード
  • この小さなスペースに収まればターゲットOSのカーネルコード

典型的にはプライマリハードディスクの指定されたパーティションからシステムが起動されます。伝統的PCのハードディスクの最初の2セクターにマスターブートレコード(MBR)が含まれます。ブート選択に含まれるディスクのパーティション情報はこのMBRの最後に記録されています。BIOSから実行される最初のブートローダコードは残りの部分を占めます。

3.3. 2段目: ブートローダ

ブートローダはBIOSによって起動されるブートプロセスの2段目です。それはシステムのカーネルイメージとinitrdイメージをメモリにロードし、それらにコントロールを引き継ぎます。このinitrdイメージはrootファイルシステムイメージで、そのサポートは使われるブートローダ次第です。

Debianシステムは通常Linuxカーネルをデフォルトのシステムカーネルとして使っています。現在の2.6カーネルにとってのinitrdイメージは技術的に言うならinitramfs (初期RAMファイルシステム)イメージです。initramfsイメージはrootファイルシステム中のファイルのgzipされたcpioアーカイブです。

Debianシステムのデフォルトインストールでは、GRUBブートローダの1段目のコードをPCプラットホームのMBRの中に置きます。多くのブートローダと設定の選択肢があります。

表3.1 ブートローダのリスト

ブートローダ パッケージ popcon サイズ initrd 説明
GRUB Legacy grub V:24, I:91 1908 サポート ディスクパーティションやvfatやext3等のファイルシステムを理解するぐらいスマートです。(lennyのデフォルト)
GRUB 2 grub-pc V:0.9, I:3 1600 サポート ディスクパーティションやvfatやext3等のファイルシステムを理解するぐらいスマートです。
GRUB 2 grub-rescue-pc V:0.04, I:0.5 2852 サポート GRUB 2のブート可能なレスキューイメージ(CDとフロッピー) (PC/BIOSバージョン)
Lilo lilo V:0.7, I:3 1192 サポート ハードディスク上のセクター位置に依存します。(古い)
Isolinux syslinux V:1.1, I:7 160 サポート ISO9660ファイルシステムを理解します。ブートCDに使われています。
Syslinux syslinux V:1.1, I:7 160 サポート MSDOSファイルシステム(FAT)理解します。ブートフロッピーで使われます。
Loadlin loadlin V:0.02, I:0.2 140 サポート 新しいシステムがFreeDOS/MSDOSシステムから起動されます。
Neil TurtonのMBR mbr V:1.0, I:6 96 非サポート MSDOSのMBRを代替するフリーソフトです。ディスクパーティションを理解するだけです。

[警告] 警告

grub-rescue-pcパッケージのイメージから作ったブート可能なレスキューメディア(CDかフロッピー)無しにブートローダを試してはいけません。これさえあると、ハードディスク上に機能するブートローダが無くともシステムの起動ができます。

GRUB Legacyのメニューの設定は"/boot/grub/menu.lst"にあります。例えば、次のような内容です:

title           Debian GNU/Linux
root            (hd0,2)
kernel          /vmlinuz root=/dev/hda3 ro
initrd          /initrd.img

GRUB 2のメニューの設定は"/boot/grub/grub.cfg"にあります。 "/etc/grub.d/*"の雛形と"/etc/default/grub"の設定から"/usr/sbin/update-grub"を使って自動的に作られます。例えば、次のような内容です:

menuentry "Debian GNU/Linux" {
        set root=(hd0,3)
        linux /vmlinuz root=/dev/hda3
        initrd /initrd.img
}

これらの例で、これらのGRUBパラメータは次の意味です:

表3.2 GRUBパラメータの意味。

GRUBパラメータ 意味
root GRUB legacyでは"(hd0,2)"またGRUB 2では"(hd0,3)"と設定することでプライマリディスクの3つ目のパーティションを使います。
kernel カーネルパラメータ"root=/dev/hda3 ro"とともに"/vmlinuz"にあるカーネルを使います。
initrd "/initrd.img"にあるinitrd/initramfsイメージを使います。

[注意] 注意

GRUB legacyプログラムが使うパーティション値はLinuxカーネルやユーティリティツールが使う値より1つ少ない数字です。GRUB 2プログラムはこの問題を修正します。

[ティップ] ティップ

UUID (「Accessing partition using UUID」参照)は、"/dev/hda3"のようなファイル名に代わるブロックの特定デバイスを確定するのに使え、例えば"root=UUID=81b289d5-4341-4003-9602-e254a17ac232 ro"です。

[ティップ] ティップ

チェインロード(連鎖導入)とよばれる技術を使うと、あるブートローダから他のブートローダを起動できます。

"info grub"とgrub-install(8)を参照下さい。

3.4. 3段目: ミニDebianシステム

ミニDebianシステムはブートローダによって起動されるブートプロセスの3段目です。メモリ上でルートファイルシステムとともにシステムカーネルを実行します。これはオプションの起動プロセスの準備段階です。

[注意] 注意

"ミニDebianシステム"は著者がこの3段目のブートプロセスを本文書中で記述するために作った言葉です。このシステムは一般にinitrdとかinitramfsシステムと呼ばれています。類似のメモリ上のシステムはDebianインストーラーでも使われています。

"/init"スクリプトはこのメモリ上のrootファイルシステムで最初に実行されるプログラムです。それはユーザスペースでカーネルを初期化し次の段階にコントロールを引き継ぐシェルプログラムです。このミニDebianシステムは、メインのブートプロセス始まる前にカーネルモジュールを追加したり、rootファイルシステムを暗号化されたファイルシステムとしてマウントする等のブートプロセスの柔軟性を提供します。

"break=init" 等をカーネルブートパラメータとして与えると、本部分のブートプロセスに割り込みrootシェルを獲得できます。この他の割り込み条件は"/init"スクリプトを参照下さい。このシェル環境はあなたの機器のハードウエアを詳細に検査できるだけ十分洗練されています。

ミニDebianシステムは機能を削ったシステムで、主にbusybox(1)というGNUツールで提供されます。

[注意] 注意

読み取りのみのrootファイルシステム上では、mountコマンドには"-n"オプションを option for mount command when you are on使う必要があります。

3.5. 4段目: 通常のDebianシステム

通常のDebianシステムはミニDebianシステムによって起動されるブートプロセスの4段目です。ミニDebianシステムのシステムカーネルはこの環境ででも実行され続けます。ルートファイルシステムはメモリ上から本当にハードディスク上にあるファイルシステムに切り替えられます。

"/sbin/init"プログラムが最初のプログラムとして実行され、メインのブートプロセス遂行します。Debianは通常sysv-rcによる伝統的なsysvinitスキームを使います。詳細な説明は、init(8)とinittab(5)と"/usr/share/doc/sysv-rc/README.runlevels.gz"を参照下さい。次にこのメインのブートプロセスの簡略化した概論を記します:

  1. Debianシステムはrunlevel N (無し)に入り、"/etc/inittab"の記述にしたがいシステムを初期化します。
  2. Debianシステムはrunlevel Sに入り、シングルユーザモード下でハードウエアーの初期化等を完了するシステム初期化をします。
  3. Debianシステムは指定されたmulti-user runlevels (2 to 5)の内の1つに入り、システムサービスを開始します。

マルチユーザモードで使われる最初のrunlevelは、"init="というカーネルブートパラメータもしくは"/etc/inittab"の"initdefault"行で指定されます。インストールされたままのDebianシステムはrunlevel 2で開始します。

initシステムが実行する全てのスクリプトは"/etc/init.d/"ディレクトリの中にあります。

[ティップ] ティップ

単一の設定ファイル"/etc/runlevel.conf"を使うsysv-rcパッケージ提供のブートメカニズム代替のブートメカニズムに関しては、file-rcパッケージを参照下さい。"/etc/init.d/rc"と"/etc/init.d/rcS"と"/usr/sbin/update-rc.d"と"/usr/sbin/invoke-rc.d"のスクリプトによって両メカニズムには互換性があります。

3.5.1. runlevelの意味

runlevelはその設定に1つのディレクトリを使い特定の意味があります:

表3.3 runlevelsとその意味のリスト。

runlevel ディレクトリ 意味
N 無し システムのブートアップ(無し)。"/etc/rcN.d/"ディレクトリはありません。
0 /etc/rc0.d/ システム停止
S /etc/rcS.d/ ブート時のシングルユーザモード。小文字の"s"を別名として使えます。
1 /etc/rc1.d/ マルチユーザモードから切り替えたシングルユーザモード。
2 /etc/rc2.d/ マルチユーザモード
3 /etc/rc3.d/ ,,
4 /etc/rc4.d/ ,,
5 /etc/rc5.d/ ,,
6 /etc/rc6.d/ システム再起動。
7 /etc/rc7.d/ 有効なマルチユーザモードですが通常使われません。
8 /etc/rc8.d/ ,,
9 /etc/rc9.d/ ,,

コンソールからrunlevelを、例えば4に、次のようにして変更できます:

$ sudo telinit 4
[注意] 注意

Debianシステムは2から5のrunlevels間で如何なる意味の違いも事前に付与しません。Debianシステムのシステム管理者はこれに変更を加えられます。(つまりDebianは、Red Hat LinuxともSun Microsystems社のSolarisともHewlett Packard社のHP-UXともIBM社のAIXとも…違います。)

[注意] 注意

Debianシステムは7から9のrunlevelsに対応するディレクトリをパッケージインストール時に埋めることはありません。伝統的なUnixバリアントはこれらのrunlevelsを使いません。

3.5.2. runlevelの設定

runlevelのディレクトリ中のシムリンク名前は、"S<2-digit-number><original-name>"か"K<2-digit-number><original-name>"という形式となっています。2桁数字はスクリプトの実行順序決定に使われます。"S"は"開始(Start)"と言う意味で、"K"は"停止(Kill)"と言う意味です。

init(8)かtelinit(8)コマンドがrunlevelを"<n>"に変更すると:

  1. "/etc/rc<n>.d/"中の"K"で始まるスクリプト名が、引数"stop"1つつけてアルファベット順に実行されます。(サービス停止)
  2. "/etc/rc<n>.d/"中の"S"で始まるスクリプト名が、引数"start"1つつけてアルファベット順に実行されます。(サービス開始)

例えば、runlevelのディレクトリに"S10sysklogd"と"S20exim4"があった時に、"S20exim4"の前に"S10sysklogd"が実行されます。

[警告] 警告

メンテナよりあなたのほうが知識があるのでもなければ"/etc/rcS.d/"の中のシムリンクに変更を加えようとするのはお勧めできません。

3.5.3. runlevel管理例

例えば、Red Hat Linuxのようなrunlevelを設定してみましょう、つまり:

  • runlevel=3をデフォルトとしてシステムを起動します、
  • runlevel=(0,1,2,6)でgdm(1)を起動しません、
  • runlevel=(3,4,5)でgdm(1)を起動します。

これは、"/etc/inittab"ファイルをエディタで変更して起動するrunlevel変更し、sysv-rc-confbum等の使いやすいrunlevel管理ツールを使ってrunlevelを編集することでできます。こうする代わりにコマンドラインだけを使うなら、(gdmパッケージをデフォルトでインストールしディスプレイマネージャとして選択した後に)次に示すようにします:

# cd /etc/rc2.d ; mv S21gdm K21gdm
# cd /etc ; perl -i -p -e 's/^id:.:/id:3:/' inittab

ディスプレイマネージャデーモン(xdmgdmkdmwdm)が起動される際には、"/etc/X11/default-display-manager"ファイル内容を確認する事を覚えておいて下さい。

[注意] 注意

startx(1)コマンドを使えば、どのコンソールシェルからもXが起動できます。

3.5.4. 各initスクリプトのデフォルトのパラメータ

"/etc/init.d/"の中の各initスクリプトのデフォルトパラメータは、"/etc/default/"の中の環境変数のアサインメントのみを含む対応ファイルによって与えられます。このディレクトリ名の選択はDebianシステム特定です。それは、Red Hat Linuxや他のディストリビューションで使われる"/etc/sysconfig"ディレクトリにほぼ相当します。例えば、"/etc/default/cron"を使うと"/etc/init.d/cron"がどう機能するかを制御できます。

"/etc/default/rcS"ファイルを使うとmotd(5)やsulogin(8)等のブート時のデフォルトをカスタマイズできます。

もしそのような変数の変更で希望の挙動が得られない場合には、initスクリプト自体を変更することができます。これらスクリプトは管理者が編集可能な設定ファイルです。

3.5.5. ホスト名

カーネルがシステムのホスト名を維持管理します。initスクリプトの"/etc/init.d/hostname.sh"は、(hostnameコマンドを使って)"/etc/hostname"に保存された名前を使ってブート時にホスト名を設定します。このファイルには、完全修飾ドメイン名ではなく、システムのホスト名のみが含まれているべきです。

現在のホスト名を確認するには、hostname(1)を引数無しで実行します。

3.5.6. ネットワークインターフェースの初期化

ネットワークインターフェースはブート時にシングルユーザモード下でinitスクリプト"/etc/init.d/ifupdown-clean"と"/etc/init.d/ifupdown"によって初期化されます。それらの設定に関しては、5章ネットワークの設定を参照下さい。

3.5.7. ネットワークサービスの初期化

多くのネットワークサービス(6章ネットワークアプリケーション参照)はブート時に、例えば"/etc/init.d/exim4"にシムリンクされている"/etc/rc2.d/S20exim4"(RUNLEVEL=2の場合)等という、initスクリプトによってデーモンプロセスとして起動されます。

ネットワークサービスによってはスーパーサーバーinetd(もしくはその同等)を用いて必要に応じて起動されます。inetdは、"/etc/init.d/inetd"にシムリンクされた"/etc/rc2.d/S20inetd"(RUNLEVEL=2の場合)によってブート時に起動されます。基本的に、inetdは一つの実行デーモンによりいくつかの他のデーモンを起動できるようにすることで、システムのロードを下げます。

サービス要求が到達する度に、そのプロトコルとサービスが"/etc/protocols"と"/etc/services"というデータベースを照覧することで確認されます。さらにinetdは、"/etc/inetd.conf"の中にある通常のインターネットサービスか、"/etc/rpc.conf"の中にあるSun RPC準拠サービスを照覧します。

システムのセキュリティのために"/etc/inetd.conf"にある不使用のサービスは確実にディスエーブルしましょう。NFS他のRPCを使うプログラムためにはSunRPCサービスはアクティブにする必要があります。

時々、inetdが対象となるサーバーを直接起動せずに、対象となるサーバーを名を"/etc/inetd.conf"中に引数とし記載したTCPデーモンラッパープログラムtcpd(8)を起動することがあります。

もし最近のDebianシステムでリモートアクセスで問題に会った場合には、"/etc/hosts.deny"中に"ALL:PARANOID"という文言があるならコメントアウトしましょう。

詳しいことは、inetd(8)とinetd.conf(5)とprotocols(5)とservices(5)とtcpd(8)とhosts_access(5)とhosts_options(5)を参照下さい。

Sun-RPCに関してさらに詳しいことは、rpcinfo(8)とportmap(8)と"/usr/share/doc/portmap/portmapper.txt.gz"を参照下さい。

3.5.8. システムメッセージ

ログファイルとスクリーン上の両方のシステムメッセージに関して、"/etc/syslog.conf"によってカスタマイズできます。syslogd(8)とsyslog.conf(5)を参照下さい。さらに「Log analyzer」も参照下さい。

3.5.9. カーネルメッセージ

ログファイルとスクリーン上の両方のカーネルメッセージに関して、"/etc/init.d/klogd"によってカスタマイズできます。このスクリプト中に"KLOGD='-c 3'"と設定し"/etc/init.d/klogd restart"を実行しましょう。klogd(8)参照下さい。

エラーメッセージのレベルを直接変更してもいいです:

# dmesg -n3

ここで:

表3.4 カーネルエラーレベルのリスト

エラーレベル値 エラーレベル名 意味
0 KERN_EMERG システムは不安定
1 KERN_ALERT 直ぐアクションが必要
2 KERN_CRIT クリチカルなコンディション
3 KERN_ERR エラーコンディション
4 KERN_WARNING 警告コンディション
5 KERN_NOTICE ノーマルだが重要なコンディション
6 KERN_INFO 情報
7 KERN_DEBUG デバグレベルのメッセージ

3.5.10. udevシステム

Linuxカーネル 2.6では、udevシステムがハードウエアの自動検出と初期化のメカニズムを提供します(udev(7)参照)。カーネルが各デバイスを発見すると、udevシステムはsysfsファイルシステム(「procfsとsysfs」参照)からの情報を使いユーザプロセスを起動し、modprobe(8)プログラム(「カーネルモジュール初期化」参照)を使ってそれをサポートする必要なカーネルモジュールをロードし、対応するデバイスノードを作成します。

[ティップ] ティップ

もし"/lib/modules/<kernel-version>/modules.dep"が何らかの理由でdepmod(8)によって適切に生成されていなかった場合には、モジュールはudevシステムによる期待にそってロードされないかもしれません。これを修正するには、"depmod -a"を実行しましょう。

デバイスノード名は"/etc/udev/rules.d/"の中のファイルによって設定できます("/usr/share/doc/udev/writing_udev_rules/index.html"参照)。

udevシステムは少々動くターゲットなので、詳細は他のドキュメントに譲り、ここでは最小限の記述に止めます。

3.5.11. カーネルモジュール初期化

modprobe(8)プログラムは、ユーザプロセスからカーネルモジュールを追加や削除することで実行中のLinuxカーネルの設定を可能にします。udevシステム(「udevシステム」参照)は、その起動を自動化しカーネルモジュールの初期化を補助します。

ハードウエアー以外のモジュールや特殊なハードウエアーモジュールは、次です:

  • ポイント間ネットワークデバイス(TUN)と仮想Ethernetネットワークデバイス(TAP)を提供する、TUN/TAPモジュール、
  • netfilterファイアーウォール機能(iptables(8)と「Netfilter」)を提供するnetfilterモジュール、
  • ワッチドッグタイマードライバのモジュールは、"/etc/modules"ファイルの中にリストすることでプリロードされます(modules(5)参照)。

modprobe(8)プログラムのための設定ファイルは、modprobe.conf(5)で説明されているように"/etc/modprobes.d/"ディレクトリの下にあります。(あるカーネルモジュールが自動ロードされるのを避けるには、"/etc/modprobes.d/blacklist" ファイル中にブラックリスしましょう。)

depmod(8)プログラムによって生成される"/lib/modules/<version>/modules.dep"ファイルは、modprobe(8)プログラムによって使われるモジュール依存関係を記述します。

[注意] 注意

ブート時にmodprobe(8)を使ってのモジュールロードの問題に出会った場合には、"depmod -a"として"modules.dep"を再構築をするとこの様な問題が解消できるかもしれません。

modinfo(8)プログラムはLinuxカーネルモジュールに関する情報を表示します。

lsmod(8)プログラムは"/proc/modules"の内容を読みやすい形式にして、どのカーネルモジュールが現在ロードされているかを表示します。

[ティップ] ティップ

あなたのシステム上の正確なハードウエアーを特定します。「Hardware identification」を参照下さい。

[ティップ] ティップ

ブート時に期待されるハードウエアー機能を有効となるように設定もできます。「ハードウエア設定」を参照下さい。

[ティップ] ティップ

あなたのデバイスのサポートは、カーネルを再コンパイルすれば追加できます。「カーネル」を参照下さい。

第4章 認証

人(またはプログラム)がシステムへのアクセスの要求をした際に、認証はその正体が信頼できるものだと確認します。

[警告] 警告

PAMの設定のエラーはあなたをあなた自身のシステムから締め出すかも知れません。レスキューCDを手元に置くか代替ブートパーティション設定を必ずしましょう。回復するには、それらを使ってシステムをブートしそこから修正しましょう。

4.1. 通常のUnix認証

通常のUnix認証はPAM(プラグ可能な認証モジュール)のもとでpam_unix.so(8)モジュールによって提供される。":"で分離されたエントリーを持つその3つの重要なコンフィギュレーションファイルは:

表4.1 3つのpam_unix(8)に関する重要なコンフィギュレーションファイル。

ファイル パーミッション(許可) ユーザ グループ 説明
/etc/passwd -rw-r--r-- root root (浄化された)ユーザアカウント情報。
/etc/shadow -rw-r----- root shadow 保護されたユーザアカウント情報。
/etc/group -rw-r--r-- root root グループ情報。

"/etc/passwd" ファイルの内容は:

...
user1:x:1000:1000:User1 Name,,,:/home/user1:/bin/bash
user2:x:1001:1001:User2 Name,,,:/home/user2:/bin/bash
...

passwd(5) に説明されているように、このファイルの ":" で分離されたエントリーそれぞれは:

  • ログイン名
  • パスワード規定エントリー
  • 数値のユーザID
  • 数値のグループID
  • ユーザ名またはコメント領域
  • ユーザのホームディレクトリ
  • ユーザのコマンドインタープリター(無いこともある)

"/etc/passwd"の2番目のエントリーは暗号化したパスワードのエントリーとして使われていました。"/etc/shadow"が導入された後は、このエントリーはパスワード規定エントリーとして使われています。

表4.2 "/etc/passwd"の2番目のエントリーの内容。

内容 意味
(空白) パスワード無しアカウント
x 暗号化したパスワードは"/etc/shadow"ファイルの中にある。
* このアカウントへのログイン不可
! このアカウントへのログイン不可

"/etc/shadow" ファイルの内容は:

...
user1:$1$Xop0FYH9$IfxyQwBe9b8tiyIkt2P4F/:13262:0:99999:7:::
user2:$1$vXGZLVbS$ElyErNf/agUDsm1DehJMS/:13261:0:99999:7:::
...

shadow(5)で説明されているように、このファイルの":"で分離されたエントリーそれぞれは:

  • ログイン名
  • 暗号化されたパスワード。最初が"$1$"で始まっているのはMD5暗号化が使われていることを示します。"*"はログイン不可を示します。
  • 1970年1月1日から、最後にパスワードが変更された日までの日数
  • パスワードが変更可能となるまでの日数
  • パスワードを変更しなくてはならなくなる日までの日数
  • パスワード有効期限が来る前に、ユーザが警告を受ける日数

"/etc/group"のファイル内容は:

...
group1:x:20:user1,user2
...

shadow(5)で説明されているように、このファイルの":"で分離されたエントリーそれぞれは:

  • グループ名
  • 暗号化されたパスワード(実際は使われていない)
  • 数値のグループID。
  • "," で分離されたユーザ名のリスト。

"/etc/gshadow"ファイルは"/etc/shadow"ファイルが"/etc/group"ファイルに対する機能と同様の機能がありますが、実際には使われていません。

[注意] 注意

もし"authoptionalpam_group.so"行が"/etc/pam.d/common-auth"に書き加えれ、"/etc/security/group.conf"に対応する設定がされていれば、実際のユーザのグループメンバーシップは動的に割り当てられます。pam_group(8)参照下さい。

[注意] 注意

base-passwd パッケージはユーザとグループに関する権威のあるリストが含まれます: "/usr/share/doc/base-passwd/users-and-groups.html"。

4.2. アカウントとパスワードの情報管理

アカウント情報管理のための重要コマンド:

表4.3 アカウント情報管理のためのコマンドリスト。

コマンド 機能
getent passwd <user_name> "<user_name>"のアカウント情報の閲覧
getent shadow <user_name> "<user_name>"のシャドーされたアカウント情報の閲覧
getent group <group_name> "<group_name>"のグループ情報の閲覧
passwd アカウントのパスワード管理
passwd -e アカウント開設のための一回だけ使えるパスワードの設定
chage パスワードのエージング情報管理

一部機能が機能するにはroot権限が必要な場合があります。パスワードとデータの暗号化はcrypt(3)参照下さい。

[注意] 注意

Debianが提供するalioth機器と同様なPAMとNSSの設定をされたシステム上では、ローカルの"/etc/passwd"や"/etc/group"や"/etc/shadow"の内容がシステムにアクティブに利用されていないことがあります。

4.3. 良好なパスワード

システムインストール時やpasswd(1)コマンドによってアカウント作成する際に次に記すようなセットからなる6から8文字の良好なパスワードpasswd(1)によると選択するべきです:

  • 小文字のアルファベット
  • 数字の0から9
  • 句読点
[警告] 警告

想像できるような単語はパスワードに選択禁止。

4.4. 暗号化されたパスワード作成

ソルトを使って暗号化されたパスワードを生成する独立のツールとして次があります:

表4.4 パスワード生成ツールのリスト。

パッケージ popcon サイズ コマンド 機能
whois V:11, I:89 344 mkpasswd crypt(3)ライブラリーの充実しすぎたフロントエンド
openssl V:29, I:90 2360 openssl passwd パスワードハッシュの計算(OpenSSL)。passwd(1ssl)

4.5. PAM と NSS

Debianシステムのような最新のUnix的システムはPAM(差し替え可能な認証モジュール:PluggableAuthenticationModules)NSS(ネームサービススイッチ:NameServiceSwitch)メカニズムをローカルのシステム管理者がそのシステム管理用に提供します。それらの役割をまとめると次の様になります:

  • PAM は、アプリケーションソフトウエアが使う柔軟な認証メカニズムを提供し、パスワードデータの交換に関与します。
  • NSSは、ls(1)andid(1)等のプログラムがユーザやグループの名前を得ためにC標準ライブラリー経由で頻用する柔軟なネームサービスメカニズムを提供します。

これらのPAMとNSSシステムは一貫した設定が必要です。

PAMとNSSシステムに関する注目のパッケージは:

表4.5 注目すべきPAMとNSSシステムのリスト。

パッケージ popcon サイズ 説明
libpam-modules V:82, I:99 972 差し替え可能な認証モジュール(基本サービス)
libpam-ldap V:1.8, I:4 404 LDAPインターフェースを可能にする差し替え可能な認証モジュール
libpam-cracklib V:0.8, I:1.8 132 cracklibのサポートを可能にする差し替え可能な認証モジュール
libpam-doc I:0.8 1156 差し替え可能な認証モジュール(htmlとtextの文書)
libc6 V:95, I:99 11496 GNU Cライブラリー: "ネームサービススイッチ"も提供する共有ライブラリー
glibc-doc I:4 1800 GNU C ライブラリー: マンページ
glibc-doc-reference I:1.5 12160 GNU C ライブラリー: infoとpdfとhtmlフォーマットでのリファレンスマニュアル(non-free)
libnss-mdns I:54 144 マルチキャストDNSを使った名前解決のためのNSSモジュール
libnss-ldap I:4 312 LDAPをネームサービスとして使うNSSモジュール
libnss-ldapd V:0.12, I:0.2 356 LDAPをネームサービスとして使うNSSモジュール(libnss-ldapの新たなフォーク)

  • libpam-doc中の"The Linux-PAM System Administrators' Guide"はPAM設定を学ぶ上で必須です。
  • glibc-doc-referenceの中の"System Databases and Name Service Switch"セクションはNSS設定を学ぶ上で必須です。
[注意] 注意

より大規模かつ最新のリストは"aptitudesearch'libpam-|libnss-'"コマンドを実行すると得られます。NSSという頭字語は "ネームサービススイッチ:NameServiceSwitch"と異なる"ネットワークセキュリティサービス:NetworkSecurityService"を指すこともあります。

[注意] 注意

PAMは個別プログラムに関する環境変数をシステム全体のデフォルト値に初期化する最も基本的な手段です。

4.5.1. PAMとNSSによってアクセスされるコンフィギュレーションファイル

PAM がアクセスする注目すべきコンフィギュレーションファイル:

表4.6 PAMがアクセスするコンフィギュレーションファイルのリスト。

設定ファイル 機能
/etc/pam.d/<プログラム名> "<program_name>"に関するPAMコンフィギュレーションの設定。pam(7)とpam.d(5)参照下さい。
/etc/nsswitch.conf 各サービスに関するエントリーによるNSSコンフィギュレーションの設定。nsswitch.conf(5)参照下さい。
/etc/nologin ユーザのログイン制限のためにpam_nologin(8)モジュールがアクセス。
/etc/securetty pam_securetty(8)モジュールによりrootアクセスに使うttyを制限します。
/etc/security/access.conf pam_access(8)モジュールによりアクセス制限を設定します。
/etc/security/group.conf pam_group(8)モジュールによりグループに基づく制約を設定する。
/etc/security/pam_env.conf pam_env(8)モジュールにより環境変数を設定します。
/etc/environment "readenv=1"引数を付きのpam_env(8)モジュールによって追加での環境変数を設定します。
/etc/default/locale "readenv=1envfile=/etc/default/locale"引数を付きのpam_env(8)モジュールによって追加でロケールを設定します。(Debian)
/etc/security/limits.conf pam_linits(8)モジュールによってリソース制限(ulimit, core, …)を設定します。
/etc/security/time.conf pam_time(8)モジュールによって時間制限を設定します。

パスワード選択の制限はpam_unix(8)とpam_cracklib(8)モジュールで実装されています。それらは引数を使って設定します。

[ティップ] ティップ

PAMモジュールはファイル名のサフィックスとして".so"を使います。

4.5.2. 最新の集中システム管理

集中化された軽量ディレクトリアクセスプロトコル(LDAP)を採用することで多くのネットワーク上のUnix的や非Unix的システムを最新の集中システム管理が実現できます。軽量ディレクトリアクセスプロトコルのオープンソース実装はOpenLDAPソフトウエアです。

LDAPサーバーは、libpam-ldaplibnss-ldapパッケージで提供されるPAMとNSSを使うことでDebianシステムにアカウント情報を提供します。この実現ためにはいくつかの設定が必要です(著者は本設定を使っていないため、本情報は完全に二次情報です。ご理解の上お読みください。):

  • スタンドアローンのLDAPデーモンであるslapd(8)等のプログラムを走らせることで集中化されたLDAPサーバーを設置します。
  • デフォルトの"pam_unix.so"に代えて"pam_ldap.so"を使うには"/etc/pam.d/"ディレクトリ中のPAMコンフィギュレーションファイルを変更します。
  • デフォルト("compat"または"file")に代えて"ldap"を使うには"/etc/nsswitch.conf"ファイル中のNSS設定を変更します。
  • Debianでは、"/etc/pam_ldap.conf"をlibpam-ldapの設定ファイル、"/etc/pam_ldap.secret"をrootのパスワードを保存するファイルとして使っています。
  • Debianでは、"/etc/pam_ldap.conf"をlibpam-ldapの設定ファイル、"/etc/pam_ldap.secret"をrootのパスワードを保存するファイルとして使っています。
  • パスワードのセキュリティ確保のためにlibpam-ldapSSL(もしくはTLS)接続を使うよう設定しなければいけません。
  • LDAPのネットワークオバーヘッドの犠牲はあるとはいえ、データの整合性確保のためにlibnss-ldapSSL(もしくはTLS)接続を使うように設定できます。
  • LDAP のネットワークトラフィックを減少させるためにLDAPサーチ結果を一時保持するためのnscd(8)をローカルで走らせるべきです。

libpam-docパッケージで提供されるpam_ldap.conf(5)や"/usr/share/doc/libpam-doc/html/"やglibc-docパッケージで提供される"infolibc'NameServiceSwitch'"といった文書を参照下さい。

同様に、これに代わる集中化されたシステムは次を使っても設定できます:

4.5.3. 「どうしてGNUのsuはwheelグループをサポートしないのか」

これはRichard M. Stallmanが書いた昔の"info su"の最後に書かれていた有名な文言です。ご心配は無用です。現在DebianにあるsuはPAMを使っているので"/etc/pam.d/su"の中の"pam_wheel.so"の行をエネーブルすることでsuを使えるのをrootグループに限定できます。

4.5.4. パスワード規則強化

libpam-cracklibパッケージをインストールすると、例えば"/etc/pam.d/common-password"に次のような行があれば、パスワード規則を強化できます:

lennyの場合:

password required pam_cracklib.so retry=3 minlen=9 difok=3
password required pam_unix.so use_authtok nullok md5

squeezeの場合:

password required pam_cracklib.so retry=3 minlen=9 difok=3
password [success=1 default=ignore] pam_unix.so use_authtok nullok md5
password requisite pam_deny.so
password required pam_permit.so

4.6. 他のアクセスコントロール

[注意] 注意

カーネルのセキューアーアテンションキー(SAK)機能の制限は「Alt-SysRq」を参照下さい。

4.6.1. sudo

sudoはシステム管理者がユーザに制限付きのroot権限を与え、そのroot活動を記録するように設計されたプログラムです。sudoはユーザの通常パスワードだけが必要です。sudoパッケージをインストールし、"/etc/sudoers"の中のオプションを設定することによりアクティベートしてください。"/usr/share/doc/sudo/examples/sudoersのコンフィギュレーション例を参照ください。

単一ユーザシステムにおける私のsudoの使い方(see「sudoの設定」)は自分自身の失敗からの防衛を目指しています。sudoを使うことは、常にrootアカウントからシステムを使うよりは良い方法だと個人的には考えます。例えば、次は"<some_file>"の所有者を"<my_name>"に変更します:

$ sudo chown <my_name> <some_file>

rootのパスワード(自分でシステムインストールをしたDebianユーザなら当然知っています)を知っていれば、どのユーザアカウントからいかなるコマンドも"su -c"とすればrootもとで実行できます。

4.6.2. SELinux

セキュリティ強化したLinux(SELinux)強制アクセス制御(MAC)ポリシーのある通常のUnix的な権限モデルより厳格な枠組みです。ある条件下ではrootの権限すら制限を受けます。

4.6.3. サーバーのサービスへのアクセスの制限

インターネットスーパーサーバーinetdは、"/etc/init.d/inetd"にシムリンクされた"/etc/rc2.d/S20inetd"(RUNLEVEL=2の場合)によってブート時に起動されます。基本的に、inetdは一つの実行デーモンによりいくつかの他のデーモンを起動できるようにすることで、システムのロードを下げます。

サービス要求が到達する度に、そのプロトコルとサービスが"/etc/protocols"と"/etc/services"というデータベースを照覧することで確認されます。さらにinetdは、"/etc/inetd.conf"の中にある通常のインターネットサービスか、"/etc/rpc.conf"の中にあるSun RPC準拠サービスを照覧します。

システムのセキュリティのために"/etc/inetd.conf"にある不使用のサービスは確実にディスエーブルしましょう。NFS他のRPCを使うプログラムためにはSun RPCサービスはアクティブにする必要があります。

時々、inetdが対象となるサーバーを直接起動せずに、対象となるサーバー名を"/etc/inetd.conf"中に引数とし記載したTCPデーモンラッパープログラムtcpd(8)を起動することがあります。この様な場合には、tcpdは要求を記録し"/etc/hosts.deny"や"/etc/hosts.allow"を用いた追加確認後で適切なサーバープログラムを起動します。

もし最近のDebianシステムでリモートアクセスで問題があった場合には、"/etc/hosts.deny"中に"ALL:PARANOID"という文言があるならコメントアウトしましょう。

詳しいことは、inetd(8)とinetd.conf(5)とprotocols(5)とservices(5)とtcpd(8)とhosts_access(5)とhosts_options(5)を参照下さい。

Sun RPCに関してさらに詳しいことは、rpcinfo(8)とportmap(8)と"/usr/share/doc/portmap/portmapper.txt.gz"を参照下さい。

atd(8)とcron(8)に関しては、PAM以外のアクセスコントロールがあります。

4.7. 認証のセキュリティ

ここに書かれている情報はあなたのセキュリティのニーズに充分ではないかもしれませんが、良いスタートです。

4.7.1. インターネット経由のセキュアなパスワード

多くのトランスポーテーションレイヤーサービスはパスワード認証も含めて暗号化せずにメッセージを通信します。途中で傍受されかねないインターネットの荒野を経由して暗号化せずパスワードを送ることは非常によくない考えです。これらに関しては、"トランスポーテーションレイヤーセキュリティ"(TLS)もしくはその前身の"セキュアソケットレイヤー"(SSL)で暗号化することでパスワードを含むすべての通信をセキュアにしてサービスができます。

表4.7 インセキュアとセキュアな、サービスやポートのリスト

インセキュアなサービス名 ポート セキュアなサービス名 ポート
www (http) 80 https 443
smtp (mail) 25 ssmtp (smtps) 465
ftp-data 20 ftps-data 989
ftp 21 ftps 990
telnet 23 telnets 992
imap2 143 imaps 993
pop3 110 pop3s 995
ldap 389 ldaps 636

暗号化にはCPUタイムがかかります。CPUに友好的な代替方法として、POPには"パスワードを認証されたポストオフィスプロトコル"(APOP)やSMTPやIMAPには"チャレンジレスポンス認証メカニズムMD5"(CRAM-MD5)といったセキュアな認証プロトコルでパスワードのみを保護しつつ通信は暗号化無しですることもできます。(最近メールクライアントからメールサーバーにインターネット経由でメールメッセージを送る際には、CRAM-MD5で認証をしたのちネットワークプロバイダーによるポート25ブロッキングを避けて従来のSMTPポート25の代わりにメッセージサブミッションポート587を使うことがよく行われます。)

4.7.2. セキュアシェル

セキュアシェル(SSH)プログラムはセキュアな認証とともにインセキュアなネットワークを通過したお互いに信頼し合っていないホスト間のセキュアで暗号化された通信を可能にします。OpenSSHクライアントssh(1)とOpenSSHデーモンsshd(8)から成り立っています。SSHはポートフォーワーディング機能を使いPOPやXのようなインセキュアプロトコルの通信をインターネット経由でトンネルするのに使えます。

クライアントは、ホストベースド認証、公開鍵認証、チャレンジレスポンス認証、パスワード認証を使って認証をとろうとします。公開鍵認証を利用すると、リモートからのパスワード無しログインができるようになります。「The remote access server and utility (SSH)」参照下さい。

4.7.3. インターネットのためのセキュリティ強化策

たとえ、セキュアシェル (SSH)ポイントツーポイントトンネリングプロトコル(PPTP)サーバーのようなセキュアサービスを走らせる場合でも、ブルートフォースのパスワード推測等による侵入の可能性は残っています。次のようなセキュリティのためのツールとともに、ファイアーウォールポリシー(「Netfilter」参照)を使うのはセキュリティ状況を向上させ得る。

表4.8 セキュリティ強化策のためのツール表

パッケージ popcon サイズ 説明
knockd V:0.14, I:0.3 164 小さなポートノックのデーモンknocked(1)とクライアントkonck
denyhosts V:1.5, I:1.9 432 sshからの侵入者をシステム管理者が排除することを助けるユーティリティ
fail2ban V:3, I:3 616 複数回の認証エラーを発生させるIPを使用禁止とする
libpam-shield V:0.01, I:0.05 172 パスワード推測によるリモートからの攻撃者を締め出す

4.7.4. rootパスワードのセキュリティ確保

あなたの機器に他人がroot権限を持ってアクセスするのを阻止するには、次が必要です:

  • ハードディスクへの物理的アクセスを阻止します。
  • BIOSに鍵を書け、リムーバブルメディアからの起動を阻止します。
  • GRUBのインタラクティブセッションのパスワードを設定します。
  • GRUBのメニュー項目編集に鍵をかけます。

ハードディスクへの物理的アクセスがあれば、パスワードをリセットすることは比較的簡単です。

  • ハードディスクをCDから起動可能なBIOSのついたPCに移動します。
  • レスキューメディア(Debianブートディスク、Knopix CD、GRUB CD、...)でシステムを起動します。
  • rootパーティションを読み書きアクセスでマウントします。
  • rootパーティションの"/etc/passwd"を編集し、rootアカウントの2番目の項目を空にします。

grub-rescue-pcの起動時にGRUBのメニュー項目を編集できる(「2段目: ブートローダ」参照)のならもっと簡単です。

  • カーネルパラメータを"root=/dev/hda6 rw init=/bin/sh"のような感じに変更してシステムを起動。
  • "/etc/passwd"を編集し、rootアカウントの2番目の項目を空にします。
  • システム再起動。

システムのrootシェルにパスワード無しに入ることが出きるようになりました。

[注意] 注意

rootシェルにアクセスさえできれば、johnとかcrackパッケージ(「System security and integrity check」参照)のようなブルートフォースのパスワードクラッキングツールを使ってすべてのユーザアカウントのパスワードを破る事ができます。

この様な懸念を回避できる唯一の合理的なソフトウエア的解決法は、dm-cryptとinitramfs(「Data encryption tips」参照)をつかう、ソフトウエア暗号化されたrootパーティション(もしくは"/etc" パーティション)を使うことです。でも、パスワードがシステム起動毎に必要になってしまいます。

第5章 ネットワークの設定

[ティップ] ティップ

GNU/Linuxのネットワーク設定の一般的ガイドはLinux Network Administrators Guideを参照下さい。

Debianシステム上の伝統的なTCP/IPネットワークのセットアップはifupdownパッケージをよる高レベルのツールとして使います。2つの場合があります:

ここでは伝統的な場合を詳細に説明します。

また、ワイヤレスネットワークの設定を容易にするnetwork-managerwicdのような代替の高レベルツールにもここで少し触れていきます(「自動ネットワーク設定」参照)。

5.1. 基本的ネットワークインフラ

現代的なDebianシステムの基本的ネットワークインフラをレビューしましょう。

5.1.1. ドメイン名

ドメイン名を名付けるのは通常PCワークステーションのユーザにとってはトリッキーです。PCワークステーションは、ネットワークを渡り歩く可動PCかもしれないし、インターネットからアクセスできないNATファイアーウォールの背後にあるかもしれません。そのような場合、ドメイン名がかち合うのを避けるために有効なドメイン名をドメイン名として選びたくないでしょう。

rfc2606によると、インターネットから確実に無効なドメイン名を作るためにはトップレベルドメイン(TLD)の選択として"invalid"が良い選択のようです。

mDNSネットワーク探索プロトコル(Apple Bonjour / Apple Rendezvous、Debian上のAvahi)は、"local"擬似トップレベルドメインとして使います。Microsoftも"local"をローカルエリアネットワークのTLDとして推奨しているようでもあります

無効TLDのよくある選択は、私が受け取ったメールの解析によると、"localdomain"とか"lan"とか"localnet"とか"home"のようです。

5.1.2. ホスト名の解決

ホスト名の解決もまた、現在NSS (ネームサービススイッチ、Name Service Switch)メカニズムによってサポートされています。この解決の流れは次です:

  1. "hosts: files dns"のようなスタンザのある"/etc/nsswitch.conf"ファイルがホスト名の解消の順序を規定します。(これは、"/etc/host.conf"ファイル中の"order"スタンザの機能を置換します。)
  2. filesメソッドが最初に発動されます。ホスト名が"/etc/hosts"ファイルに見つかると、それに対応する全ての有効アドレスを返し終了します。("/etc/host.conf"ファイルは"multi on"を含みます。)
  3. dnsメソッドが発動されます。"/etc/resolv.conf"ファイルで識別されるインターネットドメイン名システム(DNS)への問い合わせでホスト名が見つかれば、それに関する全ての有効アドレスを返します。

"/etc/hosts"ファイルはホスト名とIPアドレスを関連付けます:

127.0.0.1 localhost
127.0.1.1 <host_name>.<domain_name> <host_name>

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts

上記中の<host_name>は、"/etc/hostname"で定義される自分自身のホスト名と一致します。上記中の<domain_name>は、このホストの完全修飾ドメイン名(FQDN)です。

[ティップ] ティップ

真のFQDNを持たない可動PCでは、この設定ファイル中の<domain_name>のTLD部分に、実在しない"invalid"とかmDNSの"local"をTLDとして選べます。

resolvconfパッケージがインストールされなかったら、"/etc/resolv.conf"は静的なファイルです。インストールされると、それはシンボリックリンクになります。いずれにせよ,解決機構を初期化する情報を含んでいます。もしDNSがIP="192.168.11.1"に見つかるなら、それは次を含みます:

nameserver 192.168.11.1

resolvconfパッケージはこの"/etc/resolv.conf"をシンボリックリンクにし、フックスクリプトで自動的にその内容を管理します。

アドホクのmDNSのドメイン"local"中で通常Unix/Linuxプログラムによる名前解決を実質的にできるようにするマルチキャストDNS(Zeroconf、別名Apple Bonjour / Apple Rendezvous)を使うホスト名解決は、libnss-mdnsパッケージをインストールすると提供できます。このような機能を有効にするには、"/etc/nsswitch.conf"ファイル中に"hosts: files mdns4_minimal [NOTFOUND=return] dns mdns4"のようなスタンザが必要です。

5.1.3. ネットワークインターフェース名

Linuxカーネル中の各ハードウエアーは、それが見つかり次第ユーザスペースの設定メカニズムudev(「udevシステム」参照)を通じて、例えばeth0のようなネットワークインターフェース名が付与されます。ネットワークインターフェース名は、ifup(8)とinterfaces(5)の中で物理インターフェースと呼ばれています。

MACアドレス等を使って各リブート毎に永続性をもって各ネットワークインターフェースが名付けられるように記録するファイル"/etc/udev/rules.d/70-persistent-net.rules"があります。このファイルは"persistent-net-generator.rules"ルールファイルによって実行されているような"/lib/udev/write_net_rules"プログラムによって自動生成されます。そのファイルを変更することで命名ルールを変更できます。

[注意] 注意

"/etc/udev/rules.d/70-persistent-net.rules"ルールファイルを編集する時は、各ルールを1行に納めてMACアドレスに小文字を使わなければいけません。例えば、あなたがこのファイル中に"Firewire device"と"PCI device"を見つけたら、きっと"PCI device"をeth0として第1番目のネットワークインターフェースとして設定したいでしょう。

5.1.4. LANのためのネットワークアドレス範囲

rfc1918によってローカルエリアネットワーク(LAN)での使用に予約されている各クラス毎のIPv4 32ビットアドレス範囲を確認しましょう。これらのアドレスは本来のインターネット上のアドレスとかち合う事が無いことが保証されています。

表5.1 ネットワークアドレス範囲のリスト

クラス ネットワークアドレス ネットマスク ネットマスク/ビット サブネットの数
A 10.x.x.x 255.0.0.0 /8 1
B 172.16.x.x — 172.31.x.x 255.255.0.0 /16 16
C 192.168.0.x — 192.168.255.x 255.255.255.0 /24 256

[注意] 注意

これらのアドレス内の1つがホストに付与されている場合、そのホストはインターネットを直接アクセスせずに、各サービスのプロキシとなるかネットワークアドレス変換(NAT)をするゲートウエーを通してアクセスしなければいけません。ブロードバンドルーターは消費者LAN環境のために通常NATを行います。

5.1.5. ネットワーク設定インフラ

Linuxのネットワークシステムには2タイプの低レベルネットワークプログラムがあります(「Iproute2コマンド」参照)。

  • 古いnet-toolsプログラム(ifconfig(8)、…)はLinux NET-3ネットワークシステム由来です。これらの多くはすでに時代遅れです。
  • 新しいLinux iproute2プログラム(ip(8)、…)は現行のLinuxのネットワークシステムです。

これらの低レベルのネットワークプログラムは強力ですが、使うのが面倒です。そこで高レベルのネットワーク設定プログラムが作られました。

ifupdownパッケージはDebian上のそのような高レベルネットワーク設定のデファクトスタンダードです。それを使うと、"ifup eth0"とするだけでネットワークを立ち上げることができます。その設定ファイルは、"/etc/network/interfaces"ファイルで、その典型的内容は次です:

auto lo
iface lo inet loopback

auto eth0
iface eth0 inet dhcp

resolvconfパッケージは、ネットワークアドレス解決設定ファイル"/etc/resolv.conf"の書き変えを自動化してネットワークアドレス解決の円滑な再構成をサポートするためにifupdownシステムを補完するために作られました。現在、ほとんどのDebianのネットワーク設定パッケージはresolvconfパッケージを使うように変更されています("/usr/share/doc/resolvconf/README.Debian"参照)。

ifplugdguessnetifscheme等のifupdownパッケージの補助スクリプトが有線LAN上の可動PCのためのネットワーク環境設定のようなネットワーク環境の動的設定を自動化するために作られています。これらはちょっと使い難いですが、既存のifupdownシステムとは反りが合います。

ifupdownシステムと独立な、network-managerwicd等の代替となる高レベルネットワーク設定システムはワイアレスネットワーク上の可動PCも含めたネットワーク環境を楽に設定するために作られた。これらは比較的新しくそのDebianシステムへの統合は進行中なので、これらとifupdownがかち合うことを避けるために"/etc/network/interfaces"中の対応するネットワークインターフェースを手動で無効にする必要があるかもしれません。(「自動ネットワーク設定」参照)。

表5.2 ネットワーク設定ツールのリスト。

パッケージ popcon サイズ タイプ 機能
ifupdown V:63, I:99 228 設定::ifupdown ネットワークを接続したり切断したりする標準化されたツール(Debian特定)
ifplugd V:0.4, I:0.9 332 , , 有線ネットワークを自動的に管理します
ifupdown-extra V:0.04, I:0.2 124 , , "ifupdown"パッケージを強化するネットワークテストスクリプト
ifmetric V:0.02, I:0.09 100 , , ネットワークインターフェースの経路メトリック設定をします
guessnet V:0.09, I:0.4 492 , , ifupdownのヘルパースクリプト: ifplugdguessnetifscheme、…
ifscheme V:0.03, I:0.10 80 , , "ifupdown"パッケージを補強するmappingスクリプト
ifupdown-scripts-zg2 V:0.00, I:0.05 220 , , Zugschlusさんのifupdownの手動方法のインターフェーススクリプト
network-manager V:30, I:38 2180 設定::NetworkManager NetworkManager (デーモン): ネットワークを自動管理します
network-manager-gnome V:22, I:35 3372 , , NetworkManager (GNOMEフロントエンド)
network-manager-kde V:2, I:4 3088 , , NetworkManager (KDEフロントエンド)
wicd V:1.2, I:1.5 1852 設定::wicd 有線と無線のネットワークマネージャ
iptables V:25, I:99 1368 設定::Netfilter パケットフィルタリングとNATのための管理ツール
iproute V:38, I:75 1000 設定::iproute2 IPv6や他の上級ネットワーク設定: ip(8)やtc(8)等
ifrename V:0.2, I:0.8 108 , , 各種の静的クライテリアに基づきネットワークインターフェースを改名します: ifrename(8)
ethtool V:3, I:11 256 , , Ethernetデバイス設定の表示と設定をします
iputils-ping V:36, I:99 124 テスト::iproute2 ホスト名IPアドレスによってリモートホストのネットワークからの到達性をテストするツール
iputils-arping V:1.1, I:17 72 , , ARPアドレスによって特定されるリモートホストのネットワークからの到達性をテストするツール
iputils-tracepath V:0.4, I:2 108 , , リモートホストへのネットワークパスを追跡するツール
net-tools V:80, I:99 1016 設定::net-tools NET-3ネットワーキングツールキット(IPv4ネットワーク設定): ifconfig(8)等
inetutils-ping V:0.05, I:0.14 268 テスト::net-tools ホスト名IPアドレスによってリモートホストのネットワークからの到達性をテストするツール(レガシー、GNU)
arping V:0.5, I:2 64 , , ARPアドレスによって特定されるリモートホストのネットワークからの到達性をテストするツール(レガシー)
traceroute V:14, I:98 184 , , リモートホストへのネットワークパスを追跡するツール(レガシー、コンソール)
dhcp3-client V:50, I:93 608 設定::低レベル DHCPクライアント
wpasupplicant V:12, I:45 960 , , WPAとWPA2 (IEEE 802.11i)のためのクライアントサポート
wireless-tools V:9, I:27 276 , , Linuxのワイアレス拡張を操作するツール
ppp V:7, I:26 1100 , , chatによるPPP/PPPoEコネクション
pppoeconf V:0.5, I:4 200 設定::ヘルパー PPPoEコネクションの設定ヘルパー
pppconfig V:0.4, I:3 900 , , chatによるPPPコネクションの設定ヘルパー
wvdial V:0.6, I:2 352 , , wvdialpppによるPPPコネクションの設定ヘルパー
mtr-tiny V:4, I:54 120 テスト::低レベル リモートホストへのネットワークパスを追跡するツール(curses)
mtr V:0.5, I:2 176 , , リモートホストへのネットワークパスを追跡するツール(cursesとGTK+)
gnome-nettool V:4, I:40 1766 , , リモートホストへのネットワークパスを追跡するツール(GNOME)
nmap V:6, I:30 3768 , , ネットワークマッパー/ポートスキャナ(Nmap、コンソール)
zenmap V:0.2, I:1.0 1232 , , ネットワークマッパー/ポートスキャナ(GTK+)
knmap V:0.12, I:0.7 1992 , , ネットワークマッパー/ポートスキャナ(KDE)
tcpdump V:3, I:22 796 , , ネットワークトラフィックアナライザー(Tcpdump、コンソール)
wireshark V:2, I:10 1604 , , ネットワークトラフィックアナライザー(Wireshark、GTK+)
tshark V:0.5, I:3 284 , , ネットワークトラフィックアナライザー(コンソール)
nagios3 V:0.8, I:1.1 4152 , , ホストとサービスとネットワークを監視や管理するシステム(Nagios)
tcptrace V:0.07, I:0.4 432 , , tcpdumpの出力から接続状況のまとめを作成するツール
snort V:0.7, I:0.9 1100 , , 柔軟なネットワーク侵入検知システム(Snort)
ntop V:1.2, I:2 15600 , , ネットワークの使用状況をウエッブブラウザで表示する
dnsutils V:14, I:91 388 , , BINDによって提供されるネットワーククライアント: nslookup(8)とnsupdate(8)とdig(8)
dlint V:0.5, I:7 96 , , ネームサーバーの閲覧でDNSのゾーン情報を確認
dnstracer V:0.09, I:0.6 88 , , DNSサーバーをその源流まで遡るツール

5.1.6. ネットワークデバイスサポート

Debianシステムによってほとんどのハードウエアーデバイスはサポートされていますが、一部のネットワークデバイスはそのサポートのためにDSFG non-freeのドライバが必要です。「Non-free hardware drivers」を参照下さい。

5.2. ネットワーク接続方法

[注意] 注意

本セクションで説明されている接続テスト方法はあくまでテスト目的のためのものです。毎日のネットワーク接続のために使うためではありません。ifupdownパッケージを通して使うことをお勧めします(「ifupdownを使った基本的なネットワーク設定」参照)。

典型的なネットワーク接続方法とPCまでの接続経路は次のようにまとめられます:

表5.3 典型的なネットワーク接続方法と接続経路のリスト。

PC 接続方法 接続経路
シリアルポート(ppp0) PPP モデム ⇔ POTS ⇔ ダイヤルアップアクセスポイント ⇔ ISP
イーサーネットポート(eth0) PPPoE/DHCP/静的 ⇔ BBモデム ⇔ BBサービス ⇔ BBアクセスポイント ⇔ ISP
イーサーネットポート(eth0) DHCP/静的 ⇔ LAN ⇔ ネットワークアドレス変換(NAT)機能のあるBBルーター (⇔ BBモデム …)

各接続方法のための設定スクリプトのまとめると次となります:

表5.4 ネットワーク接続設定のリスト。

接続方法 設定 バックエンドパッケージ
PPP pppconfig決定論的chatの作成 pppconfigppp
PPP(代替) wvdialconfはヒューリスティックのあるchatの作成 pppwvdial
PPPoE pppoeconf決定論的chatの作成 pppoeconfppp
DHCP "/etc/dhcp3/dhclient.conf"中に記述されています dhcp3-client
静的IP (IPv4) "/etc/network/interfaces"中に記述されています net-tools
静的IP (IPv6) "/etc/network/interfaces"中に記述されています iproute

ネットワーク接続の省略語は次の意味です:

表5.5 ネットワーク接続の省略語のリスト。

省略語 意味
POTS 旧来型電話サービス
BB ブロードバンド
BBサービス 例えばデジタルサブスクラーバーライン(DSL)やケーブルテレビや家庭向け光ファイバー(FTTP)。
BBモデム 例えば、DSLモデムケーブルモデム光ファイバー端末(ONT)
LAN ローカルエリアネットワーク
WAN 広域ネットワーク
DHCP 動的ホスト設定プロトコル
PPP ポイント間接続プロトコル
PPPoE Ethernet経由のポイント間接続プロトコル
ISP インターネットサービス供給者

[注意] 注意

ケーブルTV経由のWAN接続サービスは大体DHCPかPPPoEでサービスを受けます。ADSLとFTTPの接続サービスは大体PPPoEでサービスを受けます。WAN接続の正確な設定要件はあなたのISPにご確認下さい。

[注意] 注意

BBルータが家庭内LAN環境を作るのに使われる時には、LAN上のPCはネットワークアドレス変換(NAT)をしてBBルーター経由でWANに接続されます。そのような場合、LAN上のPCのネットワークインターフェースは静的IPかBBルーターからのDHCPでサービスを受けます。BBルーターはあなたのISPによる指示にしたがってWANに接続されるよう設定しなければいけません。

5.2.1. イーサーネットを使ってのDHCP接続

典型的な最近の家庭内や小規模ビジネスネットワークのLANはWAN(インターネット)に何らかの消費者向けブロードバンドルーターを使って接続されています。このルーターの後ろのLANは通常ルーター上で稼働する動的ホスト設定プロトコル(DHCP)サーバーによりサービスを受けています。

動的ホスト設定プロトコル(DHCP)サービスを受けるイーサーネットでは、dhcp3-clientパッケージをインストールするだけです。

5.2.2. イーサーネットを使っての静的IP接続

静的IPサービスを受けるイーサーネットでは、特段何をする必要もありません。

5.2.3. pppconfigを使ってのPPP接続

設定スクリプトpppconfigPPP接続を次の選択をすることで対話式で設定します:

  • 電話番号
  • ISPでのユーザ名
  • ISPのパスワード
  • ポートの速度
  • モデム通信のポート
  • 認証方法

設定ファイルは以下:

表5.6 pppconfigを使ってのPPP接続のための設定ファイルのリスト。

ファイル 機能
/etc/ppp/peers/<isp_name> pppconfigによって生成された<isp_name>に特定なpppdのための設定ファイル
/etc/chatscripts/<isp_name> pppconfigによって生成された<isp_name>に特定なchatのための設定ファイル
/etc/ppp/options pppdのための一般的な実行パラメータ
/etc/ppp/pap-secret PAPのための認証データ(安全上問題あり)
/etc/ppp/chap-secret CHAPのための認証データ(比較的安全)

[注意] 注意

もしponpoffコマンドが引数無しに起動された場合には、"<isp_name>"の値として"provider"が使われます。

低レベルのネットワーク設定ツールを使って設定の確認ができます。

$ sudo pon <isp_name>
...
$ sudo poff <isp_name>

詳細は"/usr/share/doc/ppp/README.Debian.gz"を参照下さい。

5.2.4. wvdialconfを使った代替PPP接続

pppd(8)を使う異なるアプローチは、wvdialパッケージが提供するwvdial(1)からそれを実行することです。電話を掛け接続の交渉をするためにpppdchat(8)を実行するのではなく、wvdialが電話を掛け接続の交渉をした後にpppdを始動し後を任せます。

設定スクリプトwvdialconfはPPP接続を次の選択をすることで対話式で設定します:

  • 電話番号
  • ISPでのユーザ名
  • ISPのパスワード

ほとんどの場合wvdialは接続をすることに成功し、自動的に認証データのリストを管理します。

設定ファイルは以下:

表5.7 wvdialconfでPPP接続する際の設定ファイルリスト。

ファイル 機能
/etc/ppp/peers/wvdial wvdialconfwvdialに合わせて生成したpppdの設定ファイル
/etc/wvdial.conf wvdialconfが生成した設定ファイル
/etc/ppp/options pppdのための一般的な実行パラメータ
/etc/ppp/pap-secret PAPのための認証データ(安全上問題あり)
/etc/ppp/chap-secret CHAPのための認証データ(比較的安全)

低レベルのネットワーク設定ツールを使って設定の確認ができます。

$ sudo wvdial
...
$ sudo killall wvdial

詳細はwvdial(1)とwvdial.conf(5)を参照下さい。

5.2.5. pppoeconfを使ったPPPoE接続

あなたのISPがPPPoE接続を提供し、あなたのPCを直接WANに接続すると決めた際には、あなたのPCのネットワークはPPPoEで設定しないといけません。PPPoEとはイーサーネット経由のPPPの意味です。設定スクリプトpppoeconfはPPPoE接続を対話式で設定します。

設定ファイルは以下:

表5.8 pppoeconfを用いてPPPoE接続する際の設定ファイルのリスト。

ファイル 機能
/etc/ppp/peers/dsl-provider pppoeconfpppoeに合わせて生成したpppdの設定ファイル
/etc/ppp/options pppdのための一般的な実行パラメータ
/etc/ppp/pap-secret PAPのための認証データ(安全上問題あり)
/etc/ppp/chap-secret CHAPのための認証データ(比較的安全)

低レベルのネットワーク設定ツールを使って設定の確認ができます。

$ sudo /sbin/ifconfig eth0 up
$ sudo pon dsl-provider
...
$ sudo poff dsl-provider
$ sudo /sbin/ifconfig eth0 down

詳細は"/usr/share/doc/pppoeconf/README.Debian"を参照下さい。

5.3. ifupdownを使った基本的なネットワーク設定

ifupdownパッケージはDebianシステムでの高レベルネットワーク設定の標準化された枠組みを提供します。このセクションでは、簡略化された紹介と多くの典型例でifupdownを使った基本的なネットワーク設定を学びます。

5.3.1. 簡略化されたコマンドシンタックス

ifupdownパッケージには2つのコマンドがあります: ifup(8)とifdown(8)。設定ファイル"/etc/network/interfaces"により規定される高レベルのネットワーク設定を提供します。

表5.9 ifupdownを使う基本的なネットワーク設定コマンドのリスト。

コマンド アクション
ifup eth0 "iface eth0"スタンザがあれば、ネットワークインターフェースeth0をネットワーク設定eth0で起動します。
ifdown eth0 "iface eth0"スタンザがあれば、ネットワークインターフェースeth0に関するネットワーク設定eth0を終了し停止します。

[警告] 警告

up状態にあるインターフェースを、ifconfig(8)やip(8)コマンドのような低レベル設定ツールを使って設定してはいけません。

[注意] 注意

ifupdownというコマンドはありません。

5.3.2. "/etc/network/interfaces"の基本的なシンタックス

"/etc/network/interfaces"のシンタックスはinterfaces(5)に説明されていて、要点は:

表5.10 "/etc/network/interfaces"のスタンザのリスト

スタンザ 意味
"auto <interface_name>" システム起動時にインターフェース<interface_name>を起動します。
"allow-auto <interface_name>" , ,
"allow-hotplug <interface_name>" カーネルがインターフェースからのホットプラグイベントを認知した際にインターフェース<interface_name>を起動します。
"iface <config_name> …"によって始まる行 ネットワーク設定<config_name>を規定します。
"mapping <interface_name_glob> "によって始まる行 <interface_name>に対応する<config_name>のmapping値を規定します。
ハッシュ"#"で始まる行 コメントして無視される。(行末コメントは非サポート)
バックスラシュ"\"で終わる行 設定を次行に継続します。

ifaceスタンザで始まる行は次のシンタクスです:

iface <config_name> <address_family> <method_name>
 <option1> <value1>
 <option2> <value2>
 ...

基本設定に関しては、mappingスタンザは使われませんし、ネットワークインターフェース名をネットワーク設定名として使います(「mappingスタンザ」参照)。

[警告] 警告

"/etc/network/interfaces"のネットワークインターフェースに関する"iface"スタンザの重複定義をしてはいけません。

5.3.3. ループバックネットワークインターフェース

"/etc/network/interfaces"ファイルに次の設定をすることでシステムブート時にループバックネットワークインターフェースloが起動されます(autoスタンザ経由)。

auto lo
iface lo inet loopback

この設定は、"/etc/network/interfaces"ファイル中にいつも存在します。

5.3.4. DHCPサービスを受けるネットワークインターフェース

「イーサーネットを使ってのDHCP接続」によりシステムの準備をした後、DHCPによってサービスされるネットワークインターフェースは"/etc/network/interfaces"ファイルの中に次のような設定エントリーを設定します:

allow-hotplug eth0
iface eth0 inet dhcp
 hostname "mymachine"

Linuxカーネルが物理インターフェースeth0を認識した場合、allow-hotplugスタンザはifupによりそのインターフェースが起動させられるようにし、ifaceスタンザがifupがインターフェースがDHCPを使うように設定します。

5.3.5. 静的IPを使うネットワークインターフェース

静的IPによってサービスされるネットワークインターフェースは"/etc/network/interfaces"ファイル中に例えば次の設定エントリーを作ることで設定されます:

allow-hotplug eth0
iface eth0 inet static
 address 192.168.11.100
 netmask 255.255.255.0
 broadcast 192.168.11.255
 gateway 192.168.11.1
 dns-domain lan
 dns-nameservers 192.168.11.1

Linuxカーネルが物理インターフェースeth0を認識した場合、allow-hotplugスタンザはifupによりそのインターフェースが起動させられるようにし、ifaceスタンザがifupがインターフェースが静的IPを使うように設定します。

ここで、私は次のような仮定をしています:

  • LANネットワークのIPアドレス範囲: 192.168.11.0 - 192.168.11.255
  • ゲートウエーのIPアドレス: 192.168.11.1
  • PCのIPアドレス: 192.168.11.100
  • resolvconfパッケージがインストール済み。
  • ドメイン名は"lan"。
  • DNSサーバーのIPアドレス: 192.168.11.1

resolvconfパッケージがインストールされていないと、DNS関係の設定は手動で"/etc/resolv.conf"を次のように編集する必要があります:

nameserver 192.168.11.1
domain lan
[注意] 注意

上記例で用いたIPアドレスはそのままコピーされるべきものではありません。IP番号はあなたの実際のネットワーク設定に合わせなければいけません。

5.3.6. ワイアレスLANインターフェースの基本

ワイアレスLAN (省略するとWLAN)IEEE 802.11という標準群に基づく特別な免許なく使える無線を使う帯域拡散通信を経由の高速ワイアレス接続を提供します。

WLANインターフェースは通常のEthernetインターフェースと非常に似ていますが、始動時にネットワークIDと暗号キーデータを必要とします。インターフェース名が使われるカーネルドライバによってeth1wlan0ath0wifi0等とインターフェース名が少々異なる以外は、それらに使われる高レベルのネットワークツールはEthernetインターフェースのものとまったく同じです。

[ティップ] ティップ

wmaster0デバイスは、新規のLinuxのmac80211 APIによるSoftMACによってのみ使われる内部デバイスのマスターデバイスです。

WLANに関して留意すべきキーワードは次です:

表5.11 WLANの略語のリスト。

省略語 元の言葉 意味
NWID ネットワークID 802.11以前のWaveLANネットワークによって使われる16ビットネットワークID。絶対使用を控えること。
(E)SSID (拡張)サービスセットアイデンティファイアー 802.11 ワイアレスLANが統合されて連結されてできるワイアレスアクセスポイント(APs)のネットワーク名。ドメインID。
WEP, (WEP2) 有線等価プライバシー 第1世代の、40ビットのキーを使う64ビット(128ビット)のワイアレス暗号化標準。使用を控えること。
WPA Wi-Fi保護アクセス(Protected Access) 第2世代の、WEPとの互換性のあるワイアレス暗号化標準(802.11iの殆ど)。
WPA2 Wi-Fi保護アクセス(Protected Access)2 第3世代の、WEPとの互換性のないワイアレス暗号化標準(完全に802.11i)。

実際のプロトコルの選択肢は採用しているワイアレスルーターによって普通制約されます。

5.3.7. WPA/WPA2を使うワイアレスLANインターフェース

新しいWPA/WPA2を使うWLANをサポートするには、wpasupplicantパッケージをインストールする必要があります。

WLAN接続上のDHCPによってサービスされているIPの場合には、"/etc/network/interfaces"ファイルのエントリーは次のようです:

allow-hotplug ath0
iface ath0 inet dhcp
 wpa-ssid homezone
 # hexadecimal psk is encoded from a plaintext passphrase
 wpa-psk 000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f

詳細は"/usr/share/doc/wpasupplicant/README.modes.gz"を参照下さい。

5.3.8. WEPを使うワイアレスLANインターフェース

古いWEPを使うWLANをサポートするには、wireless-toolsパッケージをインストールする必要があります。(あなたの消費者用のルーターは今だにセキュアでないインフラを使っているかもしれませんが、無いよりはましです。)

[注意] 注意

WEPを使うWLAN上のネットワークトラフィックは他人に覗かれているかも知れないことを覚えておいてください。

WLAN接続上のDHCPによってサービスされているIPの場合には、"/etc/network/interfaces"ファイルのエントリーは次のようです:

allow-hotplug eth0
iface eth0 inet dhcp
 wireless-essid Home
 wireless-key1 0123-4567-89ab-cdef
 wireless-key2 12345678
 wireless-key3 s:password
 wireless-defaultkey 2
 wireless-keymode open

詳細は"/usr/share/doc/wireless-tools/README.Debian"を参照下さい。

5.3.9. PPP接続

以前説明したようにPPP接続を設定する必要があります(「pppconfigを使ってのPPP接続」参照)。さらに、第1番目のPPPデバイスppp0のための"/etc/network/interfaces"ファイルのエントリーを次のように追加します:

iface ppp0 inet ppp
 provider <isp_name>

5.3.10. 代替のPPP接続

以前説明したようにwvdialを使う代替PPP接続をまず設定する必要があります(「wvdialconfを使った代替PPP接続」参照)。さらに、第1番目のPPPデバイスppp0のための"/etc/network/interfaces"ファイルのエントリーを次のように追加します:

iface ppp0 inet wvdial

5.3.11. PPPoE接続

PPPoEによってサービスされる直接WANに接続したPCの場合、以前説明したようにPPPoE接続を設定する必要があります(「pppoeconfを使ったPPPoE接続」参照)。さらに、第1番目のPPPoEデバイスeth0のための"/etc/network/interfaces"ファイルのエントリーを次のように追加します:

allow-hotplug eth0
iface eth0 inet manual
 pre-up /sbin/ifconfig eth0 up
 up ifup ppp0=dsl
 down ifdown ppp0=dsl
 post-down /sbin/ifconfig eth0 down
# The following is used internally only
iface dsl inet ppp
 provider dsl-provider

5.3.12. ifupdownのネットワーク設定状態

"/etc/network/run/ifstate"ファイルは、ifupdownパッケージが管理する全ての有効なネットワークインターフェースの意図したネットワーク設定状態を記録します。残念ながらifupdownが意図したにもかかわらずインターフェースを起動できなかった場合でも、"/etc/network/run/ifstate"ファイルはインターフェースが起動されたと表示します。

あるインターフェースに関するifconfig(8)コマンド出力が次の例のような行を欠いている場合、IPV4ネットワークの一部としては使えません:

  inet addr:192.168.11.2  Bcast:192.168.11.255  Mask:255.255.255.0
[注意] 注意

PPPoEに接続されているイーサーネットデバイスの場合、ifconfig(8)コマンドのアウトプットは上記例のような行を欠いています。

5.3.13. 基本ネットワーク設定

例えばeth0というインターフェースを再設定したい際には、まず"sudo ifdown eth0"コマンドを実行してそれを無効にしなければいけません。こうすることでeth0のエントリーが"/etc/network/run/ifstate"ファイルから削除されます。(もしeth0が有効でなかったりそれにたいして過去に間違った設定がされている際には、こうするとエラーメッセージを発することになるかもしれません。シンプルな単一ユーザのワークステーションではいつも問題なことは知る限り起こらないようです。)

こうすることで、必要に応じてネットワークインターフェースeth0を自由に再設定するために"/etc/network/interfaces"の内容を自由に書き換えられます。

こうした後で、eth0を"sudo ifup eth0"コマンドを使って再起動できます。

[ティップ] ティップ

ネットワークインターフェースは、"sudo ifdown eth0;sudo ifup eth0"とすることで(再)初期化できます。

5.3.14. ifupdown-extraパッケージ

ifupdown-extraパッケージは、ifupdownとともに使う使いやすいネットワーク接続テストを次によって提供します:

  • シェルから実行されるnetwork-test(1)コマンド。
  • ifupコマンド実行毎に実行される自動スクリプト。

network-testコマンドをつかうことで面倒な低レベルコマンドを使ってネットワーク問題を分析する手間を省けます。

自動スクリプトは"/etc/network/*/"にインストールされ:

  • ネットワークケーブルの接続の確認。
  • IPアドレスの重複使用の確認。
  • "/etc/network/routes"の定義に従った静的ルートの設定。
  • ネットワークのゲートウエーが到達可能かの確認。
  • 結果を"/var/log/syslog"ファイルに記録。

このsyslog記録はリモートシステムのネットワーク問題を管理する上で非常に有用です。

[ティップ] ティップ

ifupdown-extraパッケージの自動的な挙動は"/etc/default/network-test"によって設定可能です。これらの自動テストの一部はARPからの返答を聞くのでシステムのブートプロセスを少々遅らせます。

5.4. ifupdownを使う上級ネットワーク設定

ifupdownパッケージの機能は、上級知識を使うと「ifupdownを使った基本的なネットワーク設定」に書かれているよりも向上します。

ここに記述されている機能は全く任意のものです。著者自身、怠け者で面倒な事が嫌いなために、ここに書かれたことを使うことは滅多にありません。

[注意] 注意

「ifupdownを使った基本的なネットワーク設定」に書かれた情報でネットワーク接続をうまく設定できないのに、次の情報を使うと状況は更に悪くなります。

5.4.1. ifplugdパッケージ

ifplugdパッケージはイーサーネット接続のみを管理する古い自動ネットワーク設定ツールです。これによって可動PC等のイーサーネットケーブルの脱着問題を解決します。もしNetworkManagerWicd (「自動ネットワーク設定」参照)がインストールされている場合は、このパッケージは必要ありません。

このパッケージはデーモンとして実行され、autoとかallow-hotplugという機能(表5.10「"/etc/network/interfaces"のスタンザのリスト」)を置き換え、インターフェースがネットワークに繋がれるとインターフェースを起動します。

例えばeth0という内部イーサーネットポートに対するifplugdパッケージの利用方法は次です:

  • "/etc/network/interfaces"の中のスタンザを削除します: "auto eth0"または"allow-hotplug eth0"、
  • "/etc/network/interfaces"の中のスタンザを残します: "iface eth0 inet …"と"mapping …"、
  • ifplugdパッケージをインストールします、
  • "sudo dpkg-reconfigure ifplugd"の実行します。
  • eth0を"ifplugdにより監視される静的インターフェース"とします。

こうするとお望みどおりのネットワーク設定が機能します:

  • 電源投入もしくはハードウエアーの発見時に、インターフェースは自動的に起動されます。

  • イーサーネットケーブルを発見時にインターフェースが起動されます。
  • イーサーネットケーブルを外して少し経った時点でインターフェースが自動的に停止されます。
  • イーサーネットケーブルを接続した時点でインターフェースが新しいネットワーク環境下で起動されます。
[ティップ] ティップ

The arguments for the ifplugd(8)コマンドの引数はインターフェースの再設定の遅延時間などの挙動を設定します。

5.4.2. ifmetricパッケージ

ifmericパッケージを使うと、DHCPでもルートのメトリクスを事後操作できます。

次のようにするとeth0インターフェースをwlan0インターフェースより優先するように設定できます:

  • ifmetricパッケージをインストール。
  • "iface eth0 inet dhcp"行のすぐ下に"metric 0"というオプション行を追加します。
  • "iface wlan0 inet dhcp"行のすぐ下に"metric 1"というオプション行を追加します。

メトリック0とは最高優先順位のルートでデフォルトのルートということを意味します.大きなメトリック値は低い優先順位を意味します。最低のメトリック値をもつ有効なインターフェースのIPアドレスが発信源となるインターフェースになります。ifmetric(8)を参照下さい。

5.4.3. 仮想インターフェース

物理的には単一のイーサーネットインターフェースは異なるIPアドレスをもつ複数の仮想インターフェースとして設定できます。いくつかのIPサブネットワークにインターフェースを繋ぐのが通常こうする目的です。例えば、単一ネットワークインターフェースを使ったIPアドレスに基づく仮想ウエッブホスティングがその適用例です。

例えば、次を仮定しましょう

  • あなたのホスト上の単一のイーサーネットインターフェースが(ブロードバンドルーターではなく)イーサーネットハブに接続されています。
  • イーサーネットハブはインターネットとLANネットワークの両方に接続されています。
  • LANネットワークはサブネット192.168.0.x/24を使う。
  • あなたのホストはインターネットに関しては物理インターフェースeth0をDHCPが提供するIPアドレスで使います。
  • あなたのホストはLANに関しては仮想インターフェースeth0:0192.168.0.1で使います。

このとき"/etc/network/interfaces"中の次のスタンザがあなたのネットワークを設定します:

iface eth0 inet dhcp
 metric 0
iface eth0:0 inet static
 address 192.168.0.1
 netmask 255.255.255.0
 network 192.168.0.0
 broadcast 192.168.0.255
 metric 1
[注意] 注意

netfilter/iptables(「Netfilter」参照)を使ってネットワークアドレス変換(NAT)を使う上記設定例は単一インターフェースを使ってLANに対して安価なルーターを提供しますが、そのような設定を使ったのでは真のファイアーウォール能力はありません。2つの物理インターフェースとNATを使ってインターネットからローカルネットワークをセキュアするべきです。

5.4.4. 上級コマンドシンタックス

ifupdownパッケージはネットワーク設定名とネットワークインターフェース名を使って上級のネットワーク設定をできるようにします。わたしはifup(8)やinterfaces(5)とは少々異なる用語法をここでは使っています。

表5.12 ネットワークデバイスの用語法のリスト。

マンページの用語法 著者の用語法 説明 この後の文中の用例
物理インターフェース ネットワークインターフェース Linuxカーネルが(udevメカニズムを利用して)与える名前。 lo, eth0, <interface_name>
論理インターフェース ネットワーク設定 "/etc/network/interfaces"中でifaceに続く名前文字列。 config1, config2, <config_name>

「簡略化されたコマンドシンタックス」中の基本的なネットワーク設定コマンドは、ifaceスタンザ中のネットワーク設定名の文句と、"/etc/network/interfaces"中のネットワークインターフェース名が一致している必要があります。

上級ネットワーク設定コマンドは"/etc/network/interfaces"の中で、ネットワーク設定名とネットワークインターフェース名を区別を可能にします:

表5.13 ifupdownを使う上級ネットワーク設定コマンドのリスト。

コマンド アクション
ifup eth0=config1 ネットワーク設定config1を使うネットワークインターフェースeth0を始動します。
ifdown eth0=config1 ネットワーク設定config1を使うネットワークインターフェースeth0を停止します。
ifup eth0 mappingスタンザによって選ばれる設定を使ってネットワークインターフェースeth0を始動します。
ifdown eth0 mappingスタンザによって選ばれる設定を使ってネットワークインターフェースeth0を停止します。

5.4.5. mappingスタンザ

「"/etc/network/interfaces"の基本的なシンタックス」では複雑になるのを避けるために"/etc/network/interfaces"中のmappingスタンザを説明しませんでした。このスタンザには次のシンタクスがあります:

mapping <interface_name_glob>
 script <script_name>
 map <script_input1>
 map <script_input2>
 map ...

上記は、<script_name>で指定されるmappingスクリプトで設定の選択を自動化することで"/etc/network/interfaces"に上級機能を付与します。

"<interface_name_glob>"が"eth0"と一致する時に、次が実行され

$ sudo ifup eth0

それは、次の命令を実行をします:

$ sudo ifup eth0=$(echo -e '<script_input1> \n <script_input2> \n ...' | <script_name> eth0)

そしてeth0が自動的に設定されます。ここで、"map"を含む行は任意で繰り返してもいいです。

[注意] 注意

mappingスタンザのグロッブはシェルのファイル名グロブのように機能します(「シェルグロブ」参照)。

5.4.6. 手動切り替え可能なネットワーク設定

「基本ネットワーク設定」でしたように"/etc/network/interfaces"ファイルを書き直すことなくいくつかのネットワーク設定間を手動で切り替える方法を次に示します。

アクセスする必要のある全てのネットワーク設定のついて、単一の"/etc/network/interfaces"ファイルを次に示すように作ります:

auto lo
iface lo inet loopback

iface config1 inet dhcp
 hostname "mymachine"

iface config2 inet static
 address 192.168.11.100
 netmask 255.255.255.0
 broadcast 192.168.11.255
 gateway 192.168.11.1
 dns-domain lan
 dns-nameservers 192.168.11.1

iface pppoe inet manual
 pre-up /sbin/ifconfig eth0 up
 up ifup ppp0=dsl
 down ifdown ppp0=dsl
 post-down /sbin/ifconfig eth0 down

# The following is used internally only
iface dsl inet ppp
 provider dsl-provider

iface pots inet ppp
 provider provider

ifaceの後に文言であるネットワーク設定名に、ネットワークインターフェース名にの文言を使っていないことに注目下さい。また、何らかのイベントの際にネットワークインターフェースeth0を自動的に起動するautoスタンザもallow-hotplugスタンザもありません。

さあ、ネットワーク設定を切り替える準備完了です。

あなたのPCをDHCPが提供されるLANに移動しましょう。ネットワークインターフェース(物理インターフェース)eth0ネットワーク設定名(論理インターフェース名)config1を付与してそれを起動します:

$ sudo ifup eth0=config1
Password:
...

インターフェースeth0が起動され、DHCPで設定され、LANに接続されます。

$ sudo ifdown eth0=config1
...

インターフェースeth0が停止され、LANから切断されます。

あなたのPCを静的IPが提供されるLANに移動しましょう。ネットワークインターフェース(物理インターフェース)eth0ネットワーク設定名(論理インターフェース名)config2を付与してそれを起動します:

$ sudo ifup eth0=config2
...

インターフェースeth0が起動され、静的IPで設定され、LANに接続されます。dns-*で与えられる追加パラメータが"/etc/resolv.conf"の内容を設定します。この"/etc/resolv.conf"はresolvconfパッケージがインストールされている方がうまく管理されます。

$ sudo ifdown eth0=config2
...

インターフェースeth0が停止され、LANから再度切断されます。

あなたのPCをPPPoEが提供されているサービスに繋がっているBBモデムのポートに移動しましょう。ネットワークインターフェースeth0ネットワーク設定pppoeを付与してそれを起動します:

$ sudo ifup eth0=pppoe
...

インターフェースeth0が起動され、ISPに直接接続されたPPPoEで設定されます。

$ sudo ifdown eth0=pppoe
...

インターフェースeth0が停止され再切断されます。

あなたのPCをLANやBBモデムのないPOTSとモデムを使っている場所に移動しましょう。ネットワークインターフェースppp0ネットワーク設定potsを付与してそれを起動します:

$ sudo ifup ppp0=pots
...

インターフェースppp0が起動され、PPPを使ってインターネットに接続されます。

$ sudo ifdown ppp0=pots
...

インターフェースppp0が停止され再切断されます。

ifupdownシステムのネットワーク設定状態の現状は"/etc/network/run/ifstate"ファイルの内容で確認しましょう。

[警告] 警告

複数のネットワークインターフェースがある場合には、eth*ppp*等の最後の数字を調整する必要があります。

5.4.7. ifupdownシステムを使うスクリプト

ifupdownシステムはスクリプトに環境変数を引き渡して"/etc/network/*/"中にインストールされたスクリプトを自動実行します:

表5.14 ifupdownシステムが引き渡す環境変数のリスト。

環境変数 引き渡す変数値
"$IFACE" 処理対象のインターフェースの物理名(インターフェース名)
"$LOGICAL" 処理対象のインターフェースの論理名(設定名)
"$ADDRFAM" インターフェースの<address_family>
"$METHOD" インターフェースの<method_name>。(例えば"static")
"$MODE" ifupから実行されると"start"、ifdownから実行されると"stop" 。
"$PHASE" "$MODE"と同じ、ただしpre-uppost-uppre-downpost-down段階の区別を細かくします。
"$VERBOSITY" "--verbose"使用の指標; 使用されたら1、使用されなかったら0。
"$PATH" コマンドサーチパス: "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
"$IF_<OPTION>" ifaceスタンザ下の対応するオプションの値。

各環境変数"$IF_<OPTION>"は、対応する<option1>や<option2>オプションの名前に"$IF_"を付け、大文字に変換し、ハイホンを下線に変換し、英数字文字以外を捨てて作成されます。

[ティップ] ティップ

<address_family>や<method_name>や<option1>や<option2>に関しては「"/etc/network/interfaces"の基本的なシンタックス」を参照下さい。

ifupdown-extraパッケージ(「ifupdown-extraパッケージ」参照)はこのような環境変数を使ってifupdownパッケージの機能拡張をします。ifmetricパッケージ(「ifmetricパッケージ」参照)は"$IF_METRIC"変数を通してメトリック値を設定する"/etc/network/if-up.d/ifmetric"スクリプトをインストールします。ネットワーク設定の自動選択の簡単で強力な枠組みを提供しているguessnetパッケージ(「guessnetを使うmapping」参照)もまたこれらを使います。

[注意] 注意

これらの環境変数を使うネットワーク設定スクリプトのより具体的な例に関しては、"/usr/share/doc/ifupdown/examples/*"中の例示スクリプトやifschemeifupdown-scripts-zg2パッケージで使われているスクリプトを確認して下さい。このような追加スクリプトは基本的なifupdown-extraguessnetパッケージと機能の重複があります。このような追加スクリプトをインストールしたら、干渉しないようにこのようなスクリプトをカスタマイズするべきです。

5.4.8. guessnetを使うmapping

「手動切り替え可能なネットワーク設定」に記述されたように手動で設定選択する代わりに、「mappingスタンザ」に記述されたmappingメカニズムをつかってカスタムスクリプトでネットワーク設定を自動的に選択できます。

guessnetパッケージにより提供されるguessnet-ifupdown(8)コマンドはmappingスクリプトとして使われるように設計されてい、ifupdownシステムを拡張する強力な枠組みを提供します。

  • ifaceスタンザの下の各ネットワーク設定毎にguessnetオプションの値としてテスト条件をリストします。
  • mappingは最初のエラーを返さないifaceをネットワーク設定として選択します。

guessnetオプションはifupdownシステムにより実行されるスクリプトに追加の環境変数をエクスポートするだけなので、"/etc/network/interfaces"ファイルをmappingスクリプトとguessnet-ifupdownとオリジナルのネットワーク設定インフラであるifupdownとで重複して利用することで特に支障は起こりません。詳細はguessnet-ifupdown(8)を参照下さい。

[注意] 注意

"/etc/network/interfaces"中に複数のguessnetオプション行が必要な時には、オプション行の開始文字列重複をifupdownパッケージは許さないので、guessnet1guessnet2等で始まるオプション行を使いましょう。

5.5. デスクトップのためのネットワーク設定

5.5.1. GUIのネットワーク設定ツール

GNOMEのような各デスクトップ環境が提供するデフォルトのGUIのネットワーク設定ツールの能力は静的IPやDHCPのような基本設定に限られています。あなたが見ていないところで"/etc/network/interfaces"ファイルの内容を上書きしています。自分自身で実際どのように"/etc/network/interfaces"ファイルが書き換えられているか確認して下さい。

[注意] 注意

それらは手動でされた"/etc/network/interfaces"ファイルへの複雑な上級の設定を理解しないかもしれません。

5.5.2. 自動ネットワーク設定

ifupdownパッケージと独立なデーモンを通してネットワーク接続を管理する、NetworkManager (NM) (network-managerと関連パッケージ)や、Wicd (wicdパッケージ) 等の、独立の自動ネットワーク設定ツールがあります。これらによってワイアレス接続が簡単にできます。これらには洒落たGUIユーザインターフェースが付いてきます。

[警告] 警告

サーバーにはこの様な自動ネットワーク設定を使わないで下さい。これらはラップトップ上のモービルデスクトップを主対象としています。

[警告] 警告

これらの自動ネットワーク設定ツールは動く標的で、ここに書かれている事はsqueezeでは正しくないかもしれません。お気をつけ下さい。

[注意] 注意

こういった自動ネットワーク設定は、「ifupdownを使った基本的なネットワーク設定」「ifupdownを使う上級ネットワーク設定」のような"/etc/network/interfaces"への凝ったifupdown設定と互換性がないかも知れません。lennyでは、「DHCPサービスを受けるネットワークインターフェース」に書かれたようなDHCPでコントロールされているインターフェースに"hostname"スタンザがあることだけでNMがそのインターフェースを無視するようになってしまいます。最新の問題や制約条件に関してはnetwork-managerのBTSwicdのBTSを参照下さい。

NMの設定は"/usr/share/doc/network-manager/README.Debian"に記されています。その要点は:

  1. 次のようにして、例えばfooというデスクトップユーザを"netdev"グループに属するようにします:

    $ sudo adduser foo netdev
  2. "/etc/network/interfaces"の設定を次のようにできるだけ簡単にします:

    auto lo
    iface lo inet loopback
    
    auto eth0
    iface eth0 inet dhcp
  3. NMを次のようにして再起動します:

    $ sudo /etc/init.d/network-manager restart
[注意] 注意

ifupdownとの干渉を避けるために、"/etc/network/interfaces"にリストされてないインターフェースか、"auto …"または"allow-hotplug …"を使いかつ(他のオプション無しで)"iface … inet dhcp"を使って設定されているインターフェースのみがNMによって管理されます。

Wicdの設定は、"/usr/share/doc/wicd/README.Debian"に記されています。その要点は:

  1. "/etc/network/interfaces"中の設定を次のようにだけとします:

    auto lo
    iface lo inet loopback
  2. Wicdを再起動します。

    $ sudo /etc/init.d/wicd restart

5.6. 低レベルネットワーク設定

5.6.1. Iproute2コマンド

Iproute2コマンドは完全な低レベルネットワーク設定機能を提供します。型遅れとなったnet-toolsコマンドと新しいiproute2コマンド等との翻訳表を次に示します。

表5.15 型遅れとなったnet-toolsコマンドと新しいiproute2コマンド等との翻訳表。

型遅れのnet-tools 新しいiproute2等 操作
ifconfig(8) ip addr デバイスのプロトコル (IPまたはIPv6)アドレス
route(8) ip route ルーティングテーブル
arp(8) ip neigh ARPまたはNDISCキャッシュ項目
ipmaddr ip maddr マルチキャストアドレス
iptunnel ip tunnel IP経由トンネル
nameif(8) ifrename(8) MACアドレスに基づきネットワークインターフェースを命名
mii-tool(8) ethtool(8) イーサーネットデバイスの設定。

ip(8)とIPROUTE2 Utility Suite Howtoを参照下さい。

5.6.2. 安全な低レベルネットワーク操作

次の低レベルネットワークコマンドは、ネットワーク設定を変更しないので安全に使えます。

表5.16 低レベルネットワークコマンドのリスト。

コマンド 説明
ifconfig 有効インターフェースのリンクとアドレスの状態を表示
ip addr show 有効インターフェースのリンクとアドレスの状態を表示
route -n 数字を使ったアドレスで全てのルーティングテーブルを表示
ip route show 数字を使ったアドレスで全てのルーティングテーブルを表示
arp ARPキャッシュテーブルの現状の内容を表示
ip neigh ARPキャッシュテーブルの現状の内容を表示
plog pppデーモンのログを表示
ping yahoo.com "yahoo.com"までのインターネット接続の確認
whois yahoo.com ドメインデータベースに"yahoo.com"を誰が登録したかを確認
traceroute yahoo.com "yahoo.com"までのインターネット接続の追跡
tracepath yahoo.com "yahoo.com"までのインターネット接続の追跡
mtr yahoo.com "yahoo.com"までのインターネット接続の追跡(繰り返し)
dig [@dns-server.com] example.com [{a|mx|any}] "example.com"のDNSレコードを"dns-server.com"で"a"か"mx"か"any"かのレコードに関して確認します。
iptables -L -n パケットフィルタの確認
netstat -a オープンポートの発見
netstat -l --inet 聴取中のポートの発見
netstat -ln --tcp 聴取中のTCPポートの発見(数字)
dlint example.com "examle.org"のDNSゾーン情報を確認

[ティップ] ティップ

これらの低レベルネットワーク設定ツールは"/sbin/"中にあります。"/sbin/ifconfig"等のような完全コマンドパスを使うか、 "~/.bashrc"中の"$PATH"リストに"/sbin"を追加する必要があるかもしれません。

5.7. ネットワークの最適化

一般的なネットワークの最適化は本書の射程外です。ここでは消費者用の接続に関する課題にのみ触れます。

表5.17 ネットワーク最適化ツールのリスト。

パッケージ popcon サイズ 説明
iftop V:1.0, I:6 108 ネットワークインターフェースの帯域利用情報を表示
iperf V:0.4, I:2 208 インターネットプロトコルのバンド幅測定ツール
apt-spy V:0.2, I:1.6 204 バンド幅テストに基づき"/etc/apt/sources.list"ファイルを作成します。
ifstat V:0.2, I:1.0 88 インターフェース統計モニタ
bmon V:0.2, I:0.8 188 可搬型バンド幅モニタ兼速度推定機
ethstatus V:0.12, I:0.8 84 ネットワークデバイスのスループットを迅速に測定するスクリプト
bing V:0.11, I:0.7 96 経験則的確率バンド幅試験機
bwm-ng V:0.2, I:0.9 152 簡単軽量のコンソール式のバンド幅モニタ
ethstats V:0.06, I:0.3 52 コンソール式のイーサーネット統計モニタ
ipfm V:0.04, I:0.15 156 帯域分析ツール

5.7.1. 最適MTUの発見

最大送信単位(MTU)値は、ping(8)を"-M do"オプションとともに使ってICMPパケットをデータサイズ1500(IP+ICMPヘッダー分の28バイトを加えて)から始めてIPフラグメンテーションしない最大サイズを見つけることで実験的に決定できます。例えば:

$ ping -c 1 -s $((1500-28)) -M do www.debian.org
PING www.debian.org (194.109.137.218) 1472(1500) bytes of data.
From 192.168.11.2 icmp_seq=1 Frag needed and DF set (mtu = 1454)

--- www.debian.org ping statistics ---
0 packets transmitted, 0 received, +1 errors
  • …1500ではなく1452を試しましょう
  • ping(8)が成功します

このプロセスはパスMTU (PMTU)発見 (RFC1191)で、tracepath(8)コマンドで自動化できます。

[ティップ] ティップ

PMTU値が1454となる上記例はAsynchronous Transfer Mode (ATM)をバックボーンネットワークとして使い顧客をPPPoEでサービスしていたFTTPプロバイダーの場合でした。実際のPMTU値はあなたの環境に依存します。例えば私の新しいFTTPプロバイダーの場合は1500です。

表5.18 最適MTU値の基本的なガイドライン

ネットワーク環境 MTU 理由
ダイヤルアップ接続(IP: PPP) 576 標準
イーサーネット接続(IP: DHCPまたは固定) 1500 標準かつデフォルト
イーサーネット接続(IP: PPPoE) 1492 (=1500-8) PPPヘッダーに2バイト、PPPoEヘッダーに6バイト、
イーサーネット接続(ISPのバックボーン: ATM、IP: DHCPまたは固定) 1462 (=48*31-18-8) 著者推定: イーサーネットヘッダーに18、SAR末尾に8
イーサーネット接続(ISPのバックボーン: ATM、IP: PPPoE) 1454 (=48*31-8-18-8) 根拠は"Optimal MTU configuration for PPPoE ADSL Connections"を参照下さい。

これらの基本的なガイドラインに加えて、次を覚えておきましょう:

  • 何らかのトンネル手法(VPN等)を使うと、それらのオーバーヘッドのために最適MTUを更に減らすかもしれません。
  • MTU値は実験的に決定されるPMTU値を越すべきではありません。
  • もし他の制約条件を満たすなら、MTU値は一般的に大きい方がいいです。

5.7.2. MTUの設定

MTU値をそのデフォルトの1500から1454に設定する例を次に示します。

DHCP(「DHCPサービスを受けるネットワークインターフェース」参照)の場合、"/etc/network/interfaces"中の該当するifaceスタンザ行を次と交換する事ができます。例えば:

iface eth0 inet dhcp
 hostname "mymachine"
 pre-up /sbin/ifconfig $IFACE mtu 1454

静的IP(「静的IPを使うネットワークインターフェース」参照)の場合、"/etc/network/interfaces"中の該当するifaceスタンザ行を次と交換する事ができます。例えば:

iface eth0 inet static
 address 192.168.11.100
 netmask 255.255.255.0
 broadcast 192.168.11.255
 gateway 192.168.11.1
 mtu 1454
 dns-domain lan
 dns-nameservers 192.168.11.1

直接のPPPoE(「pppoeconfを使ったPPPoE接続」参照)の場合、"/etc/ppp/peers/dsl-provider"中の該当する"mtu"行を次と交換する事ができます:

mtu 1454

最大セグメントサイズ(MSS)はパケットサイズの代替尺度として使われます。MSSとMTUの関係は次です:

  • IPv4ではMSS = MTU - 40
  • IPv6ではMSS = MTU - 60
[注意] 注意

iptables(8)(「Netfilter」参照)を使う最適化はMSSを使ってパッケットサイズを制約できるのでルーターとして有用です。

5.7.3. WAN TCPの最適化

現代的な高帯域でレイテンシーの大きなWANでは、TCPのスループットはTCPバッファーサイズパラメータを"TCP Tuning Guide"や"TCP tuning"に書かれている手順で調整することで最大化できます。今のところ現在のDebianのデフォルトは高速の1G bpsのFTTPサービスでつながっている私のLANでも十分機能しています。

5.8. Netfilter

NetfilterLinuxカーネルのモジュール(「カーネルモジュール初期化」参照)を利用するステートフルファイアーウォールネットワークアドレス変換(NAT) のインフラを提供します。

表5.19 ファイアーウォールツールのリスト。

パッケージ popcon サイズ 説明
iptables V:25, I:99 1368 netfilterのための管理ツール
iptstate V:0.15, I:0.9 156 netfilterの状態を常時モニタするツール。(top(1)と似ています)
shorewall-perl V:0.16, I:0.4 608 Shorelineファイアーウォールnetfilter設定ファイル生成システム(Perlベース、lennyで推薦)
shorewall-shell I:1.6 348 Shorelineファイアーウォールnetfilter設定ファイル生成システム(シェルベース、lennyでの代替)
ipmasq V:0.2, I:0.5 612 netfilterを設定するinitスクリプトの簡単な組み合わせ(古い)

netfilterのユーザスペースの主プログラムはiptables(8)です。シェルから対話形式で手動でnetfilterを設定し、その状態をiptables-save(8)で保存し、iptables-restore(8)を使ってinitスクリプト経由でシステムのリブート時に回復できます。

shorewallのような設定ヘルパースクリプトはこの過程を簡単にします。

http://www.netfilter.org/documentation/ (または"/usr/share/doc/iptables/html/"中)の文書を参照下さい:

[ティップ] ティップ

これらはLinux 2.4のために書かれたとはいえ、iptables(8)コマンドもnetfilterカーネル機能も現在のLinux 2.6にもあてはまります。

第6章 ネットワークアプリケーション

ネットワーク接続を確立した(5章ネットワークの設定参照)あとで、各種のネットワークアプリケーションを実行できます。

6.1. ウエッブブラウザ

多くのウエッブブラウザパッケージがハイパーテキスト転送プロトコル(HTTP)を使って遠隔コンテントにアクセスするために存在します。

表6.1 ウェッブブラウザのリスト。

パッケージ popcon サイズ 説明
iceweasel V:35, I:56 3908 ウエッブブラウザ (X) (非商標化されたMozilla Firefox)
iceape-browser V:2, I:4 NOT_FOUND ウエッブブラウザ (X) (非商標化されたMozillaブラウザ、bug#505565というセキュリティ問題で削除済)。
epiphany-browser V:8, I:41 32 ウエッブブラウザ (X) (GNOME HIG準拠ブラウザ、Epiphany)
galeon V:1.3, I:2 1748 ウエッブブラウザ (X) (GNOMEブラウザ、GaleonEpiphanyで継承されました)
konqueror V:11, I:20 3652 ウエッブブラウザ (X) (KDEブラウザ、Konqueror)
w3m V:23, I:85 1968 ウエッブブラウザ(テキスト)(w3m)
lynx V:2, I:25 48 , ,
elinks V:2, I:6 1452 , ,
links V:3, I:9 1372 , ,
links2 V:1.0, I:4 3280 , ,

6.1.1. ブラウザ設定

次に示す特別のURL文字列を使うと一部のブラウザでその設定値を確認する事ができます。

  • "about:"
  • "about:config"
  • "about:plugins"

Debianは、Java (ソフトウエアプラットフォーム)Flashのみならず、MPEGMPEG2MPEG4DivXWindows Media Video (.wmv)QuickTime (.mov)MP3 (.mp3)Ogg/VorbisファイルやDVDsやVCDs等を取り扱えるブラウザのプラグインコンポーネントを提供します。Debianではnon-freeのブラウザプラグインパッケージをcontribかnon-freeのコンポーネントのブラウザプラグインとしてインストールできます。

表6.2 ブラウザプラグインのリスト。

パッケージ popcon サイズ コンポーネント 説明
icedtea-gcjwebplugin V:0.6, I:0.8 204 main Java plugin using Hotspot JIT
sun-java6-plugin I:9 52 non-free Java plugin for Sun's Java SE 6 (i386 only)
swfdec-mozilla V:11, I:23 244 main Flash plugin based on libswfdec
mozilla-plugin-gnash V:0.5, I:1.8 108 main Flash plugin based on Gnash
flashplugin-nonfree V:1.4, I:10 128 contrib Flash plugin helper to install Adobe Flash Player (i386, amd64 only)
mozilla-bonobo V:0.16, I:0.4 168 main Mozilla plugin support for GNOME Bonobo components
mozilla-plugin-vlc V:3, I:5 160 main Multimedia plugin based on VLC media player
totem-mozilla V:21, I:41 268 main Multimedia plugin based on GNOME's Totem media player
gecko-mediaplayer V:0.19, I:0.2 680 main Multimedia plugin based on (GNOME) MPlayer
nspluginwrapper V:1.9, I:3 472 contrib A wrapper to run i386 Netscape plugins on amd64 architecture

[ティップ] ティップ

上記のDebianパッケージを使うのが遥に簡単であるとはいえ、今でもブラウザのプラグインは"*.so"をプラグインディレクトリ(例えば"/usr/lib/iceweasel/plugins/")等にインストールしブラウザを再起動することで手動で有効にすることができます。

Some web sites refuse to be connected based on the user-agent string of your browser. You can work around this situation by spoofing the user-agent string. For exaple, you can do this by adding:

user_pref{"general.useragent.override","Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)"};

into user configuration files such as "~/.gnome2/epiphany/mozilla/epiphany/user.js" or "~/.mozilla/firefox/*.default/user.js". Alternatively, you can add and reset this variable by typing "about:config" into URL and right clicking its display contents.

[注意] 注意

Spoofed user-agent string may cause bad side effects with Java.

6.2. メールシステム

[注意] 注意

If you are to set up the mail server to exchange mail directly with the Internet, you should be better than reading this elementary document.

6.2.1. Modern mail service basics

In order to contain spam (unwanted and unsolicited e-mail) problems, many ISPs which provide consumer grade Internet connection are implementing counter measures:

  • The smarthost service for their customers to send message uses the message submission port (587) specified in rfc4409 with the password (SMTP AUTH service) specified in rfc4954.
  • The SMTP port (25) connection from their internal network hosts (except ISP's own outgoing mail server) to the Internet are blocked.
  • The SMTP port (25) connection to the ISP's incoming mail server from some suspicious external network hosts are blocked. (The connection from hosts on the dynamic IP address range used by the dial-up and other consumer grade Internet connections are the first ones to be blocked.)

When configuring your mail system or resolving mail delivery problems, you must consider these new limitations.

In light of these hostile Internet situation and limitations, some independent Internet mail ISPs such as Yahoo.com and Gmail.com offer the secure mail service which can be connected from anywhere on the Internet using Transport Layer Security (TLS) and its predecessor, Secure Sockets Layer (SSL) :

  • The smarthost service for their customers to send message uses the SMTP/SSL port (465) or the message submission port (587) with the password (SMTP AUTH service).
  • The incoming mail is accessible at the TLS/POP3 port (995) with POP3.
[注意] 注意

It is not realistic to run SMTP server on consumer grade network to send mail directly to the remote host reliably. They are very likely to be rejected. You must use some smarthost services offered by your connection ISP or independent mail ISPs. For the simplicity, I will assume that the smarthost is located at "smtp.hostname.dom", requires SMTP AUTH, and uses the message submission port (587) in the following text.

6.2.2. Basic mail software choice

表6.3 List of popular mail system for workstation.

パッケージ popcon サイズ 機能
exim4-daemon-light V:61, I:67 928 Exim4 mail transport agent (MTA: Debian default)
exim4-base V:63, I:69 1660 Exim4 documentation (text) and common files
exim4-doc-html I:0.8 5756 Exim4 documentation (html)
exim4-doc-info I:0.4 596 Exim4 documentation (info)
postfix V:16, I:18 3436 Postfix mail transport agent (MTA: alternative)
postfix-doc I:2 3332 Postfix documentation (html+text)
sasl2-bin V:1.9, I:5 448 Cyrus SASL API implementation (supplement postfix for SMTP-AUTH)
cyrus-sasl2-doc I:3 284 Cyrus SASL - documentation
fetchmail V:2, I:6 1812 Remote mail retrieval and forwarding utility
procmail V:18, I:86 360 Mail filter utility
mutt V:22, I:83 5772 Mail user agent (MUA) to read/write the mail usually used with vim

The choice between exim4-* and postfix packages is really up to you.

Although the popcon vote count of exim4 looks several times popular than that of postfix, this does not mean postfix is not popular with Debian developers. The Debian server system uses both exim4 and postfix. The mail header analysis of mailing list postings from prominent Debian developers also indicate both of these MTAs are as popular.

The exim4-* packages are known to have very small memory consumption and very flexible for its configuration. The postfix package is known to be compact, fast, simple, and secure. Both come with ample documentation and are as good in quality and license.

6.2.3. The mail configuration strategy for workstation

The most simple mail configuration is that the mail is sent to the ISP's smarthost and received from ISP's POP3 server by the MUA itself. This type of configuration is popular with full featured GUI based mail user agent (MUA) such as icedove(1), evolution(1), etc.. If you need to filter mail by their types, you use MUA's filtering function. For this case, the local mail transport agent (MTA) need to do local delivery only.

The alternative mail configuration is that the mail is sent via local MTA to the ISP's smarthost and received from ISP's POP3 by fetchmail(1) to the local mailbox. If you need to filter mail by their types, you use procmail(1) to filter mail into separate mailboxes. This type of configuration is popular with simple console based MUA such as mutt(1), gnus(1), etc., although this is possible with any MUAs. For this case, the local MTA need to do both smarthost delivery and local delivery.

6.2.3.1. exim4設定

For Internet via smarthost, you (re)configure exim4-* packages as follows:

$ sudo /etc/init.d/exim4 stop
$ sudo dpkg-reconfigure exim4-conf
  • Chose "mail sent by smarthost; received via SMTP or fetchmail".
  • Set "IP address or host name of the outgoing smarthost:" to "smtp.hostname.dom:587".
  • Reply to "Keep number of DNS-queries minimal (Dial-on-Demand)?" as:

    • "No" if the system is connected to Internet while booting, or
    • もしシステムが起動時にインターネットに接続されていない場合は、"Yes"。
$ sudo vim /etc/exim4/passwd.client
  • スマートホストのパスワードエントリを作成。
$ cat /etc/exim4/passwd.client
^smtp.*\.hostname\.dom:username@hostname.dom:password
$ sudo /etc/init.d/exim4 start

The host name in "/etc/exim4/passwd.client" should not be the alias. You check the real host name with:

$ host smtp.hostname.dom
smtp.hostname.dom is an alias for smtp99.hostname.dom.
smtp99.hostname.dom has address 123.234.123.89

I use regex in "/etc/exim4/passwd.client" to work around the alias issue so even if the ISP moves host pointed by the alias, SMTP AUTH will likely be working.

[注意] 注意

You must execute update-exim4.conf(8) after manually updating exim4 configuration files in "/etc/exim4/".

[注意] 注意

Starting exim4 will take long time if "No" (default value) was chosen for the debconf query of "Keep number of DNS-queries minimal (Dial-on-Demand)?" and the system is not connected to Internet while booting.

[注意] 注意

Please read the official guide at: "/usr/share/doc/exim4-base/README.Debian.gz" and update-exim4.conf(8).

[ティップ] ティップ

Local customization file "/etc/exim4/exim4.conf.localmacros" may be created to set MACROs. For example, Yahoo's mail service is said to require "MAIN_TLS_ENABLE = true" and "AUTH_CLIENT_ALLOW_NOTLS_PASSWORDS = yes" in it.

6.2.3.2. The configuration of postfix with SASL

For Internet via smarthost, you should first read postfix documentation and key manual pages:

表6.4 List of important postfix manual pages

コマンド 機能
postfix(1) Postfix control program
postconf(1) Postfixの設定ユーティリティ
postconf(5) Postfix configuration parameters
postmap(1) Postfix lookup table maintenance
postalias(1) Postfix alias database maintenance

You (re)configure postfix and sasl2-bin packages as follows:

$ sudo /etc/init.d/postfix stop
$ sudo dpkg-reconfigure postfix
  • Chose "Internet with smarthost"
  • Set "SMTP relay host (blank for none):" to "[smtp.hostname.dom]:587"
$ sudo postconf -e 'smtp_sender_dependent_authentication = yes'
$ sudo postconf -e 'smtp_sasl_auth_enable = yes'
$ sudo postconf -e 'smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd'
$ sudo postconf -e 'smtp_sasl_type = cyrus'
$ sudo vim /etc/postfix/sasl_passwd
  • スマートホストのパスワードエントリを作成。
$ cat /etc/postfix/sasl_passwd
[smtp.hostname.dom]:587     username:password
$ sudo postmap hush:/etc/postfix/sasl_passwd
$ sudo /etc/init.d/postfix start

Here the use of "[" and "]" in the dpkg-reconfigure dialogue and "/etc/postfix/sasl_passwd" ensures not to check MX record but directly use exact hostname specified. Read more for "Enabling SASL authentication in the Postfix SMTP client" in "usr/share/doc/postfix/html/SASL_README.html".

6.2.3.3. メールアドレス設定

There are a few mail address configuration files for mail transport, delivery and user agents.

表6.5 List of mail address related configuration files.

ファイル 機能 application
/etc/mailname default host name for (outgoing) mail Debian specific, mailname(5)
/etc/email-addresses host name spoofing for outgoing mail exim(8) specific, exim4-config_files(5)
/etc/postfix/generic host name spoofing for outgoing mail postfix(1) specific, activated after postmap(1) command execution.
/etc/aliases account name alias for incoming mail general, activated after newaliases(1) command execution.

The mailname in the "/etc/mailname" file is usually a fully qualified domain name (FQDN) that resolves to one of the host's IP addresses. The mobile workstation which does not have a hostname with resolvable IP address, set this mailname to the value of "hostname -f". (This is safe choice and works for both exim4-* and postfix.)

[ティップ] ティップ

The contents of "/etc/mailname" is used by many non-MTA programs for their default behavior. For mutt, set "hostname" and "from" variables in ~/muttrc file to override the mailname value. For programs in the devscripts package, such as bts(1) and dch(1), export environment variables "$DEBFULLNAME" and "$DEBEMAIL" to override it.

When setting the mailname to "hostname -f", the spoofing of the source mail address via MTA can be realized by:

  • "/etc/email-addresses" file for exim4(8) as explained in the exim4-config_files(5), and
  • "/etc/postfix/generic" file for postfix(1) as explained in the generic(5).

For postfix, the following extra steps are needed:

# postmap hash:/etc/postfix/generic
# postconf -e 'smtp_generic_maps = hash:/etc/postfix/generic'
# postfix reload

You check filters using:

  • exim(8) with -brw, -bf, -bF, -bV, … options.
  • postmap(1) with -q option.
[ティップ] ティップ

Exim comes with several utility programs such as exiqgrep(8) and exipick(8). See "dpkg -L exim4-base|grep man8/" for available commands.

6.2.4. Tips for managing the mail

6.2.4.1. 基本的なMTAの操作

There are several basic MTA operations. Some may be performed via sendmail(1) compatibility interface.

表6.6 List of basic MTA operation.

eximコマンド postfix command 説明
sendmail sendmail Read mail from standard input and arrange for delivery. (-bm)
mailq mailq List the mail queue with status and queue ID. (-bp)
newaliases newaliases Initialize alias database. (-I)
exim4 -q postqueue -f flush waiting mail (-q)
exim4 -qf postsuper -r ALL deferred; postqueue -f flush all mail
exim4 -qff postsuper -r ALL; postqueue -f flush even frozen mail
exim4 -Mg queue_id postsuper -h queue_id freeze one message by its queue ID
exim4 -Mrm queue_id postsuper -d queue_id remove one message by its queue ID
--- postsuper -d ALL remove all messages

For the script in "/etc/ppp/ip-up.d/*", "flush all mail" may be good idea.

6.2.4.2. Basic MUA — Mutt

Use mutt as the mail user agent (MUA) in combination with vim. Customize with "~/.muttrc"; for example:

# use visual mode and "gq" to reformat quotes
set editor="vim -c 'set tw=72 et ft=mail'"
#
# header weeding taken from the manual (Sven's Draconian header weeding)
#
ignore *
unignore from: date subject to cc
unignore user-agent x-mailer
hdr_order from subject to cc date user-agent x-mailer
set hostname=spoof.example.org
set from="First Last <username@example.org>"
....

Add the following to "/etc/mailcap" or "~/.mailcap" to display HTML mail and MS Word attachments inline:

text/html; lynx -force_html %s; needsterminal;
application/msword; /usr/bin/antiword '%s'; copiousoutput; description="Microsoft Word Text"; nametemplate=%s.doc

6.2.4.3. Redeliver mbox contents

You need to manually deliver mails to the sorted mailboxes in your home directory from "/var/mail/<username>" if your home directory became full and procmail(1) failed. After making disk space in the home directory, run:

# /etc/init.d/${MAILDAEMON} stop
# formail -s procmail </var/mail/<username>
# /etc/init.d/${MAILDAEMON} start

6.2.5. Choices of software for the mail

For mail system programs, there are many alternatives developed with different priority. Here is the overview.

6.2.5.1. MTA

There are many choices for MTA (mail transfer agent).

表6.7 List of MTA.

パッケージ popcon サイズ capability
exim4-daemon-light V:61, I:67 928 full
postfix V:16, I:18 3436 full (security)
exim4-daemon-heavy V:1.8, I:2 1040 full (flexible)
sendmail-bin V:2, I:2 2080 full (only if you are already familiar)
nullmailer V:0.6, I:0.8 452 strip down, no local mail
ssmtp V:0.9, I:1.4 0 strip down, no local mail
nbsmtp V:0.2, I:0.2 120 ?
courier-mta V:0.2, I:0.2 4000 very full (web interface etc.)
xmail V:0.19, I:0.2 824 light
masqmail V:0.04, I:0.06 556 light
esmtp V:0.11, I:0.2 156 light
esmtp-run V:0.08, I:0.12 8 light (sendmail compatibility extension to esmtp)
msmtp V:0.2, I:0.6 324 light
msmtp-mta V:0.08, I:0.12 32 light (sendmail compatibility extension to msmtp)

6.2.5.2. MUA

If you subscribe to Debian related mailing list, it may be a good idea to use such MUA as mutt and gnus which are the de facto standard for the participant and known to behave as expected.

表6.8 List of MUA.

パッケージ popcon サイズ タイプ
iceweasel V:35, I:56 3908 X GUI (unbranded Mozilla Firefox)
evolution V:23, I:41 10200 X GUI (part of a groupware suite)
icedove V:11, I:15 38108 X GUI (unbranded Mozilla Thunderbird)
mutt V:22, I:83 5772 character terminal probably with vim
gnus V:0.04, I:0.5 6272 character terminal under (x)emacs

6.2.5.3. The remote mail retrieval and forward utility

Although fetchmail(1) has been de facto standard for the remote mail retrieval on GNU/Linux, the authour likes getmail(1) now. If you want to reject mail before downloading to save bandwidth, mailfilter or mpop may be useful. Whichever mail retriever utilities are used, it is good idea to configure system to deliver retrieved mails to MDA, such as maildrop, via pipe.

表6.9 List of remote mail retrieval and forward utilities.

パッケージ popcon サイズ capability
fetchmail V:2, I:6 1812 mail retriever (POP3, APOP, IMAP) (old)
getmail4 V:0.3, I:0.7 632 mail retriever (POP3, IMAP4, and SDPS) (simple, secure, and reliable)
mailfilter V:0.01, I:0.07 352 mail retriever (POP3) with with regex filtering capability
mpop V:0.01, I:0.06 364 mail retriever (POP3) and MDA with filtering capability

getmail(1) configuration is described in getmail documentation. Here is my set up to access multiple POP3 accounts as user:

  • Create "/usr/local/bin/getmails" as:
#!/bin/sh
set -e
rcfiles="/usr/bin/getmail"
for file in $HOME/.getmail/config/* ; do
  rcfiles="$rcfiles --rcfile $file"
done
exec $rcfiles $@
  • Execute as follows:
$ sudo chmod 755 /usr/local/bin/getmails
$ mkdir -m 0700 $HOME/.getmail
$ mkdir -m 0700 $HOME/.getmail/config
$ mkdir -m 0700 $HOME/.getmail/log
  • Create configuration files "$HOME/.getmail/config/pop3_name" for each POP3 acconts as:
[retriever]
type = SimplePOP3SSLRetriever
server = pop.example.com
username =  pop3_name@example.com
password = secret

[destination]
type = MDA_external
path = /usr/bin/maildrop
unixfrom = True
'Spam'
[options]
verbose = 0
delete = True
delivered_to = False
message_log = ~/.getmail/log/pop3_name.log
  • Execute as follows:
$ chmod 0600 $HOME/.getmail/config/*
  • schedule "/usr/local/bin/getmails" to run every 15 minutes with cron(8) by executing "sudo crontab -e -u <user_name>" and adding following entry:
5,20,35,50 * * * * /usr/local/bin/getmails --quiet
[ティップ] ティップ

Problems of POP3 access may not come from getmail. Some popular free POP3 services may be violating the POP3 protocol and their SPAM filter may not be perfect. For example, they may delete messages just after receiving RETR command before receiving DELE command and may quarantined messages into Spam mailbox. You should minimize damages by configuring them to archive accessed messages and not to delete them. See also "Some mail was not downloaded".

6.2.5.4. MDA with filter

Most MTA programs, such as postfix and exim4, function as MDA (mail delivery agent). There are specialized MDA with filtering capabilities.

Although procmail(1) has been de facto standard for MDA with filter on GNU/Linux, authour likes maildrop(1) now. Whichever filtering utilities are used, it is good idea to configure system to deliver filtered mails to a qmail-style Maildir.

表6.10 フィルタ付きのMDAのリスト。

パッケージ popcon サイズ 説明
procmail V:18, I:86 360 MDA with filter (old)
mailagent V:0.5, I:6 1688 MDA with perl filter
maildrop V:0.3, I:0.8 1040 MDA with structured filtering language

maildrop(1) configuration is described in maildropfilter documentation. Here is a configuration example for "$HOME/.mailfilter":

logfile $HOME/.maildroplog
# clearly bad looking mails: drop them into X-trash and exit
if (    /^X-Advertisement/ ||\
        /^Subject:.*BUSINESS PROPOSAL/ ||\
        /^Subject:.*URGENT.*ASISSTANCE/ ||\
        /^Subject: *I NEED YOUR ASSISTANCE/ )
    to "$HOME/Maildir/X-trash/"

# Delivering mailinglist messages
if (    /^Precedence:.*list/ ||\
        /^Precedence:.*bulk/ ||\
        /^List-/ ||\
        /^X-Distribution:.*bulk/ )
{
    if (    /^Resent-Sender.*debian-user-request@lists.debian.org/)
        to "$HOME/Maildir/debian-user/"
    if (    /^Resent-Sender.*debian-devel-request@lists.debian.org/)
        to "$HOME/Maildir/debian-devel/"
    if (    /^Resent-Sender.*debian-announce-request@lists.debian.org/)
        to "$HOME/Maildir/debian-announce/"
    to "$HOME/Maildir/mailing-list/"
}
to "$HOME/Maildir/Inbox/"
exit
[警告] 警告

Unlike procmail, maildrop does not create missing maildir directories automatically. You must create them manually using maildirmake(1) in advance.

Equivalent configurartion can be done with procmail(1) with "$HOME/.procmailrc" as:

MAILDIR=$HOME/Maildir
DEFAULT=$MAILDIR/Inbox/
LOGFILE=$MAILDIR/Maillog
# clearly bad looking mails: drop them into X-trash and exit
:0
* 1^0 ^X-Advertisement
* 1^0 ^Subject:.*BUSINESS PROPOSAL
* 1^0 ^Subject:.*URGENT.*ASISSTANCE
* 1^0 ^Subject: *I NEED YOUR ASSISTANCE
X-trash/

# Delivering mailinglist messages
:0
* 1^0 ^Precedence:.*list
* 1^0 ^Precedence:.*bulk
* 1^0 ^List-
* 1^0 ^X-Distribution:.*bulk
{
:0
* 1^0 ^Return-path:.*debian-devel-admin@debian.or.jp
jp-debian-devel/

:0
* ^Resent-Sender.*debian-user-request@lists.debian.org
debian-user/

:0
* ^Resent-Sender.*debian-devel-request@lists.debian.org
debian-devel/

:0
* ^Resent-Sender.*debian-announce-request@lists.debian.org
debian-announce

:0
mailing-list/
}

:0
Inbox/

6.2.5.5. POP3/IMAP4 server

If you are to run a private server on LAN, you may consider to run POP3 / IMAP4 server for delivering mail to LAN clients.

表6.11 List of POP3/IMAP4 servers.

パッケージ popcon サイズ タイプ 説明
qpopper V:1.2, I:5 644 POP3 拡張Qualcommバージョン
courier-pop V:1.4, I:2 232 POP3 support only the maildir format
ipopd V:0.12, I:0.2 204 POP3 formerly part of the University of Washington IMAP package
cyrus-pop3d-2.2 V:0.16, I:0.3 856 POP3 part of the Cyrus IMAPd suite
xmail V:0.19, I:0.2 824 POP3 ESMTP/POP3 mail server
courier-imap V:3, I:4 1604 IMAP This provides access to email stored in Maildirs
uw-imapd V:1.2, I:5 272 IMAP the University of Washington IMAP
cyrus-imapd-2.2 V:0.5, I:0.7 2636 IMAP part of the Cyrus IMAPd suite

6.3. The print server and utility

In the old Unix-like system, the BSD Line printer daemon was the standard. Since the standard print out format of the free software is PostScript on the Unix like system, some filter system was used along with Ghostscript to enable printing to the non-PostScript printer.

Recently, Common UNIX Printing System (CUPS) is the new de facto standard. The CUPS uses Internet Printing Protocol (IPP). The IPP is now supported by other OSs such as Windows XP and Mac OS X and has became new cross-platform de facto standard for remote printing with bi-directional communication capability.

The standard printable data format for the application on the Debian system is the PostScript (PS) which is a page description language. The data in PS format is fed into the Ghostscript PostScript interpreter to produce the printable data specific to the printer. See 「Ghostscript」.

Thanks to the file format dependent auto-conversion feature of the CUPS system, simply feeding any data to the lpr command should generate the expected print output. (In CUPS, lpr can be enabled by installing the cups-bsd package.)

The Debian system has few notable packages for the print servers and utilities:

表6.12 プリントサーバーとユーティリティのリスト。

パッケージ popcon サイズ 機能 ポート
lpr V:3, I:3 440 BSD lpr/lpd (Line printer daemon) printer (515)
lprng V:0.9, I:1.2 3020 , , (Enhanced) , ,
cups V:29, I:40 11164 Internet Printing CUPS server IPP (631)
cups-client V:8, I:41 440 System V printer commands for CUPS: lp(1), lpstat(1), lpoptions(1), cancel(1), lpmove(8), lpinfo(8), lpadmin(8), … , ,
cups-bsd V:6, I:37 180 BSD printer commands for CUPS: lpr(1), lpq(1), lprm(1), lpc(8) , ,
cups-driver-gutenprint V:8, I:32 1264 printer drivers for CUPS Not applicable

[ティップ] ティップ

You can configure CUPS system by pointing your web browser to "http://localhost:631/" .

6.4. The remote access server and utility (SSH)

The Secure SHell (SSH) is the secure way to connect over the Internet. A free version of SSH called OpenSSH is available as the ssh package in Debian.

表6.13 リモートアクセスサーバーとユーティリティのリスト

パッケージ popcon サイズ tool comment
openssh-client V:55, I:98 2084 ssh セキュアシェルクライアント
openssh-server V:65, I:77 812 sshd セキュアシェルサーバー
ssh-askpass-fullscreen V:0.11, I:0.5 92 ssh-askpass-fullscreen asks user for a pass phrase for ssh-add (GNOME2)
ssh-askpass V:0.7, I:4 156 ssh-askpass asks user for a pass phrase for ssh-add (plain X)

[注意] 注意

See 「インターネットのためのセキュリティ強化策」 if your SSH is accessible from Internet.

[ティップ] ティップ

Please use the screen(1) program to enable remote shell process to survive the interrupted connection (see 「screenプログラム」).

6.4.1. Basics of SSH

/etc/ssh/sshd_not_to_be_run must not be present if one wishes to run the OpenSSH server.

SSH has two authentication protocols:

表6.14 List of SSH authentication protocols and methods.

SSH protocol SSH method 説明
SSH-1 RSAAuthentication RSAアイデンティティ鍵を用いるユーザ認証
, , RhostsAuthentication .rhosts based host authentication (insecure, disabled)
, , RhostsRSAAuthentication .rhosts authentication combined with RSA host key (disabled)
, , ChallengeResponseAuthentication RSAチャレンジ応答認証
, , PasswordAuthentication バスワードを用いる認証
SSH-2 PubkeyAuthentication 公開鍵を用いるユーザ認証
, , HostbasedAuthentication "~/.rhosts" or "/etc/hosts.equiv" authentication combined with public key client host authentication (disabled)
, , ChallengeResponseAuthentication チャレンジ応答認証
, , PasswordAuthentication バスワードを用いる認証

Be careful about these differences if you are using a non-Debian system.

See "/usr/share/doc/ssh/README.Debian.gz", ssh(1), sshd(8), ssh-agent(1), and ssh-keygen(1) for details.

Following are the key configuration files:

表6.15 SSH設定ファイルのリスト。

設定ファイル 機能
/etc/ssh/ssh_config SSH client defaults. See ssh_config(5).
/etc/ssh/sshd_config SSH server defaults. See sshd_config(5).
~/.ssh/authorized_keys the lists of the default public SSH keys that clients use to connect to this account on this host.
~/.ssh/identity secret SSH-1 RSA key of the user.
~/.ssh/id_rsa secret SSH-2 RSA key of the user.
~/.ssh/id_dsa secret SSH-2 DSA key of the user.

[ティップ] ティップ

See ssh-keygen(1), ssh-add(1) and ssh-agent(1) for how to use public and secret SSH keys.

The following will start an ssh(1) connection from a client.

表6.16 List of SSH client startup examples.

コマンド 説明
ssh username@hostname.domain.ext connect with default mode
ssh -v username@hostname.domain.ext connect with default mode with debugging messages
ssh -1 username@hostname.domain.ext force to connect with SSH version 1
ssh -1 -o RSAAuthentication=no -l username hostname.domain.ext force to use password with SSH version 1
ssh -o PreferredAuthentications=password -l username hostname.domain.ext force to use password with SSH version 2

If you use the same user name on the local and the remote host, you can eliminate typing "username@". Even if you use different user name on the local and the remote host, you can eliminate it using "~/.ssh/config". For Debian Alioth service with account name "foo-guest", you set "~/.ssh/config" to contain:

Host alioth.debian.org svn.debian.org git.debian.org
    User foo-guest

For the user, ssh(1) functions as a smarter and more secure telnet(1). Unlike telnet command, ssh command does not bomb on the telnet escape character (initial default CTRL-]).

6.4.2. Port forwarding for SMTP/POP3 tunneling

To establish a pipe to connect to port 25 of remote-server from port 4025 of localhost, and to port 110 of remote-server from port 4110 of localhost through ssh, execute on the local machine:

# ssh -q -L 4025:remote-server:25 4110:remote-server:110 username@remote-server

This is a secure way to make connections to SMTP/POP3 servers over the Internet. Set the "AllowTcpForwarding" entry to "yes" in "/etc/ssh/sshd_config" of the remote host.

6.4.3. Connecting with fewer passwords — RSA

One can avoid having to remember a password for each remote system by using "RSAAuthentication" (SSH-1 protocol) or PubkeyAuthentication (SSH-2 protocol).

On the remote system, set the respective entries, "RSAAuthentication yes" or "PubkeyAuthentication yes", in "/etc/ssh/sshd_config".

Then generate authentication keys locally and install the public key on the remote system:

  • "RSAAuthentication": RSA1 key for SSH-1 (deprecated because superseded.)
$ ssh-keygen
$ cat .ssh/identity.pub | ssh user1@remote "cat - >>.ssh/authorized_keys"
  • PubkeyAuthentication: RSA key for SSH-2
$ ssh-keygen -t rsa
$ cat .ssh/id_rsa.pub | ssh user1@remote "cat - >>.ssh/authorized_keys"
  • PubkeyAuthentication: DSA key for SSH-2 (deprecated because key is smaller and slow. Also see DSA-1571-1.)
$ ssh-keygen -t dsa
$ cat .ssh/id_dsa.pub | ssh user1@remote "cat - >>.ssh/authorized_keys"
[注意] 注意

There are no more reasons to work around RSA patent using DSA since it has been expired. DSA stands for Digital Signature Algorithm and slow.

One can change the pass phrase later with "ssh-keygen -p". Make sure to verify settings by testing the connection. In case of any problem, use "ssh -v".

You can add options to the entries in "~/.ssh/authorized_keys" to limit hosts and to run specific commands. See sshd(8) for details.

Note that SSH-2 has "HostbasedAuthentication". For this to work, you must adjust the settings of "HostbasedAuthentication" to "yes" in both "/etc/ssh/sshd_config" on the server machine and "/etc/ssh/ssh_config" or "~/.ssh/config" on the client machine.

6.4.4. Dealing with alien SSH clients

There are a few free SSH clients available for other platforms.

表6.17 List of free SSH clients for other platforms.

environment free SSH program
Windows puTTY (http://www.chiark.greenend.org.uk/~sgtatham/putty/) (GPL)
Windows (cygwin) SSH in cygwin (http://www.cygwin.com/) (GPL)
Macintosh Classic macSSH (http://www.macssh.com/) (GPL)
Mac OS X OpenSSH; use ssh in the Terminal application (GPL)

6.4.5. Setting up ssh-agent

It is safer to protect your SSH authentication key with a pass phrase. If it was not set, use "ssh-keygen -p" to set it.

Place your public key (e.g. "~/.ssh/id_rsa.pub") into "~/.ssh/authorized_keys" on a remote host using a password-based connection to the remote host as described above.

$ ssh-agent bash
$ ssh-add ~/.ssh/id_rsa
Enter passphrase for /home/<username>/.ssh/id_rsa:
Identity added: /home/<username>/.ssh/id_rsa (/home/<username>/.ssh/id_rsa)
  • No passphrase needed from here on, e.g.:
$ scp foo <username>@remote.host:foo
  • No password requested.
  • Press ^D to terminating ssh-agent session.

For the X server, the normal Debian startup script executes ssh-agent as the parent process. So you only need to execute ssh-add once. For more, read ssh-agent(1)and ssh-add(1).

6.4.6. Troubleshooting SSH

If you have problems, check the permissions of configuration files and run ssh with the "-v" option.

Use the "-P" option if you are root and have trouble with a firewall; this avoids the use of server ports 1--1023.

If ssh connections to a remote site suddenly stop working, it may be the result of tinkering by the sysadmin, most likely a change in "host_key" during system maintenance. After making sure this is the case and nobody is trying to fake the remote host by some clever hack, one can regain a connection by removing the "host_key" entry from "~/.ssh/known_hosts" on the local machine.

6.5. Other network application servers

表6.18 List of other network application servers.

パッケージ popcon サイズ protocol focus
telnetd V:0.5, I:1.4 156 TELNET TELNET server
telnetd-ssl V:0.16, I:0.4 204 , , , , (SSL support)
nfs-kernel-server V:14, I:23 324 NFS Unix式ファイル共有
samba V:22, I:34 13464 SMB windows file and printer sharing
netatalk V:6, I:10 2448 ATP apple/mac file and printer sharing (AppleTalk)
proftpd-basic V:4, I:4 2060 FTP general file download
wu-ftpd V:0.5, I:0.7 820 , , , ,
apache2-mpm-prefork V:36, I:42 56 HTTP general web server
apache2-mpm-worker V:5, I:6 56 , , , ,
squid V:6, I:7 1816 , , 汎用ウエッブプロキシサーバー
squid3 V:1.0, I:1.3 2404 , , , ,
slpd V:0.2, I:0.4 228 SLP LDAP サーバーとしてのOpenSLP サーバー
bind9 V:11, I:17 840 DNS IP address for other hosts
dhcp3-server V:5, I:9 808 DHCP IP address of client itself

Common Internet File System Protocol (CIFS) is the same protocol as Server Message Block (SMB).

[ティップ] ティップ

Use of proxy server such as squid is much more efficient for saving bandwidth than use of local mirror server with the full Debian archive contents.

6.6. Other network application clients

表6.19 ネットワークアプリケーションのリスト。

パッケージ popcon サイズ protocol focus
netcat V:2, I:57 36 TCP/IP TCP/IP swiss army knife
stunnel4 V:0.5, I:1.7 508 SSL Universal SSL Wrapper
telnet V:15, I:90 200 TELNET TELNET client
telnet-ssl V:0.3, I:1.2 244 , , , , (SSL support)
nfs-common V:52, I:82 504 NFS Unix式ファイル共有
smbclient V:7, I:41 25116 SMB MS windows file and printer sharing client
smbfs V:6, I:26 4656 , , Mount and umount commands for remote MS windows file
ftp V:10, I:87 160 FTP FTP client
lftp V:1.4, I:6 1724 , , , ,
ncftp V:1.7, I:8 1212 , , Full screen FTP client
wget V:29, I:99 1944 HTTPFTP Web downloader
curl V:5, I:19 304 , , , ,
dog V:0.07, I:0.3 76 HTTP Web uploader (cat with URL support)
bind9-host V:47, I:90 172 DNS The host command from bind9, priority standard
dnsutils V:14, I:91 388 , , The dig command from bind, priority standard
host V:1.5, I:3 180 , , The host command from dnsutils, priority extra
dhcp3-client V:50, I:93 608 DHCP Obtain IP address
ldap-utils V:1.6, I:7 608 LDAP Obtain data from LDAP server

6.7. The diagnosis of the system daemons

The telnet program enables manual connection and diagnosis of the system daemons. E.g.:

$ telnet mail.ispname.net pop3

The following RFCs provide required knowledge to text each system daemon.

表6.20 List of popular RFCs.

RFC 説明
rfc1939 and rfc2449 POP3 service
rfc3501 IMAP4 サービス
rfc2821 (rfc821) SMTPサービス
rfc2822 (rfc822) Mail file format
rfc2045 Multipurpose Internet Mail Extensions (MIME)
rfc819 DNSサービス
rfc2616 HTTPサービス
rfc2396 URI definition

The port usage is described in "/etc/services".

[注意] 注意

For testing TLS/SSL services such as HTTPS, you need TLS/SSL enabled telnet program.

第7章 The X window system

The X window system on the Debian system is based on the source from X.Org. As of January 2009, they are X11R7.1(etch), X11R7.3(lenny) and X11R7.3(sid).

7.1. 重要パッケージ

There are a few (meta)packages provided to ease installation.

表7.1 List of key (meta)packages for X window.

(メタ)パッケージ popcon サイズ 説明
xorg I:52 32 This metapackage provides the X libraries, an X server, a set of fonts, and a group of basic X clients and utilities.
xserver-xorg V:31, I:58 204 This package provides the full suits of the X server and its configuration.
xbase-clients V:13, I:56 184 This package provides a miscellaneous assortment of X clients.
x11-common V:51, I:90 756 This package contains the filesystem infrastructure for the X window system.
xorg-docs I:12 5008 This package contains miscellaneous documentation for the X.Org software suite.
xspecs I:1.5 6504 This package contains X protocol, extension, and library technical specifications.
menu V:31, I:58 1956 This package generates the Debian menu for all menu-aware applications.
gksu V:27, I:53 176 This package provides a Gtk+ frontend to su(1) or sudo(8).
menu-xdg I:56 76 This package converts the Debian menu structure to the freedesktop.org xdg menu structure.
xdg-utils V:12, I:50 256 This package provides utilities to integrate desktop environment provided by the freedesktop.org.
gnome-desktop-environment I:34 20 metapackage for the stadard GNOME desktop environment.
kde-core I:11 NOT_FOUND metapackage for the core KDE desktop environment.
xfce4 I:5 48 metapackage for the Xfce lightweight desktop environment.
lxde-core I:1.6 40 metapackage for the LXDE lightweight desktop environment.
fluxbox V:1.3, I:3 4332 Fluxbox: package for highly configurable and low resource X window manager.

For the basics of X, refer to X(7), the LDP XWindow-User-HOWTO.

7.2. Setting up desktop environment

A desktop environment is usually a combination of a X window manager, a file manager, and a suite of compatible utility programs.

You can setup a full desktop environment such as GNOME, KDE, Xfce, or LXDE, from the aptitude under the task menu.

[ティップ] ティップ

Task menu may be out of sync with the latest package transition state under Debian unstable/testing environment. In such situation, you need to deselect some (meta)packages listed under aptitude(8) task menu to avoid package conflicts. When deselecting (meta)packages, you must select certain packages providing their dependencies if you need to keep them.

You may alternatively setup a simple environment manually just with a X window manager such as Fluxbox.

See Window Managers for X for the guide to the X window manager and the desktop environment.

7.2.1. Debianメニュー

Debian menu system provides a general interface for both text- and X-oriented programs with update-menus(1) from the menu package. Each package installs its menu data in the "/usr/share/menu/" directory. See "/usr/share/menu/README".

7.2.2. Freedesktop.org menu

Each package which is compliant to Freedesktop.org's xdg menu system installs its menu data provided by "*.desktop" under "/usr/share/applications/". Modern desktop environments which are compliant to Freedesktop.org standard use these data to generate their menu using the xdg-utils package. See "/usr/share/doc/xdg-utils/README".

7.2.3. Debian menu under GNOME desktop environment

In order to obtain access to the traditional Debian menu under GNOME desktop environment, you must install the menu-xdg package, click "System" → "Preference" → "Main Menu", and check the box for "Debian".

[ティップ] ティップ

You may need to do the similar for other modern desktop environments which are compliant to Freedesktop.org standard.

7.3. The server/client relationship

The X window system is activated as a combination of the server and client programs. The meaning for the words server and client with respect to the words local and remote requires attention here:

表7.2 List of server/client terminology.

タイプ 説明
X サーバー a program run on a local host connected to the user's display and input devices.
Xクライアント a program run on a remote host that processes data and talks to the X server.
アプリケーションサーバー a program run on a remote host that processes data and talks to the clients.
アプリケーションクライアント a program run on a local host connected to the user's display and input devices.

7.4. The X server

See xorg(1) for X server information.

7.4.1. The (re)configuration of the X server

[注意] 注意

X server (post-lenny) is rewitten to use more information from standardized OS services such as HAL and D-bus, for its configuration than that from "/etc/X11/xorg.conf". So contents in "/etc/X11/xorg.conf" are getting less. You may need to work around transitional problems of X server.

To (re)configure an X server,

# dpkg-reconfigure --priority=low x11-common
# dpkg-reconfigure --priority=low xserver-xorg

will generate a new "/etc/X11/xorg.conf" file using dexconf(1).

If you have manually edited this "/etc/X11/xorg.conf" file but would like it to be automatically updated again, run the following command:

# sudo dpkg-reconfigure -phigh xserver-xorg

Please check your X configuration with respect to the specification of your monitor carefully. For the large high resolution CRT monitor, it is a good idea to set the refresh rate as high as your monitor can handle (85 Hz is great, 75 Hz is OK) to reduce flicker. For the LCD monitor, slower standard refresh rate (60Hz) is usually fine due to its slow response.

[注意] 注意

Be careful not to use too high refresh rate which may cause fatal hardware failure of your monitor system.

7.4.2. The connection methods to the X server

There are several ways of getting the "X server" (display side) to accept connections from an "X client" (application side):

表7.3 List of connection methods to the X server.

method パッケージ popcon サイズ ユーザ encryption pertinent use
xhost command xbase-clients V:13, I:56 184 unchecked no deprecated
xauth command xbase-clients V:13, I:56 184 確認済み no for local connection via pipe
ssh -X command openssh-client V:55, I:98 2084 確認済み yes for remote network connection
GNOME display manager gdm V:32, I:45 15207 確認済み no(XDMCP) for local connection via pipe
KDE display manager kdm V:10, I:13 3772 確認済み no(XDMCP) for local connection via pipe
X display manager xdm V:0.8, I:2 688 確認済み no(XDMCP) for local connection via pipe
WindowMaker display manager wdm V:23, I:85 1968 確認済み no(XDMCP) for local connection via pipe
LTSP display manager ldm V:0.02, I:0.11 284 確認済み yes for remote SSH network connection (thin client)

[警告] 警告

Do not use remote TCP/IP connection over unsecured network for X connection unless you have very good reason such as use of encryption. A remote TCP/IP socket connection without encryption is prone to the eavesdropping attack and is disabled by default on the Debian system. Use "ssh -X".

[警告] 警告

Do not use XDMCP connection over unsecured network either. It sends data via UDP/IP without encryption and prone to the eavesdropping attack.

[ティップ] ティップ

You can dare to enable remote TCP/IP connection by setting "DisallowTCP=false" in "/etc/gdm/gdm.conf" and by removing "-nolisten" from lines found by "find /etc/X11 -type f -print0 | xargs -0 grep nolisten", if you are in the fully secured environment.

[ティップ] ティップ

LTSP stands for Linux Terminal Server Project.

7.5. Starting the X window system

The X Window system is usually started as an X session which is the combination of an X server and connecting X clients. For normal desktop system, both of them are executed on the workstation.

To start the X Window system,

  • startx command started from the command line, or
  • one of the X display manager daemon programs *dm started from the end of the start up script in "/etc/rc?.d/" directory ("?" corresponding to the runlevel) are used to start the X session. (The start up script for the display manager daemons checks the content of the "/etc/X11/default-display-manager" file before actually executing themselves.)
[ティップ] ティップ

See 「Specific locale only under X Window」 for initial environment variables of the X display manager.

Essentially, all these programs execute the "/etc/X11/Xsession" script. Then the "/etc/X11/Xsession" script performs run-parts like action to execute scripts in the "/etc/X11/Xsession.d/" directory. This is essentially an execution of a first program which is found in the following order with the exec builtin command:

  1. The script specified as the argument of "/etc/X11/Xsession" by the X display manager, if it is defined.
  2. The "~/.xsession" or "~/.Xsession" script, if it is defined.
  3. The "/usr/bin/x-session-manager" command, if it is defined.
  4. The "/usr/bin/x-window-manager" command, if it is defined.
  5. The "/usr/bin/x-terminal-emulator" command, if it is defined.

This process is affected by the content of "/etc/X11/Xsession.options". The exact programs to which these "/usr/bin/x-*" commands point, are determined by the Debian alternative system and changed by "update-alternatives --config x-session-manager", etc.

7.5.1. Starting X session with gdm

gdm(1) lets you select the session type (or desktop environment: 「Setting up desktop environment」), and language (or locale: 「ロケール」) of the X session from its menu. It keeps the selected default value in "~/.dmrc" as, e.g.:

[Desktop]
Session=default
Language=ja_JP.UTF-8

7.5.2. Customizing the X session (classic method)

On a system where "/etc/X11/Xsession.options" contains a line "allow-user-xsession" without preceding "#" characters, any user who defines "~/.xsession" or "~/.Xsession" will be able to customize the action of "/etc/X11/Xsession" by completely overiding the system code. The last command in the "~/.xsession" file should use form of "exec some-window/session-manager" to start your favorite X window/session managers.

7.5.3. Customizing the X session (new method)

Here are new methods to customize the X session without completely overiding the system code as above.

  • The display manager gdm can select a specific session and set it as the argument of "/etc/X11/Xsession".
  • The "~/.xsessionrc" file is executed as a part of start up process (desktop independent.)
  • The "~/.gnomerc" file is executed as a part of start up process. (GNOME desktop only)
  • The GUI program based session management software can use the "~/.gnome2/session" file etc..

7.5.4. Connecting a remote X client via SSH

The use of "ssh -X" enables a secure connection from a local X server to a remote application server.

  • Set "X11Forwarding" entries to "yes" in "/etc/ssh/sshd_config" of the remote host, if you want to avoid "-X" command-line option.
  • Start the X server on the local host.
  • Open an xterm in the local host.
  • Run ssh(1) to establish a connection with the remote site.
localname @ localhost $ ssh -q -X loginname@remotehost.domain
Password:
.....
  • Run an X application command, e.g. "gimp", on the remote site.
loginname @ remotehost $ gimp &

This method allows the display of the remote X client output as if it were locally connected through a local UNIX domain socket.

7.5.5. インターネット経由のセキュアなXターミナル

Secure X terminal via Internet, which displays remotely run entire X desktop environment, can easily achieved by using specialized package such as ldm. Your local machine becomes a secure thin client to the remote application server connected via SSH.

If you want to add similar feature to your normal display manager gdm, create executable shell script at "/usr/local/bin/ssh-session" as:

#!/bin/sh -e
# Based on gdm-ssh-session in gdm source (GPL)
ZENITY=$(type -p zenity)
TARGETHOST=$($ZENITY --width=600 \
--title "Host to connect to" --entry \
--text "Enter the name of the host you want to log in to as user@host.dom:")
TARGETSESSION=$($ZENITY --width=600 --height=400 \
--title "Remote session name" --list --radiolist --text "Select one" \
--column " " --column "Session" --column "description" --print-column 2 \
TRUE "/etc/X11/Xsession" "Debian" \
FALSE "/etc/X11/xinit/Xclients" "RH variants" \
FALSE "gnome-session" "GNOME session" \
FALSE "xterm" "Safe choice" \
FALSE "rxvt" "Safe choice" \
FALSE "gnome-terminal" "Safe choice")
echo "Connecting to "$TARGETHOST" with $TARGETSESSION"
/usr/bin/ssh -A -X -T -n "$TARGETHOST" "$TARGETSESSION"
#SSH_ASKPASS=/usr/bin/ssh-askpass /usr/bin/ssh -A -X -T -n "$TARGETHOST" "$TARGETSESSION"

Then add followings to "/etc/dm/Sessions/ssh.desktop":

[Desktop Entry]
Encoding=UTF-8
Name=SSH
Comment=This session logs you into a remote host using ssh
Exec=/usr/local/bin/ssh-session
Type=Application

7.6. Fonts in the X window

X window on the Debian system support two mechanisms for font management:

  • server side font management: the original core X11 font system and
  • client side font management: the new Xft 2 font system.

The core X11 font system provides backward compatibility with older applications such as Xterm with bitmap fonts. It is supported by installing pertinent font packages which trigger defoma(1) scripts to generate required files such as "fonts.dir".

The Xft2 font system is used by all modern applications such as ones from GNOME, KDE, OpenOffice.org, etc.. It supports all fonts listed below (「基本的フォント」, 「Additional fonts」, and 「CJK fonts」) with advanced features such as anti-aliasing. It has no configuration mechanism itself, rather it relies upon the fontconfig library to configure and customize fonts as described in fonts.conf(5). Actual rasterization is supported by the FreeType 2 font engine. These new X clients using Xft2 font system can talk to modern X server via the X Rendering Extension.

表7.4 Table of packages to support X window font systems.

パッケージ popcon サイズ 説明
xfonts-utils V:36, I:70 456 X Window System font utility programs
libxft2 V:44, I:75 148 Xft: FreeType-based font drawing library for X
libfreetype6 V:58, I:88 780 FreeType 2 font engine, shared library files
fontconfig V:37, I:74 460 generic font configuration library - support binaries
fontconfig-config V:21, I:82 416 generic font configuration library - configuration
defoma V:30, I:84 449 Debian Font Manager — automatic font configuration framework
x-ttcidfont-conf I:40 156 TrueType configuration for X (for CJK support)

You can check actual font path for:

  • core X11 font path with "xset q"
  • fontconfig font default: "fc-match"
[ティップ] ティップ

"The Penguin and Unicode" is a good overview of modern X Window system. Other documentations at http://unifont.org/ should provide good information on Unicode fonts, Unicode-enabled software, internationalization, and Unicode usability issues on free/libre/open source (FLOSS) operating systems.

[ティップ] ティップ

You should rely on fontconfig infrastructure to configure fonts on the Debian system. Debian Font Manager (defoma(1)) is only useful as font installation such as X logical font description (XLFD) data.

7.6.1. 基本的フォント

There are 2 major types of computer fonts:

  • bitmap fonts (good for low resolution rasterization)
  • outline/stroke fonts (good for high resolution rasterization)

While scaling of bitmap fonts causes jugged image, scaling of outline/stroke fonts produces smooth image.

Bitmap fonts on the Debian system are provided by compressed X11 pcf bitmap font files having their file extension ".pcf.gz".

Outline fonts on the Debian system are provided by:

  • PostScript Type 1 font files having their file extension ".pfb" (binary font file) and ".afm" (font metrics file).
  • TrueType font files having their file extension ".ttf".

表7.5 Table of corresponding PostScript Type 1 fonts.

フォントパッケージ popcon サイズ sans-serif font serif font monospace font source of font
PostScript N/A N/A Helvetica Times Courier Adobe
gsfonts V:18, I:69 4792 Nimbus Sans L Nimbus Roman No9 L Nimbus Mono L URW (Adobe compatible size)
gsfonts-x11 I:29 116 Nimbus Sans L Nimbus Roman No9 L Nimbus Mono L X font support with PostScript Type 1 fonts.
t1-cyrillic I:1.9 4996 Free Helvetian Free Times Free Courier URW extended (Adobe compatible size)
lmodern V:3, I:16 46180 LMSans* LMRoman* LMTypewriter* scalable PostScript and OpenType fonts based on Computer Modern (from TeX)

表7.6 Table of corresponding TrueType fonts.

フォントパッケージ popcon サイズ sans-serif font serif font monospace font source of font
ttf-mscorefonts-installer I:11 196 Arial Times New Roman Courier New Microsoft (Adobe compatible size) (This installs non-free data)
ttf-liberation I:38 1696 Liberation Sans Liberation Serif Liberation Mono Liberation Fonts project (Microsoft compatible size)
ttf-freefont I:20 4212 FreeSans FreeSerif FreeMono GNU freefont (Microsoft compatible size)
ttf-bitstream-vera I:18 NOT_FOUND Bitstream Vera Sans Bitstream Vera Serif Bitstream Vera Sans Mono Bitstream, Inc.
ttf-dejavu I:81 68 DejaVu Sans DejaVu Serif DejaVu Sans Mono DejaVu, Bitstream with extended character code support
ttf-dejavu-core I:55 2584 DejaVu Sans DejaVu Serif DejaVu Sans Mono DejaVu, basic font style variants
ttf-dejavu-extra I:55 5768 DejaVu Sans DejaVu Serif DejaVu Sans Mono DejaVu, extra font style variants
ttf-unifont I:3 16060 N/A N/A unifont GNU Unifont, with all printable character code in Unicode 5.1 Basic Multilingual Plane (BMP)

7.6.2. Additional fonts

aptitude(8) will help you find additional fonts easily:

  • by the short package list under "Packages which depend on defoma" under the defoma package list,
  • by the short package list under "Tasks" → "Localization",
  • by the filtered flat package list of font data with regex on debtag: "~Gmade-of::data:font",
  • by the filtered flat package list of the BDF (bitmap) font packages with regex on package name: "~nxfonts-", or
  • by the filtered flat package list of the TrueType (outline) font packages with regex on package name: "~nttf-".

Since Free fonts are sometimes limited, installing or sharing some commercial TrueType fonts is an option for a Debian users. In order to make this process easy for the user, some convenience packages have been created:

  • ttf-mathematica4.1
  • ttf-mscorefonts-installer You'll have a really good selection of TrueType fonts at the expense of contaminating your Free system with non-Free fonts.

7.6.3. CJK fonts

CJK問題に関する要点を次に記します:

表7.7 Table of key words used in CJK font names to indicate font types.

font type Japanese font name Chinese font name Korean font name
sans-serif gothic, ゴチック hei, gothic dodu m, gulim, gothic
serif mincho, 明朝 so ng, ming ba tang

Font name such as "VL PGothic" with "P" is a proportional font which corresponds to the fixed width "VL Gothic" font.

For example, Shift_JIS code table comprises 7070 characters. They can be grouped into:

  • JIS X 0201 single-byte characters (191 characters),
  • JIS X 0208 double-byte characters (6879 characters). Double-byte characters occupy double width on console terminals which uses CJK fixed width fonts. In order to cope with such situation, Hanzi Bitmap Font (HBF) File with file extension ".hbf" may be deployed for fonts containing single-byte and double-byte characters.

In order to save space for TrueType font files, TrueType font collection file with file extension ".ttc" may be used.

I order to cover complicated code space of characters, CID keyed Type 1 PostScript font is used with CMap files starting themselves with "%!PS-Adobe-3.0 Resource-CMap". This is rarely used for normal X display but used for PDF rendering etc. (see 「X utility applications」).

[ティップ] ティップ

The multiple glyphs are expected for some Unicode code points due to Han unification. One of the most annoying ones are "U+3001 IDEOGRAPHIC COMMA" and "U+3002 IDEOGRAPHIC FULL STOP" whose character positions differ among CJK countries. Configuring priority of Japanese centric fonts over Chinese ones using "~/.fonts.conf" should give peace of minds to Japanese.

7.7. X applications

7.7.1. X office applications

Here is a list of basic office applications (OO is OpenOffice.org):

表7.8 List of basic X office applications

パッケージ popcon パッケージサイズ 説明 タイプ
openoffice.org-writer V:25, I:48 25020 word processor OO
openoffice.org-calc V:25, I:47 17416 spreadsheet OO
openoffice.org-impress V:22, I:47 2896 プレゼンテーション OO
openoffice.org-base V:20, I:46 9052 データベース管理 OO
openoffice.org-draw V:22, I:47 8808 vector graphics editor (draw) OO
openoffice.org-math V:20, I:46 1484 mathematical equation/formula editor OO
abiword V:4, I:7 8348 word processor GNOME
gnumeric V:4, I:8 8248 spreadsheet GNOME
gimp V:14, I:50 13468 bitmap graphics editor (paint) GTK
inkscape V:12, I:28 61584 vector graphics editor (draw) GNOME
dia-gnome V:1.6, I:4 596 flowchart and diagram editor GNOME
mergeant V:0.17, I:0.2 1412 データベース管理 GNOME
planner V:0.8, I:6 7468 プロジェクト管理 GNOME
kword V:1.1, I:2 NOT_FOUND word processor KDE
kspread V:1.0, I:2 NOT_FOUND spreadsheet KDE
kpresenter V:0.8, I:2 NOT_FOUND プレゼンテーション KDE
kexi V:0.4, I:2 NOT_FOUND データベース管理 KDE
kivio V:1.0, I:2 NOT_FOUND flowchart and diagram editor KDE
karbon V:0.9, I:2 NOT_FOUND vector graphics editor (draw) KDE
krita V:1.1, I:2 NOT_FOUND bitmap graphics editor (paint) KDE
kplato V:0.3, I:2 NOT_FOUND プロジェクト管理 KDE
kchart V:0.8, I:2 NOT_FOUND graph and chart drawing program KDE
kformula V:0.7, I:1.9 NOT_FOUND mathematical equation/formula editor KDE
kugar V:0.7, I:1.8 NOT_FOUND business quality report generator KDE

7.7.2. X utility applications

Here is a list of basic utility applications which caught my eyes:

表7.9 List of basic X utility applications

パッケージ popcon パッケージサイズ 説明 タイプ
evince V:27, I:44 1036 document(pdf) viewer GNOME
kpdf V:7, I:15 NOT_FOUND document(pdf) viewer KDE3
okular V:2, I:4 3208 document(pdf) viewer KDE4
evolution V:23, I:41 10200 Personal information Management (groupware and email) GNOME
kontact V:2, I:13 1504 Personal information Management (groupware and email) KDE
scribus V:0.7, I:3 26864 desktop page layout editor KDE
glabels V:0.19, I:0.8 1045 label editor GNOME
kbarcode V:0.07, I:0.4 2180 barcode and label printing application KDE
gnucash V:0.9, I:2 5840 個人会計 GNOME
homebank V:0.08, I:0.4 896 個人会計 GTK
kmymoney2 V:0.2, I:0.9 9488 個人会計 KDE
xsane V:7, I:42 744 scanner frontend GTK
kooka V:1.4, I:11 NOT_FOUND scanner frontend KDE

[注意] 注意

The poppler-data package (non-free, see 「Ghostscript」) needs to be installed for evince and okular to display CJK PDF documents using Cmap data (「CJK fonts」).

[注意] 注意

Installing softwares such as scribus (KDE) on GNOME desktop environment are quite acceptable since corresponding functionality is not available under GNOME desktop environment. But installing too many packages with duplicated functionalities will clutter your menu.

7.8. The X trivia

7.8.1. Keymaps and pointer button mappings in X

xmodmap(1) is a utility for modifying keymaps and pointer button mappings in the X window system. To get the keycode, run xev(1) in the X and press keys. To get the meaning of keysym, look into the MACRO definition in "/usr/include/X11/keysymdef.h" file. All "#define" statements in this file are named as "XK_" prepended to keysym names.

7.8.2. Classic X clients

Most traditional X client programs, such as xterm(1), can be started with a set of standard command line options to specify geometry, font, and display.

They also use the X resource database to configure their appearance. The system-wide defaults of X resources are stored in "/etc/X11/Xresources/*" and application defaults of them are stored in "/etc/X11/app-defaults/*". Use these settings as the starting points.

The file "~/.Xresources" is used to store user resource specifications. This file is automatically merged into the default X resources upon login. To make changes to these settings and make them effective immediately, merge them into the database using the command:

$ xrdb -merge ~/.Xresources

See x(7) and xrdb(1).

7.8.3. The X terminal emulator — xterm

Learn everything about xterm(1) at http://dickey.his.com/xterm/xterm.faq.html.

7.8.4. Running X clients as root

[警告] 警告

Never start the X display/session manager under the root account by typing in root to the prompt of the display manager such as gdm because it is considered unsafe (insecure), even when you plan to perform administrative activities. The entire X architecture is considered insecure if run as root. You must always use the lowest privilege level possible, like a regular user account.

The easiest way to run a particular X client, e.g. "foo" as root is to use sudo(8):

$ sudo foo &

もしくは、

$ sudo -s
# foo &

もしくは、

$ gksu foo &

もしくは、

$ ssh -X root@localhost
# foo &
[注意] 注意

Use of ssh(1) just for this purpose as above is waste of resource.

Please note, in order for the X client to connect to the X server,

  • values of the old user's "$XAUTHORITY" and "$DISPLAY" environment variables must be copied to the new user's ones, and
  • the file pointed by value of the "$XAUTHORITY" environment variable must be readable by the new user.

The gksu package (popcon: V:27, I:53) is a specialized GTK+ GUI package for gaining the root privileges. It can be configured to use su(1) or sudo(8) as its backend depending on the "/apps/gksu/sudo-mode" gconf key. You can edit gconf key using gconf-editor(1) (menu: "Applications" → "System Tools" → "Configuration Editor").

第8章 I18N and L10N

Multilingualization (M17N) for an application software is done in 2 steps:

  • Internationalization (I18N): To make a software potentially handle multiple locales.
  • Localization (L10N): To make a software handle an specific locale.
[ティップ] ティップ

There are 17, 18, or 10 letters between "m" and "n", "i" and "n", or "l" and "n".

The modern software such as GNOME and KDE are multilingualized. They are internationalized by making them handle UTF-8 data and localized by providing their translated messages through the gettext(1) infrastructure. Translated messages may be provided as separate localization packages. They can be selected simply by setting pertinent environment variables to the appropriate locale.

The simplest representation of the text data is ASCII which is sufficient for English and uses less than 127 characters (representable with 7 bits). In order to support much more characters for the international support, many character encoding systems have been invented. The modern and sensible encoding system is UTF-8 which can handle practically all the characters known to the human (see 「Basics of encoding」).

See Introduction to i18n for details.

The international hardware support is enabled with localized hardware configuration data.

8.1. The keyboard input

The Debian system can be configured to work with many international keyboard arrangements:

表8.1 List of keyboard reconfiguration methods.

environment コマンド
Linux console dpkg-reconfigure --priority=low console-data
X Window dpkg-reconfigure --priority=low xserver-xorg

This will support keyboard input for accented characters of many European languages with its dead-key function. For Asian languages, you need more complicated input method support such as SCIM discussed next.

8.1.1. The input method support with SCIM

Setup of multilingual input for the Debian system is simplified by using the SCIM family of packages with the im-switch package. The list of SCIM packages are:

表8.2 List of input method supports with scim.


The kinput2 method and other locale dependent Asian classic input methods still exist but are not recommended for the modern UTF-8 X environment. The uim tool chain is an alternative approach for the international input method for the modern UTF-8 X environment which is also capable for non-X environment.

8.1.2. An example for Japanese

I find the Japanese input method started under English environment ("en_US.UTF-8") very useful. Here is how I did it with SCIM.

  • Install the Japanese input tool package scim-anthy with its recommended packages such as im-switch.
  • Execute "im-switch -c" from user's shell and select "scim".
  • ユーザアカウントへの再ログイン
  • Verify setting by "im-switch -l".
  • Setup input method and mode by right clicking GUI toolbar. (You can reduce menu choice of input method)
  • Start SCIM input method by CTRL-SPACE
[注意] 注意

In order to start SCIM under the non-CJK and non-en_US locale, you need to add list of those locales in UTF-8 to the "~/.scim/global" or "/etc/scim/global" file as:

/SupportedUnicodeLocales = en_US.UTF-8,en_GB.UTF_8,fr_FR.UTF-8

次に注意下さい:

  • im-switch(8) behaves differently if command is executed from root or not.
  • Input method started by im-switch depends on the locale.
  • Use of new immodule mechanism (by setting "$GTK_IM_MODULE") may cause instability during the library transition in unstable.

For the detail of setup, see "/usr/share/doc/im-switch/README.Debian.gz", "/usr/share/doc/scim/README.Debian.gz" or "/usr/share/doc/uim/README.Debian.gz". Here key points are described.

8.1.3. Disabling the input method

If you wish to input without going through XIM, set "$XMODIFIERS" value to "none" while starting a program. This may be the case if you use Japanese input infrastructure egg on emacs(1). From shell, execute as:

$ XMODIFIERS=none emacs

In order to adjust the command executed by the Debian menu, place customized configuration in "/etc/menu/" following method described in "/usr/share/doc/menu/html".

8.2. The display output

Linux console can only display limited characters. (You need to use special terminal program such as jfbterm(1) to display non-European languages on the non-X console.)

X Window can display any characters in the UTF-8 as long as required font data exists. (The encoding of the original font data is taken care by the X Window system and transparent to the user.)

8.3. ロケール

The following will focus on the locale for applications run under X Window environment started from gdm(1).

8.3.1. Basics of encoding

The environment variable "LANG=xx_YY.ZZZZ" sets the locale to language code "xx", country code "yy", and encoding "ZZZZ" (see 「"$LANG"変数」).

Current Debian system normally sets the locale as "LANG=xx_YY.UTF-8". This uses the UTF-8 encoding with the Unicode character set. This UTF-8 encoding system is a multibyte code system and uses code points smartly. The ASCII data, which consist only with 7-bit range codes, are always valid UTF-8 data consisting only with 1 byte per character.

Previous Debian system used to set the locale as "LANG=C" or "LANG=xx_YY" (without ".UTF-8").

  • The ASCII character set is used for "LANG=C" or "LANG=POSIX".
  • The traditional encoding system in Unix is used for "LANG=xx_YY".

Actual traditional encoding system used for "LANG=xx_YY" can be identified by checking "/usr/share/i18n/SUPPORTED". For example, "en_US" uses "ISO-8859-1" encoding and "fr_FR@euro" uses "ISO-8859-15" encoding.

[ティップ] ティップ

For meaning of encoding values, see 表11.2「List of encoding values and their usage.」.

8.3.2. Rationale for UTF-8 locale

The UTF-8 encoding is the modern and sensible text encoding system for I18N and enables to represent Unicode characters, i.e., practically all characters known to human. UTF stands for Unicode Transformation Format (UTF) schemes.

I recommend to use UTF-8 locale for your desktop, e.g., "LANG=en_US.UTF-8". The first part of the locale determines messages presented by applications. For example, gedit(1) (text editor for the GNOME Desktop) under "LANG=fr_FR.UTF-8" locale can display and edit Chinese character text data while presenting menus in French, as long as required fonts and input methods are installed.

I also recommend to set the locale only using the "$LANG" environment variable. I do not see much benefit of setting a complicated combination of "LC_*" variables (see locale(1)) under UTF-8 locale.

Even plain English text may contain non-ASCII characters, e.g. left and right quotation marks are not available in ASCII:

“double quoted text”
‘single quoted text’

When ASCII plain text data is converted to UTF-8 one, it has exactly the same content and size as the original ASCII one. So you loose nothing by deploying UTF-8 locale.

Some programs consume more memory after supporting I18N. This is because they are coded to use UTF-32(UCS4) internally to support Unicode for speed optimization and consume 4 bytes per each ASCII character data independent of locale selected. Again, you loose nothing by deploying UTF-8 locale.

The vendor specific old non-UTF-8 encoding systems tend to have minor but annoying differences on some characters such as graphic ones for many countries. The deployment of the UTF-8 system by the modern OSs practically solved these conflicting encoding issues.

8.3.3. ロケールの再設定

In order for the system to access a particular locale, the locale data must be compiled from the locale database. (The Debian system does not come with all available locales pre-compiled unless you installed the locales-all package.) The full list of supported locales available for compiling are listed in "/usr/share/i18n/SUPPORTED". This lists all the proper locale names. The following will list all the available UTF-8 locales already compiled to the binary form:

$ locale -a

The following command execution will reconfigure the locale package:

  • to update the list of available locales,
  • to compile them into the binary form, and
  • to set the system wide default locale value in the "/etc/defaults/locale" for use by PAM (see 「PAM と NSS」).
# dpkg-reconfigure locales

The list of available locale should include "en_US.UTF-8" and all the interesting languages with "UTF-8".

The recommended default locale is "en_US.UTF-8" for US English. For other languages, please make sure to chose locale with "UTF-8". Any one of these settings can handle any international characters.

[注意] 注意

Although setting locale to "C" will use US English message, it handles only ASCII characters.

8.3.4. Configuring system with "$LANG"

The environment variable "$LANG" is:

  • set initially by some display manager such as gdm(1) for all X programs,
  • changed by the X session startup code via "~/.xsessionrc" for all X programs (lenny feature),
  • set initially by the PAM mechanism of login(1) for the local Linux console programs,
  • set initially by the PAM mechanism of ssh(1) for the remote console programs, or
  • changed by the shell startup code, e.g. "~/.bashrc", for all console programs.
[ティップ] ティップ

It is good idea to install system wide default locale as "en_US.UTF-8" for maximum compatibility.

8.3.5. Specific locale only under X Window

You can chose specific locale only under X Window irrespective of your system wide default locale. This should provide your best desktop experience with stability.

This way, you can always access functioning character terminal with readable messages even when X Window system is not working. This becomes essential for languages which use non-roman characters such as Chinese, Japanese, and Korean.

For gdm(1), you can select different locale for the X session from its menu independent of the system default locale value in the "/etc/defaults/locale".

You can set the locale of the X session manager and the value for the default locale permanently using PAM customization (see 「PAM と NSS」) as follows. (There may be another way available as the improvement of X session manager package but please read following as the generic and basic method of setting the locale.)

First, change the following line defining language environment variable in its PAM configuration file, such as "/etc/pam.d/gdm":

auth    required        pam_env.so read_env=1 envfile=/etc/default/locale

into

auth    required        pam_env.so read_env=1 envfile=/etc/default/locale-x

Then create a "/etc/defaults/locale-gdm" file with "-rw-r--r-- 1 root root" permission containing, eg. for Japanese message:

LANG="ja_JP.UTF-8"

and keep the default "/etc/defaults/locale" file for other programs being:

LANG="en_US.UTF-8"

This is the most generic technique to customize locale.

Alternatively for this case, you may simply change locale using the "~/.xsessionrc" file.

8.3.6. Filename encoding

For cross platform data exchanges (see 「Removable mass storage device」), you may need to mount some file system with particular encodings. For example, mount(8) for vfat filesystem assumes CP437 if used without option. You need to provide explicit mount option to use UTF-8 or CP932 for filenames.

[注意] 注意

When auto-mounting a hot-pluggable USB memory stick under modern desktop environment such as GNOME, you may provide such mount option by right clicking the icon on the desktop, click "Drive" tab, click to expand "Setting", and entering "utf8" to "Mount options:". The next time this memory stick is mounted, mount with UTF-8 is enabled.

[注意] 注意

If you are upgrading system or moving disk drives from older non-UTF-8 system, file names with non-ASCII characters may be encoded in the historic and deprecated encodings such as ISO-8859-1 or eucJP. Please seek help of text conversion tools to convert them to UTF-8. See 「Text data conversion tools」.

Samba uses Unicode for newer clients (Windows NT, 200x, XP) but uses CP850 as default for older clients (DOS and Windows 9x/Me clients). This default for older clients can be changed using "dos charset" in the "/etc/samba/smb.conf" file, e.g., to CP932 for Japanese.

8.3.7. Localized messages and translated documentation

Translations exist for many of the text messages and documents that are displayed in the Debian system, such as error messages, standard program output, menus, and manual pages. GNU gettext(1) command tool chain is used as the backend tool for most translation activities.

aptitude(8) lists under "Tasks" → "Localization" provide extensive list of useful binary packages which add localized messages to applications and provide translated documentation.

For example, you can obtain the localized message for manpage by installing the manpages-<LANG> package. To read the Italian-language manpage for <programname>, execute

LANG=it_IT.UTF-8 man <programname>

to read it from "/usr/share/man/it/".

8.3.8. Effects of the locale

The sort order of characters with sort(1) is affected by the language choice of the locale. Spanish and English locale sort differently.

The date format of ls(1) is affected by the locale. The date format of "LANG=C ls -l" and "LANG=en_US.UTF-8" are different (see 「Customized display of time and date」).

Number punctuation are different for locales. For example, in English locale, one thousand one point one is displayed as "1,000.1" while in German locale, it is displayed as "1.000,1". You see this difference in spreadsheet program.

第9章 System tips

Here, I will describe basic tips to configure and manage systems, mostly from the console.

9.1. screenプログラム

screen(1) is a very useful tool for people to access remote sites via unreliable or intermittent connections since it support interrupted network connections.

表9.1 List of programs to support interrupted network connections.

パッケージ popcon サイズ 説明
screen V:11, I:31 1036 terminal multiplexer with VT100/ANSI terminal emulation

9.1.1. The use scenario for screen(1)

screen(1) not only allows one terminal window to work with multiple processes, but also allows remote shell process to survive interrupted connections. Here is a typical use scenario of screen(1).

  1. You login to a remote machine.
  2. You start screen on a single console.
  3. You execute multiple programs in screen windows created with ^A c ("Control-A" followed by "c").
  4. You switch among the multiple screen windows by ^A n ("Control-A" followed by "n").
  5. Suddenly you need to leave your terminal, but you don't want to lose your active work by keeping the connection.
  6. You detach the screen session by any methods such as:

    • brutally unplugging your network connection,
    • typing ^A d ("Control-A" followed by "d") and manually logging out from the remote connection, or
    • typing ^A DD ("Control-A" followed by "DD") to have screen detach and log you out.
  7. You log in again to the same remote machine (even from a different terminal).
  8. You start screen as "screen -r".
  9. screen will magically reattach all previous screen windows with all actively running programs.
[ティップ] ティップ

You can save connection fees for metered network connections such as dial-up and packet ones, because you can leave a process active while disconnected, and then re-attach it later when you connect again.

9.1.2. Key bindings for the screen command

In a screen session, all keyboard inputs are sent to your current window except for the command keystroke, by default ^A ("Control-A"). All screen commands are entered by typing ^A plus a single key [plus any parameters]. Here are important ones to remember:

表9.2 screenキーバインディングのリスト。

キーバインディング 意味
^A ? show a help screen (display key bindings)
^A c create a new window and switch to it
^A n go to next window
^A p go to previous window
^A 0 go to window number 0
^A 1 go to window number 1
^A w show a list of windows
^A a send a Ctrl-A to current window as keyboard input
^A h write a hardcopy of current window to file
^A H begin/end logging current window to file
^A ^X lock the terminal (password protected)
^A d detach screen session from the terminal
^A DD detach screen session and log out

See screen(1) for details.

9.2. Data recording and presentation

9.2.1. ログデーモン

Many programs record their activities under the "/var/log/" directory.

  • The kernel log daemon: klogd(8)
  • The system log daemon: syslogd(8)

See 「システムメッセージ」 and 「カーネルメッセージ」.

9.2.2. Log analyzer

Here are notable log analyzers ("~Gsecurity::log-analyzer" in aptitude(8)).

表9.3 List of system log analyzers.

パッケージ popcon サイズ 説明
logwatch V:2, I:3 2312 log analyser with nice output written in Perl
fail2ban V:3, I:3 616 複数回の認証エラーを発生させるIPを使用禁止とする
analog V:1.4, I:17 4612 web server log analyzer
awstats V:1.7, I:3 5100 powerful and featureful web server log analyzer
sarg V:1.6, I:1.8 1448 squid analysis report generator
pflogsumm V:0.3, I:0.7 164 Postfix log entry summarizer
syslog-summary V:0.2, I:1.0 80 summarize the contents of a syslog log file
lire V:0.17, I:0.2 5056 full-featured log analyzer and report generator
fwlogwatch V:0.13, I:0.2 432 Firewall log analyzer
squidview V:0.11, I:0.6 260 monitors and analyses squid access.log files
visitors V:0.10, I:0.3 224 fast web server log analyzer
swatch V:0.08, I:0.2 112 Log file viewer with regexp matching, highlighting, & hooks
crm114 V:0.07, I:0.2 1164 The Controllable Regex Mutilator and Spam Filter (CRM114)
icmpinfo V:0.06, I:0.3 84 Interpret ICMP messages

[注意] 注意

CRM114 provides language infrastructure to write fuzzy filters with the TRE regex library. Its popular use is spam mail filter but it can be used as log analyzer.

9.2.3. Recording the shell activities cleanly

The simple use of script(1) (see 「シェル活動の記録」) to record shell activity produces a file with control characters. This can be avoided by using col(1):

$ script
Script started, file is typescript
  • do whatever …
  • Press Ctrl-D to exit script
$ col -bx <typescript >cleanedfile
$ vim cleanedfile

If you don't have script (for example, during the boot process in the initramfs), you can use following instead:

$ sh -i 2>&1 | tee typescript
[ティップ] ティップ

Some x-terminal-emulator such as gnome-terminal can record. You may wish to extend line buffer for scrollback.

[ティップ] ティップ

You may use screen(1) with "^A H" (see 「Key bindings for the screen command」) to perform recording of console.

[ティップ] ティップ

You may use emacs(1) with "M-x shell", "M-x eshell", or "M-x term" to perform recording of console. You may later use "C-x C-w" to write the buffer to a file.

9.2.4. Customized display of text data

Although pager tools such as more(1) and less(1) (see 「ページャ」) and custom tools for highlighting and formatting 「Highlighting and formatting plain text data」 can display text data nicely, general purpose editors (see 「テキストエディタ」) are most versatile and customizable.

[ティップ] ティップ

For vim(1) and its pager mode alias view(1), ":set hls" will enable highlighted search.

9.2.5. Customized display of time and date

The default display format of time and date by the "ls -l" command depends on the locale (see value 「タイムスタンプ」). The "$LANG" variable is referred first and it can be overridden by the "$LC_TIME" variable.

The actual default display format for each locale depends on the version of the standard C library (the libc6 package) used. I.e., different releases of Debian had different defaults.

If you really wish to customize this display format of time and date beyond the locale, you should set the time style value by the "--time-style" argument or by the "$TIME_STYLE" value (see ls(1), date(1), "info coreutils 'ls invocation'").

表9.4 Display examples of time and date for the "ls -l" command for lenny.

time style value locale display of time and date
iso any 01-19 00:15
long-iso any 2009-01-19 00:15
full-iso any 2009-01-19 00:15:16.000000000 +0900
locale C Jan 19 00:15
locale en_US.UTF-8 2009-01-19 00:15
locale es_ES.UTF-8 ene 19 00:15
+%d.%m.%y %H:%M any 19.01.09 00:15
+%d.%b.%y %H:%M Cまたはen_US.UTF-8 19.Jan.09 00:15
+%d.%b.%y %H:%M es_ES.UTF-8 19.ene.09 00:15

[ティップ] ティップ

You can eliminate typing long option on commandline using command alias, e.g. "alias ls='ls --time-style=+%d.%m.%y\ %H:%M'" (see 「コマンドエリアス」).

[ティップ] ティップ

ISO 8601 is followed for these iso-formats.

9.2.6. Colorized shell echo

Shell echo to most modern terminals can be colorized using ANSI escape code (see "/usr/share/doc/xterm/ctlseqs.txt.gz"). E.g.:

$ RED=$(printf "\x1b[31m")
$ NORMAL=$(printf "\x1b[0m")
$ REVERSE=$(printf "\x1b[7m")
$ echo "${RED}RED-TEXT${NORMAL} ${REVERSE}REVERSE-TEXT${NORMAL}"

9.2.7. Colorized commands

Colorized commands are handy for inspecting their output in the interactive environment. I include following in my "~/.bashrc".

if [ "$TERM" != "dumb" ]; then
    eval "`dircolors -b`"
    alias ls='ls --color=always'
    alias ll='ls --color=always -l'
    alias la='ls --color=always -A'
    alias less='less -R'
    alias ls='ls --color=always'
    alias grep='grep --color=always'
    alias egrep='egrep --color=always'
    alias fgrep='fgrep --color=always'
    alias zgrep='zgrep --color=always'
else
    alias ll='ls -l'
    alias la='ls -A'
fi

The use of alias limits color effects to the interactive command usage. It has advantage over exporting environment variable "export GREP_OPTIONS='--color=auto'" since color can be seen under pager programs such as less(1). If you wish to surpress color when piping to other programs, use "--color=auto" instead in the above example for "~/.bashrc".

[ティップ] ティップ

You can turn off these colorizing aliases in the interactive environment by invoking shell with "TERM=dumb bash".

9.2.8. Recording the graphic image of an X application

There are few ways to record the graphic image of an X application, including an xterm display.

表9.5 グラフィックイメージの操作ツールのリスト。

パッケージ popcon サイズ コマンド
xbase-clients V:13, I:56 184 xwd(1)
gimp V:14, I:50 13468 GUI menu
imagemagick V:15, I:32 304 import(1)
scrot V:0.2, I:1.2 80 scrot(1)

9.2.9. 設定ファイルの変更記録

DVCSシステムを使って設定ファイルの変更を記録する専用ツールがあります。

表9.6 List of packages to record configuration history in VCS.

パッケージ popcon サイズ 説明
etckeeper V:0.4, I:0.7 372 store configuration files and its metadata with Git (default), Mercurial, or Bazaar. (new)
changetrack V:0.06, I:0.08 152 store configuration files with RCS. (old)

I recommend to use the etckeeper package with git(1) which put entire "/etc" under VCS control. Its installation guide and tutorial are found in "/usr/share/doc/etckeeper/README.gz".

Essentially, running "sudo etckeeper init" initializes the git repository for "/etc" just like the process explained in 「Git for recording configuration history」) but with special hook scripts for more thorough setups.

As you change your configuration, you can use git(1) normally to record them. It will automatically record changes nicely every time you run package management commands, too.

[ティップ] ティップ

You can browse the change history of "/etc" by executing "sudo GIT_DIR=/etc/.git gitk" with clear view for new installed packages, removed packages, and version changes of packages.

9.3. Data storage tips

Booting your system with Linux live CDs or debian-installer CDs in rescue mode make it easy for you to reconfigure data storage on your boot device. See also 「バイナリデータ」.

9.3.1. パーティション設定

For partition configuration, although fdisk(8) has been considered standard, parted(8) deserves some attention. "Disk partitioning data", "partition table", "partition map", and "disk label" are all synonyms.

Most PCs use the classic Master Boot Record (MBR) scheme to hold disk partitioning data in the first sector, i.e., LBA sector 0 (512 bytes).

[注意] 注意

Some new PCs with Extensible Firmware Interface (EFI), including Intel-based Macs, use GUID Partition Table (GPT) scheme to hold disk partitioning data not in the first sector.

Although fdisk(8) has been standard for the disk partitioning tool, parted(8) is replacing it.

表9.7 ディスクパーティション管理パッケージのリスト

パッケージ Popcon サイズ 説明 GUIDパーティションテーブル
util-linux V:90, I:99 1848 Miscellaneous system utilities including fdisk(8) and cfdisk(8) 非サポート
parted V:1.0, I:8 164 The GNU Parted disk partition resizing program サポート
gparted V:4, I:42 3168 GNOME partition editor based on libparted サポート
qtparted V:0.17, I:1.2 764 KDE partition editor based on libparted サポート
gptsync V:0.01, I:0.15 72 Synchronize classic MBR partition table with the GPT one サポート

[注意] 注意

Although parted(8) claims to create and to resize filesystem too, it is safer to do such things using best maintained specialized tools such as mkfs(8) (mkfs.msdos(8), mkfs.ext2(8), mkfs.ext3(8), …) and resize2fs(8).

[注意] 注意

In order to switch between GPT and MBR, you need to erase first few blocks of disk contents directly (see 「Clear file contents」) and use "parted /dev/sdx mklabel gpt" or "parted /dev/sdx mklabel msdos" to set it. Please note "msdos" is use here for MBR.

9.3.2. Accessing partition using UUID

Although reconfiguration of your partition may yield different names for partitions, you can access them consistently. This is also helpful if you have multiple disks and your BIOS doesn't give them consistent device names.

  • mount(8) with "-U" options can mount a block device using UUID, instead of using its file name such as "/dev/sda3".
  • "/etc/fstab" (see fstab(5)) can use UUID.
  • Boot loaders (「2段目: ブートローダ」) may use UUID too.
[ティップ] ティップ

You can probe UUID of a block special device with vol_id(8).

9.3.3. ファイルシステム設定

For ext3 filesystem, the e2fsprogs package provides:

  • mkfs.ext3(8) to create new ext3 filesystem,
  • fsck.ext3(8) to check and to repair existing ext3 filesystem, and
  • tune2fs(8) to configure superblock of ext3 filesystem.

The mkfs(8) and fsck(8) commans are provided by the e2fsprogs package as front-ends to various filesystem dependent programs (mkfs.fstype and fsck.fstype). For ext3 filesystem, they are mkfs.ext3(8) and fsck.ext3(8) (they are hardlinked to mke2fs(8) and e2fsck(8)).

Similar commands are available for each filesystem supported by Linux.

表9.8 List of filesystem management packages

パッケージ popcon サイズ 説明
e2fsprogs V:66, I:99 1884 Utilities for the ext2/ext3/ext4 filesystems.
reiserfsprogs V:3, I:10 1200 Utilities for the Reiserfs filesystem.
dosfstools V:3, I:23 224 Utilities for the FAT filesystem. (Microsoft: MS-DOS, Windows)
xfsprogs V:2, I:10 3044 Utilities for the XFS filesystem. (SGI: IRIX)
ntfsprogs V:1.5, I:6 632 Utilities for the NTFS filesystem. (Microsoft: Windows NT, …)
jfsutils V:0.6, I:3 1116 Utilities for the JFS filesystem. (IBM: AIX, OS/2)
reiser4progs V:0.08, I:0.7 1292 Utilities for the Reiser4 filesystem.
hfsprogs V:0.04, I:0.5 324 HFSHFS Plusファイルシステムのためのユーティリティ。(Apple: Mac OS)
btrfs-tools V:0.01, I:0.13 968 Utilities for the btrfs filesystem.

[ティップ] ティップ

Ext3 filesystem is the default filesystem for the Linux system and strongly recommended to use it unless you have some specific reasons not to. After Linux kernel 2.6.28 (Debian squeeze), ext4 filesystem will be available and expected to be the default filesystem for the Linux system. btrfs filesystem is expected to be the next default filesystem after ext4 filesystem for the Linux system.

[警告] 警告

You might face some limtations with ext4 since it is new. For example, you must have Linux kernel 2.6.30 or later if you wish to resizean ext4 partition.

[ティップ] ティップ

Some tools allow access to filesystem without Linux kernel support (see 「Manipulating files without mounting disk」).

9.3.4. Filesystem creation and integrity check

The mkfs(8) command creates the filesystem on a Linux system. The fsck(8) command provides the filesystem integrity check and repair on a Linux system.

[注意] 注意

It is generally not safe to run fsck on mounted filesystems.

[ティップ] ティップ

Check files in "/var/log/fsck/" for the result of the fsck(8) command run from the boot script.

[ティップ] ティップ

Use "shutdown -F -r now" to force to run the fsck(8) command safely on all filesystems including root file system on reboot. See the shutdown(8) manpage for more.

9.3.5. Optimization of filesystem by mount options

Performance and characteristics of a filesystem can be optimized by mount options used on it (see fstab(5) and mount(8)). For example:

  • "defaults" option implies default options: "rw,suid,dev,exec,auto,nouser,async". (general)
  • "noatime" or "relatime" option is very effective for speeding up the read access. (general)
  • "user" option allows an ordinary user to mount the file system. This option implies "noexec,nosuid,nodev" option combination. (general, used for CD and floppy)
  • "noexec,nodev,nosuid" option combination is used to enhance security. (general)
  • "noauto" option limits mounting by explicit operation only. (general)
  • "data=journal" option for ext3fs can enhance data integrity against power failure with some loss of write speed.
[ティップ] ティップ

You need to provide kernel boot parameter "rootflags=data=journal" to deploy "data=journal" option for the root file system formatted with ext3fs.

9.3.6. Optimization of filesystem via superblock

Characteristics of a filesystem can be optimized via its superblock using the tune2fs(8) command. For example on "/dev/hda1":

  • Execution of "sudo tune2fs -l /dev/hda1" will display the contents of its filesystem superblock.
  • Execution of "sudo tune2fs -c 50 /dev/hda1" will change frequency of filesystem checks (fsck execution during boot-up) to every 50 boots.
  • Execution of "sudo tune2fs -j /dev/hda1" will add journaling capability to the filesystem, i.e. filesystem conversion from ext2 to ext3. (Do this on the unmounted filesystem.)
  • Execution of "sudo tune2fs -O extents,uninit_bg,dir_index /dev/hda1 && fsck -pf /dev/hda1" will convert it from ext3 to ext4. (Do this on the unmounted filesystem.)
[警告] 警告

Filesystem conversion for the boot device to the ext4 filesystem should be avoided until GRUB boot loader supports the ext4 filesystem well and installed Linux Kernel version is newer than 2.6.28.

[ティップ] ティップ

Despite its name, tune2fs(8) works not only on the ext2 filesystem but also on the ext3 and ext4 filesystems.

9.3.7. ハードディスクの最適化

[警告] 警告

Please check your hardware and read manpage of hdparam(8) before playing with harddisk configuration because this may be quite dangerous for the data integrity.

You can test disk access speed of a harddisk, e.g. "/dev/hda", by "hdparm -tT /dev/hda". For some harddisk connected with (E)IDE, you can speed it up with "hdparm -q -c3 -d1 -u1 -m16 /dev/hda" by enabling the "(E)IDE 32-bit I/O support", enabling the "using_dma flag", setting "interrupt-unmask flag", and setting the "multiple 16 sector I/O" (dangerous!).

You can test write cache feature of a harddisk, e.g. "/dev/sda", by "hdparm -W /dev/sda". You can disable its write cache feature with "hdparm -W 0 /dev/sda".

You may be able to read badly pressed CDROMs on modern high head CD-ROM drive by slowing it down with "setcd -x 2.

9.3.8. Using SMART to predict harddisk failure

You can monitor and log your harddisk which is compliant to SMART with the smartd(8) daemon.

  1. BIOSSMART機能を有効にします。
  2. Install the smartmontools package.
  3. Identify your harddisk drives by listing them with df(1).

    • Let's assume a harddisk drive to be monitored as "/dev/hda".
  4. Check the output of "smartctl -a /dev/hda" to see if SMART feature is actually enabled.

    • If not, enable it by "smartctl -s on -a /dev/hda".
  5. Enable smartd(8) daemon to run by:

    • uncomment "start_smartd=yes" in the "/etc/default/smartmontools" file.
    • restart the smartd(8) daemon by "sudo /etc/init.d/smartmontools restart".
[ティップ] ティップ

The smartd(8) daemon can be customized with the /etc/smartd.conf file including how to be notified of warnings.

9.3.9. Expand usable storage space via LVM

For partitions created on Logical Volume Manager (Linux) at install time, they can be resized easily by concatenating extents onto them or truncating extents from them over multiple storage devices without major system reconfiguration.

[注意] 注意

Deployment of the current LVM system may degrade guarantee against filesystem corruption offered by journaled file systems such as ext3fs unless their system performance is sacrificed by disabling write cache of harddisk.

9.3.10. Expand usable storage space by mounting another partition

If you have an empty partition (e.g., "/dev/sdx"), you can format it with mkfs.ext3(1) and mount(8) it to a directory where you need more space. (You need to copy original data contents.)

$ sudo mv work-dir old-dir
$ sudo mkfs.ext3 /dev/sdx
$ sudo mount -t ext3 /dev/sdx work-dir
$ sudo cp -a old-dir/* work-dir
$ sudo rm -rf old-dir

9.3.11. Expand usable storage space using symlink

If you have an empty directory (e.g., "/path/to/emp-dir") in another partition with usable space, you can create a symlink to the directory with ln(8).

$ sudo mv work-dir old-dir
$ sudo mkdir -p /path/to/emp-dir
$ sudo ln -sf /path/to/emp-dir work-dir
$ sudo cp -a old-dir/* work-dir
$ sudo rm -rf old-dir
[注意] 注意

Some software may not function well with "symlink to a directory".

9.3.12. Expand usable storage space using aufs

If you have usable space in another partition (e.g., "/path/to/"), you can create a directory in it and stack that on to a directory where you need space with aufs.

$ sudo mv work-dir old-dir
$ sudo mkdir -p /path/to/emp-dir
$ sudo mount -t aufs -o br:/path/to/emp-dir:old-dir none work-dir
[注意] 注意

Use of aufs for long term data storage is not good idea since it is under development and its design change may introduce issues.

[ティップ] ティップ

In order to use aufs, its utility package aufs-tools and kernel module package for aufs such as aufs-modules-2.6-amd64 need to be installed.

[ティップ] ティップ

aufs is used to provide writable root filesystem by many modern live CD projects.

9.4. Data encryption tips

With physical access to your PC, anyone can easily gain root privilege and access all the files on your PC (see 「rootパスワードのセキュリティ確保」). This means that login password system can not secure your private and sensitive data against possible theft of your PC. You must deploy data encryption technology to do it. Although GNU privacy guard (see 「Data security infrastructure」) can encrypt files, it takes some user efforts.

dm-crypt and eCryptfs facilitates automatic data encryption natively via Linux kernel modules with minimal user efforts.

表9.9 List of data encryption utilities.

パッケージ popcon サイズ 機能
cryptsetup V:3, I:4 904 Utilities for encrypted block device (dm-crypt / LUKS)
cryptmount V:0.09, I:0.5 304 Utilities forencrypted block device (dm-crypt / LUKS) with focus on mount/unmount by normal users
ecryptfs-utils V:0.09, I:0.2 444 Utilities for encrypted stacked filesystem (eCryptfs)

Dm-crypt is a cryptographic filesystem using device-mapper. Device-mapper maps one block device to another.

eCryptfs is another cryptographic filesystem using stacked filesystem. Stacked filesystem stacks itself on top of an existing directory of a mounted filesystem.

[注意] 注意

Data encryption costs CPU time etc. Please weigh its benefits and costs.

[注意] 注意

Entire Debian system can be installed on a encrypted disk by the debian installer (lenny or newer) using dm-crypt/LUKS and initramfs.

[ティップ] ティップ

See 「Data security infrastructure」 for user space encryption utility: GNU Privacy Guard.

9.4.1. Removable disk encryption with dm-crypt/LUKS

You can encrypt contents of removable mass storage devices, e.g. USB memory stick on "/dev/sdx", using dm-crypt/LUKS. You simply formatting it as:

# badblocks -c 10240 -s -w -t random -v /dev/sdx
# shred -v -n 1 /dev/sdx
# fdisk /dev/sdx
... "n" "p" "1" "return" "return" "w"
# cryptsetup luksFormat /dev/sdx1
...
# cryptsetup luksOpen /dev/sdx1 sdx1
...
# ls -l /dev/mapper/
total 0
crw-rw---- 1 root root  10, 60 2008-10-04 18:44 control
brw-rw---- 1 root disk 254,  0 2008-10-04 23:55 sdx1
# mkfs.vfat /dev/mapper/sdx1
...
# cryptsetup luksClose sdx1

Then, it can be mounted just like normal one on to "/media/<disk_label>", except for asking password (see 「Removable mass storage device」) under modern desktop environment, such as GNOME using gnome-mount(1). The difference is that every data written to it is encrypted. You may alternatively format media in different file format, e.g., ext3 with "mkfs.ext3 /dev/sdx1".

[注意] 注意

If you are really paranoid for the security of data, you may need to overwrite multiple times in the above example. This operation is very time consuming though.

9.4.2. Encrypted swap partition with dm-crypt

If your original "/etc/fstab" contains:

/dev/sda7 swap sw 0 0

then you can enable encrypted swap partition using dm-crypt by as

# aptitude install cryptsetup
# swapoff -a
# echo "cswap /dev/sda7 /dev/urandom swap" >> /etc/crypttab
# perl -i -p -e "s/\/dev\/sda7/\/dev\/mapper\/cswap/" /etc/fstab
# /etc/init.d/cryptdisks restart
 ...
# swapon -a

9.4.3. Automatically encrypting files with eCryptfs

You can encrypt files written under "~/Private/" automatically using eCryptfs and the ecryptfs-utils package.

  • run ecryptfs-setup-private(1) and set up "~/Private/" by following prompts.
  • activate "~/Private/" by running ecryptfs-mount-private(1).
  • move sensitive data files to "~/Private/" and make symlinks as needed.

    • candidates: "~/.fetchmailrc", "~/.ssh/identity", "~/.ssh/id_rsa", "~/.ssh/id_dsa" and other files with "go-rwx".
  • move sensitive data directories to a subdirectory in "~/Private/" and make symlinks as needed.

    • candidates: "~/.gnupg" and other directories with "go-rwx".
  • create symlink from "~/Desktop/Private/" to "~/Private/" for easier desktop operations.
  • deactivate "~/Private/" by running ecryptfs-umount-private(1).
  • activate "~/Private/" by issuing "ecryptfs-mount-private" as you need encrypted data.
[ティップ] ティップ

Since eCryptfs selectively encrypt only the sensitive files, its system cost is much less than using dm-crypt on the entire root or home device. It does not require any special on-disk storage allocation effort but cannot keep all filesystem metadata confidential.

9.4.4. Automatically mounting eCryptfs

If you use your login password for wrapping encryption keys, you can automate mounting eCryptfs via Pluggable Authentication Module by having a following line just before "pam_permit.so" in "/etc/pam.d/common-auth" as:

auth required pam_ecryptfs.so unwrap

and the last line in "/etc/pam.d/common-session" as:

session optional pam_ecryptfs.so unwrap

and the first active line in "/etc/pam.d/common-password" as:

password required pam_ecryptfs.so

This is quite convienient.

[警告] 警告

Configuration errors of PAM may lock you out of your own system. See 4章認証.

[注意] 注意

If you use your login password for wrapping encryption keys, your encrypted data are as secure as your user login password (see 「良好なパスワード」). Unless you are careful to set up a strong password, your data will be at risk when someone runs password cracking software after stealing your laptop (see 「rootパスワードのセキュリティ確保」).

9.5. Monitoring, controlling, and starting program activities

Program activities can be monitored and controlled using specialized tools.

表9.10 List of tools for monitoring and controlling program activities

パッケージ popcon サイズ 説明
time V:7, I:85 152 time(1) runs a program to report system resource usages with respect to time.
coreutils V:91, I:99 12868 nice(1) runs a program with modified scheduling priority.
bsdutils V:71, I:99 180 renice(1) modifies the scheduling priority of a running process.
powertop V:0.6, I:11 424 powertop(1) gives information about system power use on Intel-based laptops.
procps V:87, I:99 752 The "/proc" file system utilities: ps(1), top(1), kill(1), watch(1), …
psmisc V:52, I:87 536 The "/proc" file system utilities: killall(1), fuser(1), pstree(1)
cron V:91, I:99 324 The cron(8) daemon runs processes according to a schedule (in background).
at V:54, I:83 220 at(1) or batch(1) commands run a job at a specified time or below certain load level.
lsof V:16, I:91 444 lsof(8) lists open files by a running process using "-p" option.
strace V:7, I:63 420 strace(1) traces system calls and signals.
ltrace V:0.3, I:2 228 ltrace(1) traces library calls.
xtrace V:0.02, I:0.15 204 xtrace(1) traces communication between X11 client and server.

9.5.1. Time a process

コマンドが開始したプロセスによって使われた表示時間。

# time some_command >/dev/null
real    0m0.035s       # time on wall clock (elapsed real time)
user    0m0.000s       # time in user mode
sys     0m0.020s       # time in kernel mode

9.5.2. スケジューリングのプライオリティー

A nice value is used to control the scheduling priority for the process.

表9.11 List of nice values for the scheduling priority.

nice value スケジューリングのプライオリティー
19 lowest priority process (nice)
0 very high priority process for user.
-20 very high priority process for root. (not-nice)

# nice  -19 top                                      # very nice
# nice --20 wodim -v -eject speed=2 dev=0,0 disk.img # very fast

Sometimes an extreme nice value does more harm than good to the system. Use this command carefully.

9.5.3. psコマンド

The ps(1) command on the Debian support both BSD and SystemV features and helps to identify the process activity statically.

表9.12 List of ps command styles.

style typical command feature
BSD ps aux %CPU %MEMを表示
System V ps -efH PPIDを表示

For the zombie (defunct) children process, you can kill them by the parent process ID identified in the (PPID) field.

The pstree(1) command display a tree of processes.

9.5.4. topコマンド

top(1) on the Debian has rich features and helps to identify what process is acting funny dynamically.

表9.13 topのコマンドのリスト。

command key レスポンス
h or ? To show help.
f To set/reset display field.
o To reorder display field.
F To set sort key field.
k To kill a process.
r To renice a process.
q To quit the top command.

9.5.5. List files opened by a process

You can list all files opened by a process with a process ID (PID), e.g. 1 as:

$ sudo lsof -p 1

PID=1 is usually init program.

9.5.6. Trace program activities

You can trace program activity with strace(1), ltrace(1), or xtrace(1) for system calls and signals, library calls, or communication between X11 client and server. For example:

$ sudo strace ls
...

9.5.7. Identify processes using files or sockets

You can also identify processes using files or sockets by fuser(1). For example:

$ sudo fuser -v /var/log/mail.log
                     USER        PID ACCESS COMMAND
/var/log/mail.log:   root       2946 F.... syslogd

You see that file "/var/log/mail.log" is open for writing by the syslogd(8) command.

$ sudo fuser -v smtp/tcp
                     USER        PID ACCESS COMMAND
smtp/tcp:            Debian-exim   3379 F.... exim4

Now you know your system runs exim4(8) to handle TCP connections to SMTP port (25).

9.5.8. Repeating a command with a constant interval

watch(1) executes a program repeatedly with a constant interval while showing its output in fullscreen.

$ watch w

This will display who is logged on to the system updated every 2 seconds.

9.5.9. Repeating a command looping over files

There are several ways to repeat a command looping over files matching some condition, e.g. matching glob pattern "*.ext".

for x in *.ext; do if [ -f "$x"]; then command "$x" ; fi; done
  • find(1) and xargs(1) combination:
find . -type f -maxdepth 1 -name '*.ext' -print0 | xargs -0 -n 1 command
  • find(1) with "-exec" option with a command:
find . -type f -maxdepth 1 -name '*.ext' -exec command '{}' \;
  • find(1) with "-exec" option with a short shell script:
find . -type f -maxdepth 1 -name '*.ext' -exec sh -c "command '{}' && echo 'successful'" \;

The above examples are written to ensure proper handling of funny file names such as ones containing spaces. See 「Idioms for the selection of files」 for more advance uses of find(1).

9.5.10. Starting a program from GUI

You can set up to start a process from graphical user interface (GUI).

Under GNOME desktop environment, a program program can be started with proper argument by drag-and-drop of an icon to the launcher icon or by "Open with …" menu with right clicking. KDE can do the equivalent, too. Here is an example for GNOME to set up mc(1) started in gnome-terminal(1):

  • create an executable program "mc-term" as:
# cat >/usr/local/bin/mc-term <<EOF
#!/bin/sh
gnome-terminal -e "mc \$1"
EOF
# chmod 755 /usr/local/bin/mc-term
  • create a desktop launcher

    • right clicking desktop space to select "Create Launcher …"
    • set "Type" to "Application"
    • set "Name" to "mc"
    • set "Command" to "mc-term %f"
    • click "OK"
  • create an open-with association

    • right click folder to select "Open with Other Application …"
    • click open "Use a custom command" dialog and enter "mc-term %f"
    • click "Open".
[ティップ] ティップ

Launcher is a file at "~/Desktop" with ".desktop" as its extension.

9.5.11. Customizing program to be started

Some programs start another program automatically. Here are check points for customizing this process:

  • アプリケーション設定メニュー:

    • GNOME desktop: "System" → "Preferences" → "Preferred Application"
    • KDE desktop: "K" → "Control Center" → "KDE Components" → "Component Chooser"
    • Iceweasle browser: "Edit" → "Preferences" → "Applications"
    • mc(1): "/etc/mc/mc.ext"
  • environment variables such as "$BROWSER", "$EDITOR", "$VISUAL", and "$PAGER" (see eviron(7)).
  • the update-alternatives(8) system for programs such as "editor", "view", "x-www-browser", "gnome-www-browser", and "www-browser" (see 「デフォルトのテキストエディタの設定」).
  • the "~/.mailcap" and "/etc/mailcap" file contents which associate MIME type with program (see mailcap(5)).
  • the the "~/.mime.types" and "/etc/mime.types" file contents which associate file name extension with MIME type (see run-mailcap(1)).
[ティップ] ティップ

update-mime(8) updates the "/etc/mailcap" file using "/etc/mailcap.order" file (see mailcap.order(5)).

[ティップ] ティップ

The debianutils package provides sensible-browser(1), sensible-editor(1), and sensible-pager(1) which make sensible decisions on which editor, pager, and web browser to call, respectively. I recommend you to read these shell commands.

[ティップ] ティップ

In order to run a console application such as mutt under X as your prefered application, you should create an X application as following and set "/usr/local/bin/mutt-term" as your prefered application to be started as described.

# cat /usr/local/bin/mutt-term <<EOF
#!/bin/sh
gnome-terminal -e "mutt \$@"
EOF
chmod 755 /usr/local/bin/mutt-term

9.5.12. Kill a process

Use kill(1) to kill (or send a signal to) a process by the process ID.

Use killall(1) or pkill(1) to do the same by the process command name and other attributes.

表9.14 List of frequently used signals for kill command.

signal value シグナル名 機能
1 HUP restart daemon
15 TERM normal kill
9 KILL kill hard

9.5.13. Schedule tasks once

Run the at(1) command to schedule a one-time job:

$ echo 'command -args'| at 3:40 monday

9.5.14. Schedule tasks regularly

Use cron(8) to schedule tasks regularly. See crontab(1) and crontab(5).

Run the command "crontab -e" to create or edit a crontab file to set up regularly scheduled events.

Example of a crontab file:

# use /bin/sh to run commands, no matter what /etc/passwd says
SHELL=/bin/sh
# mail any output to paul, no matter whose crontab this is
MAILTO=paul
# Min Hour DayOfMonth Month DayOfWeek command (Day... are OR'ed)
# run at 00:05, every day
5  0  *  * *   $HOME/bin/daily.job >> $HOME/tmp/out 2>&1
# run at 14:15 on the first of every month -- output mailed to paul
15 14 1  * *   $HOME/bin/monthly
# run at 22:00 on weekdays(1-5), annoy Joe. % for newline, last % for cc:
0 22 *   * 1-5 mail -s "It's 10pm" joe%Joe,%%Where are your kids?%.%%
23 */2 1 2 *   echo "run 23 minutes after 0am, 2am, 4am ..., on Feb 1"
5  4 *   * sun echo "run at 04:05 every sunday"
# run at 03:40 on the first Monday of each month
40 3 1-7 * *   [ "$(date +%a)" == "Mon" ] && command -args
[ティップ] ティップ

For the system not running continuously, install the anacron package to schedule periodic command at the specified intervals as closely as machine-uptime permits.

9.5.15. Alt-SysRq

Insurance against system malfunction is provided by the kernel compile option "Magic SysRq key" (SAK key) which is now the default for the Debian kernel. Pressing Alt-SysRq followed by one of the following keys does the magic of rescuing control of the system:

表9.15 List of SAK command keys.

key following Alt-SysRq 機能
r Unraw restores the keyboard after things like X crashes.
0 Changing the console loglevel to 0 reduces error messages.
k SAK (system attention key) kills all processes on the current virtual console.
e Send a SIGTERM to all processes, except for init(8).
i Send a SIGKILL to all processes, except for init(8).
s Sync all mounted filesystems.
u Remount all mounted filesystems read-only (umount).
b Reboot the system without syncing or unmounting.

The combination of "Alt-SysRq s", "Alt-SysRq u", and "Alt-SysRq r" is good for getting out of really bad situations.

See "/usr/share/doc/linux-doc-2.6.*/Documentation/sysrq.txt.gz".

[注意] 注意

The Alt-SysRq feature may be considered a security risk by allowing users access to root-privileged functions. Placing "echo 0 >/proc/sys/kernel/sysrq" in "/etc/rc.local" or "kernel.sysrq = 0" in "/etc/sysctl.conf" will disable the Alt-SysRq feature.

[ティップ] ティップ

From SSH terminal etc., you can use the Alt-SysRq feature by writing to the "/proc/sysrq-trigger". For example, "echo s > /proc/sysrq-trigger; echo u > /proc/sysrq-trigger" from the root shell prompt will sync and umount all mounted filesystems.

9.6. System maintenance tips

9.6.1. Who is logged on

You can check who is logged on to the system with w(1) or who(1).

9.6.2. Warn everyone

You can send message to everyone who is logged on to the system with wall(1):

$ echo "We are shutting down in 1 hour" | wall

9.6.3. Hardware identification

For the PCI-like devices (AGP, PCI-Express, CardBus, ExpressCard, etc.), lspci(8) (probably with "-nn" option) is a good start for the hardware identification

Alternatively, you can identify the hardware by reading contents of "/proc/bus/pci/devices" or browsing directory tree under "/sys/bus/pci" (see 「procfsとsysfs」).

表9.16 List of hardware identification tools.

パッケージ popcon サイズ 説明
pciutils V:16, I:92 780 Linux PCI Utilities, lspci(8)
usbutils V:38, I:97 548 Linux USB utilities, lsusb(8)
pcmciautils V:0.9, I:14 172 PCMCIA utilities for Linux 2.6, pccardctl(8)
scsitools V:0.2, I:1.3 484 Collection of tools for SCSI hardware management, lsscsi(8)
pnputils V:0.02, I:0.2 108 Plug and Play BIOS utilities, lspnp(8)
procinfo V:0.5, I:4 164 Displays system information from "/proc", lsdev(8)
lshw V:1.1, I:6 804 Information about hardware configuration, lshw(1)
discover V:4, I:14 928 Hardware identification system, discover(8)

9.6.4. ハードウエア設定

Although most of the hardware configuration on modern GUI desktop systems such as GNOME and KDE can be managed through accompanying GUI configuration tools, it is a good idea to know some basics methods to configure them.

表9.17 List of hardware configuration tools.

パッケージ popcon サイズ 説明
hal V:45, I:58 1844 Hardware Abstraction Layer, lshal(1)
console-tools V:59, I:95 948 Linux console font and keytable utilities.
x11-xserver-utils V:32, I:46 648 X server utilities. xset(1) and xmodmap(1).
acpid V:55, I:90 200 Daemon to manage events delivered by the Advanced Configuration and Power Interface (ACPI)
acpi V:3, I:33 92 Utilities for ACPI devices
apmd V:1.2, I:12 144 Daemon to manage events delivered by the Advanced Power Management (APM)
powersaved V:0.7, I:0.9 1800 Daemon to manage battery, temperature, ac, cpufreq (SpeedStep, Powernow!) control and monitor with ACPI and APM supports.
noflushd V:0.07, I:0.14 244 Allow idle hard disks to spin down
sleepd V:0.07, I:0.11 92 Puts a laptop to sleep during inactivity
hdparm V:13, I:34 284 Hard disk access optimization. Very effective but dangerous. You must read hdparm(8) first.
smartmontools V:6, I:18 828 Control and monitor storage systems using S.M.A.R.T.
setserial V:2, I:4 176 Collection of tools for serial port management.
memtest86+ V:0.5, I:4 384 Collection of tools for memory hardware management.
scsitools V:0.2, I:1.3 484 Collection of tools for SCSI hardware management.
tpconfig V:0.4, I:0.5 208 A program to configure touchpad devices
setcd V:0.08, I:0.4 28 Compact disc drive access optimization.
big-cursor I:0.19 68 Larger mouse cursors for X

Here, ACPI is a newer framework for the power management system than APM.

9.6.5. System and hardware time

The following will set system and hardware time to MM/DD hh:mm, CCYY.

# date MMDDhhmmCCYY
# hwclock --utc --systohc
# hwclock --show

Times are normally displayed in the local time on the Debian system but the hardware and system time usually use UTC.

If the hardware (BIOS) time is set to GMT, change the setting to "UTC=yes" in the "/etc/default/rcS".

If you wish to update system time via network, consider to use the NTP service with the packages such as ntp, ntpdate, and chrony. See:

[ティップ] ティップ

ntptrace(8) in the ntp package can trace a chain of NTP servers back to the primary source.

9.6.6. ターミナルの設定

There are several components to configure character console and ncurses(3) system features:

  • the "/etc/terminfo/*/*" file (terminfo(5))
  • the "$TERM" environment variable (term(7))
  • setterm(1), stty(1), tic(1), and toe(1)

If the terminfo entry for xterm doesn't work with a non-Debian xterm, change your terminal type, "$TERM", from "xterm" to one of the feature-limited versions such as "xterm-r6" when you log in to a Debian system remotely. See "/usr/share/doc/libncurses5/FAQ" for more. "dumb" is the lowest common denominator for "$TERM".

9.6.7. The sound infrastructure

Device drivers for sound cards for current Linux 2.6 are provided by Advanced Linux Sound Architecture (ALSA). ALSA provides emulation mode for previous Open Sound System (OSS) for compatibility.

Run "dpkg-reconfigure linux-sound-base" to select the sound system to use ALSA via blacklisting of kernel modules. Unless you have very new sound hardware, udev infrastructure should configure your sound system.

[ティップ] ティップ

Use "cat /dev/urandom > /dev/audio" or speaker-test(1) to test speaker. (^C to stop)

[ティップ] ティップ

If you can not get sound, your speaker may be connected to a muted output. Modern sound system has many outputs. alsamixer(1) in the alsa-utils package is useful to configure volume and mute settings.

Application softwares may be configured not only to access sound devices directly but also to access them via some standardized sound server system.

表9.18 サウンドパッケージのリスト。

パッケージ Popcon サイズ 説明
linux-sound-base V:42, I:55 136 Base package for ALSA and OSS sound systems
alsa-base V:3, I:54 464 ALSA driver configuration files
alsa-utils V:38, I:55 1964 Utilities for configuring and using ALSA
oss-compat V:26, I:33 60 OSS compatibility under ALSA preventing "/dev/dsp not found" errors
esound-common V:13, I:63 193 Enlightened Sound Daemon (ESD) common (Enlightenment and GNOME)
esound V:2, I:17 48 Enlightened Sound Daemon (ESD) server (Enlightenment and GNOME)
esound-clients V:8, I:21 140 Enlightened Sound Daemon (ESD) client (Enlightenment and GNOME)
libesd-alsa0 V:2, I:4 60 Enlightened Sound Daemon (ESD) library Enlightenment and GNOME)
libesd0 V:3, I:59 52 Enlightened Sound Daemon (ESD) library (Enlightenment and GNOME) - OSS
arts I:13 40 aRtsサーバー(KDE)
libarts1c2a V:21, I:38 6064 aRtsライブラリー(KDE)
libartsc0 V:18, I:44 76 aRtsライブラリー(KDE)
jackd V:1.8, I:5 400 JACK Audio Connection Kit. (JACK) server (low latency)
libjack0 V:5, I:38 540 JACK Audio Connection Kit. (JACK) library (low latency)
libjack0.100.0-0 I:17 48 JACK Audio Connection Kit. (JACK) library (low latency)
nas V:0.19, I:0.2 328 Network Audio System (NAS) server
libaudio2 V:29, I:55 204 Network Audio System (NAS) library
pulseaudio V:2, I:4 3440 PulseAudio server, replacement for ESD
libpulse0 V:7, I:34 752 PulseAudio client library, replacement for ESD
libpulsecore9 I:0.9 NOT_FOUND PulseAudio server library, replacement for ESD
libgstreamer0.10-0 V:29, I:57 2960 GStreamer: GNOME sound engine
libxine1 V:6, I:40 24 xine: KDE older sound engine
libphonon4 I:11 556 Phonon: KDE new sound engine

There is usually a common sound engine for each popular desktop environment. Each sound engine used by the application can choose to connect to different sound servers.

9.6.8. Disable the screen saver

For disabling the screen saver, use following commands.

表9.19 List of commands for disabling the screen saver.

environment コマンド
The Linux console setterm -powersave off
The X Window by turning off screensaver xset s off
The X Window by disabling dpms xset -dpms
The X Window by GUI configuration of screen saver xscreensaver-command -prefs

9.6.9. Disable the sound (beep)

One can always unplug the PC speaker. ;-) Removing pcspkr kernel module does this for you.

The following will prevent the readline(3) program used by bash(1) to beep when encountering "\a" (ASCII=7):

$ echo "set bell-style none">> ~/.inputrc

9.6.10. 使用メモリ

The kernel boot message in the "/var/log/dmesg" contains the total exact size of available memory.

free(1) and top(1) display information on memory resources on the running system.

$ grep '\] Memory' /var/log/dmesg
[    0.004000] Memory: 990528k/1016784k available (1975k kernel code, 25868k reserved, 931k data, 296k init)
$ free -k
             total       used       free     shared    buffers     cached
Mem:        997184     976928      20256          0     129592     171932
-/+ buffers/cache:     675404     321780
Swap:      4545576          4    4545572

For my MacBook with 1GB=1048576k DRAM (video system steals some of this):

表9.20 List of memory sizes reported.

報告 サイズ
Total size in dmesg 1016784k = 1GB - 31792k
Free in dmesg 990528k
Total under shell 997184k
Free under shell 20256k

Do not worry about the large size of "used" and the small size of "free" in the "Mem:" line, but read the one under them (675404 and 321780 in the example below) and relax.

9.6.11. System security and integrity check

Poor system maintenance may expose your system to external exploitation.

For system security and integrity check, you should start with:

表9.21 システムセキュリティや整合性確認のためのツールリスト

パッケージ popcon サイズ 説明
logcheck V:3, I:4 264 This mails anomalies in the system logfiles to the administrator
debsums V:2, I:3 264 こうしてインストールされたパッケージファイルはMD5チェックサムを使って検証されます。
chkrootkit V:2, I:6 864 ルートキット検出器。
clamav V:2, I:11 504 Unix用アンチウィルスユーティリティー -- コマンドラインインターフェース
tiger V:0.8, I:1.0 3088 Report system security vulnerabilities
tripwire V:0.6, I:0.8 5020 ファイルやディレクトリの整合性チェッカー
john V:0.5, I:2 476 Active password cracking tool
aide V:0.3, I:0.5 1112 Advanced Intrusion Detection Environment - static binary
bastille V:0.19, I:0.5 1960 セキュリティ強化ツール
integrit V:0.10, I:0.2 440 A file integrity verification program
crack V:0.05, I:0.2 204 Password guessing program

Here is a simple script to check for typical world writable incorrect file permissions.

# find / -perm 777 -a \! -type s -a \! -type l -a \! \( -type d -a -perm 1777 \)
[注意] 注意

Since the debsums package uses MD5 checksums stored locally, it can not be fully trusted as the system security audit tool against malicious attacks.

9.7. カーネル

Debian distributes modularized Linux kernel as packages for supported architectures.

9.7.1. Linux kernel 2.6

There are few notable features on Linux kernel 2.6 compared to 2.4.

  • Devices are created by the udev system (see 「udevシステム」).
  • Read/write accesses to IDE CD/DVD devices do not use the ide-scsi module.
  • Network packet filtering functions use iptable kernel modules.

9.7.2. Kernel headers

Most normal programs don't need kernel headers and in fact may break if you use them directly for compiling. They should be compiled against the headers in "/usr/include/linux" and "/usr/include/asm" provided by the libc6-dev package (created from the glibc source package) on the Debian system.

[注意] 注意

For compiling some kernel-specific programs such as the kernel modules from the external source and the automounter daemon (amd), you must include path to the corresponding kernel headers, e.g. "-I/usr/src/linux-particular-version/include/", to your command line. module-assistant(8) (or its short form m-a) helps users to build and install module package(s) easily for one or more custom kernels.

9.7.3. Kernel and module compile

Debian has its own method of compiling the kernel and related modules.

表9.22 Debianシステム上でカーネルの再コンパイルためにインストールする重要パッケージのリスト

パッケージ popcon サイズ 説明
build-essential I:45 48 essential packages for building Debian packages: make, gcc, …
bzip2 V:57, I:80 132 compress and decompress utilities for bz2 files
libncurses5-dev V:4, I:27 6724 developer's libraries and docs for ncurses
git-core V:6, I:10 14344 git: distributed revision control system used by the Linux kernel
fakeroot V:4, I:27 444 provide fakeroot environment for building package as non-root
initramfs-tools V:35, I:97 420 tool to build an initramfs (Debian specific)
kernel-package V:2, I:18 2340 tool to build Linux kernel packages (Debian specific)
module-assistant V:4, I:22 540 tool to help build module packages (Debian specific)
devscripts V:2, I:13 1656 helper scripts for a Debian Package maintainer (Debian specific)
linux-tree-2.6.* N/A N/A Linuxカーネルのソースツリーのメタパッケージ(Debian固有)

If you use initrd in 「2段目: ブートローダ」, make sure to read the related information in initramfs-tools(8), update-initramfs(8), mkinitramfs(8) and initramfs.conf(5).

[警告] 警告

Do not put symlinks to the directories in the source tree (e.g. "/usr/src/linux*") from "/usr/include/linux" and "/usr/include/asm" when compiling the Linux kernel source. (Some outdated documents suggest this.)

[注意] 注意

When compiling the latest Linux kernel on the Debian stable system, the use of backported latest tools from the Debian unstable may be needed.

9.7.4. Kernel source compile: Debian standard method

The Debian standard method for compiling kernel source to create a custom kernel package uses make-kpkg(1). The official documentation is in (the bottom of) "/usr/share/doc/kernel-package/README.gz". See kernel-pkg.conf(5) and kernel-img.conf(5) for customization.

Here is an example for amd64 system:

# aptitude install linux-tree-<version>
$ cd /usr/src
$ tar -xjvf linux-source-<version>.tar.bz2
$ cd linux-source-<version>
$ cp /boot/config-<oldversion> .config
$ make menuconfig
 ...
$ make-kpkg clean
$ fakeroot make-kpkg --append_to_version -amd64 --initrd --revision=rev.01 kernel_image modules_image
$ cd ..
# dpkg -i linux-image*.deb
  • reboot to new kernel with "shutdown -r now" .
[注意] 注意

When you intend to create a non-modularized kernel compiled only for one machine, invoke make-kpkg without "--initrd" option since initrd is not used. Invocation of "make oldconfig" and "make dep" are not required since "make-kpkg kernel_image" invokes them.

9.7.5. Module source compile: Debian standard method

The Debian standard method for creating and installing a custom module package for a custom kernel package uses module-assistant(8) and module-source packages. For example, following will build the unionfs kernel module package and installs it.

$ sudo aptitude install module-assistant
...
$ sudo aptitude install unionfs-source unionfs-tools unionfs-utils
$ sudo m-a update
$ sudo m-a prepare
$ sudo m-a auto-install unionfs
...
$ sudo apt-get autoremove

9.7.6. Kernel source compile: classic method

You can still build Linux kernel from the pristine sources with the classic method. You must take care the details of the system configuration manually.

$ cd /usr/src
$ wget http://www.kernel.org/pub/linux/kernel/v2.6/linux-<version>.tar.bz2
$ tar -xjvf linux-<version>.tar.bz2
$ cd linux-<version>
$ cp /boot/config-<version> .config
$ make menuconfig
 ...
$ make dep; make bzImage
$ make modules
# cp ./arch/x86_64/boot/bzImage /boot/vmlinuz-<version>
# make modules_install
# depmod -a
# update-initramfs -c -k <version>
  • set up bootloader

    • edit "/etc/lilo.conf" and run "/sbin/lilo", if you use lilo.
    • edit "/boot/grub/menu.lst", if you use grub.
  • reboot to new kernel with "shutdown -r now".

9.7.7. Non-free hardware drivers

Although most of hardware drivers are available as free software and as a part of the Debian system, you may need to load some non-free external drivers to support some hardwares, such as Winmodem, on your system.

Check pertinent resources:

9.8. 仮想化システム

Use of virtualized system enables us to run multiple instances of system simultaneously on a single hardware.

9.8.1. 仮想化ツール

仮想化には2つの段階があります:

  • create file system populated with required package data. Programs such as debootstrap and cdebootstrap helps this process.
  • run a program under virturized environment. Most basic method is provided by chroot.

There are several system virtualization and emulation related packages in Debian beyond simple chroot. Some packages also help you to setup such system.

表9.23 List of virtualization tools

パッケージ Popcon サイズ 説明
schroot V:1.0, I:1.6 1988 Specialized tool for executing Debian binary packages in chroot
sbuild V:0.07, I:0.3 408 Tool for building Debian binary packages from Debian sources
pbuilder V:0.4, I:2 1112 Debianパッケージの個人的なパッケージビルダー
debootstrap V:1.7, I:12 260 Bootstrap a basic Debian system (written in sh)
cdebootstrap V:0.5, I:2 112 Bootstrap a Debian system (written in C)
rootstrap V:0.03, I:0.2 156 A tool for building complete Linux filesystem images
user-mode-linux V:0.10, I:0.5 17828 User-mode Linux (kernel)
xen-tools V:0.3, I:2 996 Tools to manage debian XEN virtual server
bochs V:0.09, I:0.5 3360 Bochs: IA-32 PC emulator
qemu V:1.2, I:6 43984 Qemu: fast generic processor emulator
virtualbox-ose V:2, I:3 22944 VirtualBox: x86 virtualization solution on i386 and amd64
wine V:1.6, I:16 64 Wine: Windows API Implementation (standard suite)
dosbox V:0.6, I:3 2240 DOSBox: x86 emulator with Tandy/Herc/CGA/EGA/VGA/SVGA graphics, sound and DOS
util-vserver V:0.8, I:1.1 2388 Linux-VServer virtual private servers - user-space tools
vzctl V:0.5, I:1.0 1148 OpenVZ server virtualization solution - control tools
vzquota V:0.5, I:1.0 272 OpenVZ server virtualization solution - quota tools

See Wikipedia article Comparison of virtual machines for detail comparison of different virtualization solutions.

9.8.2. Chrootシステム

chroot(8) offers most basic way to run different instances of the GNU/Linux environment on a single system simultaneously without rebooting.

[注意] 注意

Examples below assumes both parent system and chroot system share the same CPU architecture.

You can learn how to setup and use chroot(8) by running pbuilder(8) program under script(1) as follows.

$ sudo mkdir /sid-root
$ sudo pbuilder --create --no-targz --debug --buildplace /sid-root

debootstrap(8)かdebootstrap(1)が、"sid-root"の下にsid環境のためのシステムデータをどのようにして埋め込んでいくかが分かります。

[ティップ] ティップ

These debootstrap(8) or debootstrap(1) are used to install Debian by the Debian Installer. These can also be used to install Debian to a system without using a Debian install disk, but instead from another GNU/Linux distribution.

$ sudo pbuilder --login --no-targz  --debug --buildplace /sid-root

You will see how a system shell running under sid environment is created:

  • ローカル設定のコピー("/etc/hosts"と"/etc/hostname"と"/etc/resolv.conf")
  • "/proc"ファイルシステムのマウント
  • "/dev/pts"ファイルシステムのマウント
  • "/usr/sbin/policy-rc.d"が作成される(これは常に101でプログラム終了する)
  • run "chroot /sid-root bin/bash -c 'exec -a -bash bin/bash'"
[注意] 注意

プログラムによっては機能するためにchrootの下でpbuilderが提供するより多くの親システムのファイルへのアクセスする必要があります。例えば、"/sys"や"/etc/passwd"や"/etc/group"や"/var/run/utmp"や"/var/log/wtmp"等がbindマウントもしくはコピーされる必要があるかもしれません。

[注意] 注意

"/usr/sbin/policy-rc.d"ファイルは、Debianシステム上でデーモンプログラムが自動的に起動されることを防ぎます。"/usr/share/doc/sysv-rc/README.policy-rc.d.gz"を参照下さい。

[ティップ] ティップ

The original purpose of the specialized chroot package, pbuilder is to construct a chroot system and builds a package inside the chroot. It is an ideal system to use to check that a package's build-dependencies are correct, and to be sure that unnecessary and wrong build dependencies will not exist in the resulting package.

[ティップ] ティップ

Similar schroot package may give you an idea to run i386 chroot system under amd64 parent system.

[ティップ] ティップ

By installing a system into a separate partition using the installer of other distributions and using this system for chroot(8), you can run other distributions under chroot(8).

9.8.3. Setting up login for chroot

You can run another login process on a separate virtual terminal where you can log in to the chroot system directly. Since on default Debian systems tty1 to tty6 run Linux consoles and tty7 runs the X Window System, let's set up tty8 for a chrooted console as an example. After creating a sid chroot system under "/sid-root" by following steps you learned from pbuilder(8), type from the root shell of the main system:

main # echo "8:23:respawn:/usr/sbin/chroot /sid-root /sbin/getty 38400 tty8"  >> /etc/inittab
main # init q
  • reload init

第10章 データ管理

Tools and tips for managing binary and text data on the Debian system are described.

10.1. 共有とコピーとアーカイブ

データのセキュリティとそのコントロールされた共有はいくつかの側面があります:

  • データアーカイブの作成
  • 遠隔ストレージアクセス
  • 複製
  • 変更履歴の追跡
  • データ共有のアシスト
  • 不正なファイルへのアクセスの防止
  • 不正なファイルの改変の検出

These can be realized by using some combination of:

  • the archive and compression tools,
  • the copy and synchronization tools,
  • the network file system,
  • the removable storage media,
  • セキュアシェル
  • 認証システム
  • the version control system tools, and
  • hash and cryptographic encryption tools.

10.1.1. Archive and compression tools

Here is a summary of archive and compression tools available on the Debian system:

表10.1 アーカイブと圧縮のツールのリスト。

パッケージ popcon サイズ コマンド comment extension
tar V:63, I:99 2456 tar(1) the standard archiver (de facto standard) .tar
cpio V:34, I:99 664 cpio(1) Unix System V style archiver, use with find(1) .cpio
binutils V:48, I:79 9036 ar(1) archiver for the creation of static libraries .ar
fastjar V:4, I:39 220 fastjar(1) archiver for Java (zip like) .jar
pax V:1.5, I:5 156 pax(1) new POSIX standard archiver, compromise between tar and cpio .pax
afio V:0.3, I:1.6 240 afio(1) extended cpio with per-file compression etc. .afio
par2 V:0.5, I:1.7 284 par2(1) Parity Archive Volume Set, for checking and repair of files .par2
gzip V:91, I:99 292 gzip(1), zcat(1), … GNU LZ77 compression utility (de facto standard) .gz
bzip2 V:57, I:80 132 bzip2(1), bzcat(1), … Burrows-Wheeler block-sorting compression utility with higher compression ratio than gzip(1) (slower than gzip with similar syntax) .bz2
lzma V:9, I:64 172 lzma(1) LZMA compression utility with higher compression ratio than gzip(1) (slower than gzip with similar syntax) .lzma
p7zip V:3, I:25 996 7zr(1), p7zip(1) 7-Zip file archiver with high compression ratio (LZMA compression) .7z
p7zip-full V:10, I:20 3400 7z(1), 7za(1) 7-Zip file archiver with high compression ratio (LZMA compression and others) .7z
lzop V:1.0, I:8 144 lzop(1) LZO compression utility with higher compression and decompression speed than gzip(1) (lower compression ratio than gzip with similar syntax) .lzo
zip V:9, I:61 628 zip(1) InfoZIP: DOS archive and compression tool .zip
unzip V:23, I:72 384 unzip(1) InfoZIP: DOS unarchive and decompression tool .zip

[警告] 警告

Do not set the "$TAPE" variable unless you know what to expect. It will change tar(1) behavior.

[注意] 注意

The gzipped tar(1) archive uses the file extension ".tgz" or .tar.gz".

[注意] 注意

cp(1), scp(1) and tar(1) may have some limitation for special files. cpio(1) and afio(1) are most versatile.

[注意] 注意

cpio(1) and afio(1) are designed to be used with find(1) and other commands and suitable for creating backup scripts since the file selection part of the script can be tested independently.

[注意] 注意

afio(1) compresses each file in the archive. This makes afio to be much safer for the file corruption than the globally compressed tar or cpio archives and to be the best archive engine for the backup script.

[注意] 注意

Internal structure of OpenOffice data files are ".jar" file.

10.1.2. Copy and synchronization tools

Here is a summary of simple copy and backup tools available on the Debian system:

表10.2 List of copy and synchronization tools.

パッケージ popcon サイズ tool 機能
coreutils V:91, I:99 12868 GNU cp Locally copy files and directories ("-a" for recursive).
openssh-client V:55, I:98 2084 scp Remotely copy files and directories (client). "-r" for recursive.
openssh-server V:65, I:77 812 sshd Remotely copy files and directories (remote server).
rsync V:16, I:40 640 - 1-way remote synchronization and backup.
unison V:0.9, I:3 1644 - 2-way remote synchronization and backup.
pdumpfs V:0.06, I:0.18 148 - Daily local backup using hardlinks, similar to Plan9's dumpfs.

[ティップ] ティップ

Execution of the bkup script mentioned in 「A copy script for the data backup」 with the "-gl" option under cron(8) should provide very similar functionality as pdumpfs for the static data archive.

[ティップ] ティップ

Version control system (VCS) tools in 表10.15「List of version control system tools.」 can function as the multi-way copy and synchronization tools.

10.1.3. アーカイブのための慣用句

Here are several ways to archive and unarchive the entire contents of the directory "/source".

With GNU tar(1):

$ tar cvzf archive.tar.gz /source
$ tar xvzf archive.tar.gz

With cpio(1):

$ find /source -xdev -print0 | cpio -ov --null > archive.cpio; gzip archive.cpio
$ zcat archive.cpio.gz | cpio -i

With afio(1):

$ find /source -xdev -print0 | afio -ovZ0 archive.afio
$ afio -ivZ archive.afio

10.1.4. Idioms for the copy

Here are several ways to copy the entire contents of the directory

  • from "/source" to "/dest", and
  • from "/source" at local to "/dest" at "user@host.dom".

With GNU cp(1) and openSSH scp(1):

# cp -a /source /dest
# scp -pr /source user@host.dom:/dest

With GNU tar(1):

# (cd /source && tar cf - . ) | (cd /dest && tar xvfp - )
# (cd /source && tar cf - . ) | ssh user@host.dom '(cd /dest && tar xvfp - )'

With cpio(1):

# cd /source; find . -print0 | cpio -pvdm --null --sparse /dest

With afio(1):

# cd /source; find . -print0 | afio -pv0a /dest

scp(1) can even copy files between remote hosts:

# scp -pr user1@host1.dom:/source user2@host2.dom:/dest

10.1.5. Idioms for the selection of files

find(1) is used to select files for archive and copy commands (see 「アーカイブのための慣用句」 and 「Idioms for the copy」) or for xargs(1) (see 「Repeating a command looping over files」). This can be enhanced by using its command arguments.

Basic syntax of find(1) can be summarized as:

  • Its conditional arguments are evaluated from left to right.
  • This evaluation stops once its outcome is determined.
  • "Logical OR" (specified by "-o" between conditionals) has lower precedence than "logical AND" (specified by "-a" or nothing between conditionals).
  • "Logical NOT" (specified by "!" before a conditional) has higher precedence than "logical AND".
  • "-prune" always returns logical TRUE and, if it is a directory, searching of file is stopped beyond this point.
  • "-name" matches the base of the filename with shell glob (see 「シェルグロブ」) but it also matches its initial "." with metacharacters such as "*" and "?". (New POSIX feature)
  • "-regex" matches the full path with emacs style BRE (see 「正規表現」) as default.
  • "-size" matches the file based on the file size (value precedented with "+" for larger, precedented with "-" for smaller)
  • "-newer" matches the file newer than the one specified in its argument.
  • "-print0" always returns logical TRUE and print the full filename (null terminated) on the standard output.

find(1) is often used with an idiomatic style. For example:

# find /path/to \
    -xdev -regextype posix-extended \
    -type f -regex ".*\.afio|.*~" -prune -o \
    -type d -regex ".*/\.git" -prune -o \
    -type f -size +99M -prune -o \
    -type f -newer /path/to/timestamp -print0

This means to do following actions:

  • search all files starting from "/path/to"
  • globally limit its search within its starting filesystem and uses ERE (see 「正規表現」) instead,
  • exclude files matching regex of ".*\.afio" or ".*~" from search by stop processing,
  • exclude directories matching regex of ".*/\.git" from search by stop processing,
  • exclude files larger than 99 Megabytes (units of 1048576 bytes) from search by stop processing, and
  • print filenames which satisfy above search conditions and newer than "/path/to/timestamp".

Please note the idiomatic use of "-prune -o" to exclude files in the above example.

[注意] 注意

For non-Debian Unix-like system, some options may not be supported for find(1). In such a case, please consider to adjust matching methods and replace "-print0" with "-print". You may need to adjust related commands too.

10.1.6. Backup and recovery

We all know that computers fail sometime or human errors cause system and data damages. Backup and recovery operations are the essential part of successful system administration. All possible failure modes will hit you some day.

There are 3 key factors which determine actual backup and recovery policy:

  1. Knowing what to backup and recover.

    • Data files directly created by you: data in "~/"
    • Data files created by applications used by you: data in "/var/" (except "/var/cache/", "/var/run/", and "/var/tmp/").
    • System configuration files: data in "/etc/"
    • Local softwares: data in "/usr/local/" or "/opt/"
    • System installation information: a memo in plain text on key steps (partition, …).
    • Proven set of data: experimenting with recovery operations in advance.
  2. Knowing how to backup and recover.

    • Secure storage of data: protection from overwrite and system failure.
    • Frequent backup: scheduled backup.
    • Redundant backup: data mirroring.
    • Fool proof process: easy single command backup.
  3. Assessing risks and costs involved.

    • Failure mode and their possibility.
    • Value of data when lost.
    • Required resources for backup: human, hardware, software, …

As for secure storage of data, data should be at least on different disk partitions preferably on different disks and machines to withstand the filesystem corruption. Important data are best stored on a write-once media such as CD/DVD-R to prevent overwrite accidents. (See 「バイナリデータ」 for how to write to the storage media from the shell commandline. GNOME desktop GUI environment gives you easy access via menu: "Places→CD/DVD Creator".)

[注意] 注意

You may wish to stop some application daemons such as MTA (see 「MTA」) while backing up data.

[注意] 注意

You should pay extra care to the backup and restoration of identity related data files such as "/etc/ssh/ssh_host_dsa_key", "/etc/ssh/ssh_host_rsa_key", "~/.gnupg/*", "~/.ssh/*", "/etc/passwd", "/etc/shadow", "/etc/fetchmailrc", "popularity-contest.conf", "/etc/ppp/pap-secrets", and "/etc/exim4/passwd.client". Some of these data can not be regenerated by entering the same input string to the system.

[注意] 注意

If you run a cron job as a user process, you need to restart it after the system restoration. See 「Schedule tasks regularly」 for cron(8) and crontab(1).

10.1.7. Backup utility suites

Here is a select list of notable backup utility suites available on the Debian system:

表10.3 バックアップスイートのユーティリティのリスト。

パッケージ popcon サイズ 説明
rdiff-backup V:1.3, I:3 764 (remote) incremental backup
dump V:0.4, I:1.6 620 4.4BSD dump(8) and restore(8) for ext2/ext3 filesystems
xfsdump V:0.3, I:1.8 684 Dump and restore with xfsdump(8) and xfsrestore(8) for XFS filesystem on GNU/Linux and IRIX
backupninja V:0.4, I:0.5 408 lightweight, extensible meta-backup system
mondo V:0.13, I:0.8 1172 Mondo Rescue: disaster recovery backup suite
sbackup V:0.09, I:0.2 488 Simple Backup Suite for GNOME desktop
keep V:0.2, I:0.5 1196 backup system for KDE
bacula-common V:1.1, I:2 832 Bacula: network backup, recovery and verification - common support files
bacula-client I:0.9 60 Bacula: network backup, recovery and verification - client meta-package
bacula-console V:0.3, I:1.2 340 Bacula: network backup, recovery and verification - text console
bacula-server I:0.6 60 Bacula: network backup, recovery and verification - server meta-package
amanda-common V:0.4, I:0.9 3120 Amanda: Advanced Maryland Automatic Network Disk Archiver (Libs)
amanda-client V:0.3, I:0.8 560 Amanda: Advanced Maryland Automatic Network Disk Archiver (Client)
amanda-server V:0.14, I:0.3 1264 Amanda: Advanced Maryland Automatic Network Disk Archiver (Server)
cdrw-taper V:0.00, I:0.06 172 taper replacement for Amanda to support backups to CD-RW or DVD+RW
backuppc V:0.7, I:0.8 2082 BackupPC is a high-performance, enterprise-grade system for backing up PCs (disk based)
backup-manager V:0.4, I:0.5 640 command-line backup tool
backup2l V:0.2, I:0.3 140 low-maintenance backup/restore tool for mountable media (disk based)
faubackup V:0.2, I:0.2 156 backup system using a filesystem for storage (disk based)

Basic tools such as ones descrived in 「Archive and compression tools」 and 「Copy and synchronization tools」 are used to facilitate system backup. In addition to these, rdiff-backup and dump packages also facilitate system backup.

  • The rdiff-backup package facilitates backs up of one directory to another, possibly over a network.
  • The dump package facilitates restoration of complete system by archiving filesystems themselves. This can perform incremental backup of filesystems efficiently. See files in "/usr/share/doc/dump/" and "Is dump really deprecated?".
  • The xfsdump package works similarly to the dump package.

There are programs for backup using these basic tools as their backends.

  • Mondo Rescue is a backup system to facilitate restoration of complete system from backup CD/DVD etc. without going through normal system installation processes.
  • sbackup and keep packages provide easy GUI frontend to regular backups of user data for desktop users. An equivalent function can be realized by a simple script (「An example script for the system backup」) and cron(8).
  • Bacula, Amanda, and BackupPC are full featured backup suite utilities which are focused on regular backups over network.

10.1.8. An example script for the system backup

For a personal Debian desktop system running unstable suite, I only need to protect personal and critical data. I reinstall system once a year anyway. Thus I see no reason to backup the whole system or to install a full featured backup utility.

I use a simple script to make a backup archive and burn it into CD/DVD using GUI. Here is an example script for this.

#!/bin/sh -e
# Copyright (C) 2007-2008 Osamu Aoki <osamu@debian.org>, Public Domain
BUUID=1000; USER=osamu # UID and name of a user who accesses backup files
BUDIR="/var/backups"
XDIR0=".+/Mail|.+/Desktop"
XDIR1=".+/\.thumbnails|.+/\.?Trash|.+/\.?[cC]ache|.+/\.gvfs|.+/sessions"
XDIR2=".+/CVS|.+/\.git|.+/\.svn|.+/Downloads|.+/Archive|.+/Checkout|.+/tmp"
XSFX=".+\.iso|.+\.tgz|.+\.tar\.gz|.+\.tar\.bz2|.+\.afio|.+\.tmp|.+\.swp|.+~"
SIZE="+99M"
DATE=$(date --utc +"%Y%m%d-%H%M")
[ -d "$BUDIR" ] || mkdir -p "BUDIR"
umask 077
dpkg --get-selections \* > /var/lib/dpkg/dpkg-selections.list
debconf-get-selections > /var/cache/debconf/debconf-selections

{
find /etc /usr/local /opt /var/lib/dpkg/dpkg-selections.list \
     /var/cache/debconf/debconf-selections -xdev -print0
find /home/$USER /root -xdev -regextype posix-extended \
  -type d -regex "$XDIR0|$XDIR1" -prune -o -type f -regex "$XSFX" -prune -o \
  -type f -size  "$SIZE" -prune -o -print0
find /home/$USER/Mail/Inbox /home/$USER/Mail/Outbox -print0
find /home/$USER/Desktop  -xdev -regextype posix-extended \
  -type d -regex "$XDIR2" -prune -o -type f -regex "$XSFX" -prune -o \
  -type f -size  "$SIZE" -prune -o -print0
} | cpio -ov --null -O $BUDIR/BU$DATE.cpio
chown $BUUID $BUDIR/BU$DATE.cpio
touch $BUDIR/backup.stamp

This is meant to be a script example executed from root:

[ティップ] ティップ

You can recover debconf configuration data with "debconf-set-selections debconf-selections" and dpkg selection data with "dpkg --set-selection <dpkg-selections.list".

10.1.9. A copy script for the data backup

For the set of data under a directory tree, the copy with "cp -a" provides the normal backup.

For the set of large non-overwritten static data under a directory tree such as the data under the "/var/cache/apt/packages/" directory, hardlinks with "cp -al" provide an alternative to the normal backup with efficient use of the disk space.

Here is a copy script, which I named as bkup, for the data backup. This script copies all (non-VCS) files under the current directory to the dated directory on the parent directory or on a remote host.

#!/bin/sh -e
# Copyright (C) 2007-2008 Osamu Aoki <osamu@debian.org>, Public Domain
function fdot(){ find . -type d \( -iname ".?*" -o -iname "CVS" \) -prune -o -print0;}
function fall(){ find . -print0;}
function mkdircd(){ mkdir -p "$1";chmod 700 "$1";cd "$1">/dev/null;}
FIND="fdot";OPT="-a";MODE="CPIOP";HOST="localhost";EXTP="$(hostname -f)"
BKUP="$(basename $(pwd)).bkup";TIME="$(date  +%Y%m%d-%H%M%S)";BU="$BKUP/$TIME"
while getopts gcCsStrlLaAxe:h:T f; do case $f in
g)  MODE="GNUCP";; # cp (GNU)
c)  MODE="CPIOP";; # cpio -p
C)  MODE="CPIOI";; # cpio -i
s)  MODE="CPIOSSH";; # cpio/ssh
S)  MODE="AFIOSSH";; # afio/ssh
t)  MODE="TARSSH";; # tar/ssh
r)  MODE="RSYNCSSH";; # rsync/ssh
l)  OPT="-alv";; # hardlink (GNU cp)
L)  OPT="-av";;  # copy (GNU cp)
a)  FIND="fall";; # find all
A)  FIND="fdot";; # find non CVS/ .???/
x)  set -x;; # trace
e)  EXTP="${OPTARG}";; # hostname -f
h)  HOST="${OPTARG}";; # user@remotehost.example.com
T)  MODE="TEST";; # test find mode
\?) echo "use -x for trace."
esac; done
shift $(expr $OPTIND - 1)
if [ $# -gt 0 ]; then
  for x in $@; do cp $OPT $x $x.$TIME; done
elif [ $MODE = GNUCP ]; then
  mkdir -p "../$BU";chmod 700 "../$BU";cp $OPT . "../$BU/"
elif [ $MODE = CPIOP ]; then
  mkdir -p "../$BU";chmod 700 "../$BU"
  $FIND|cpio --null --sparse -pvd ../$BU
elif [ $MODE = CPIOI ]; then
  $FIND|cpio -ov --null | ( mkdircd "../$BU"&&cpio -i )
elif [ $MODE = CPIOSSH ]; then
  $FIND|cpio -ov --null|ssh -C $HOST "( mkdircd \"$EXTP/$BU\"&&cpio -i )"
elif [ $MODE = AFIOSSH ]; then
  $FIND|afio -ov -0 -|ssh -C $HOST "( mkdircd \"$EXTP/$BU\"&&afio -i - )"
elif [ $MODE = TARSSH ]; then
  (tar cvf - . )|ssh -C $HOST "( mkdircd \"$EXTP/$BU\"&& tar xvfp - )"
elif [ $MODE = RSYNCSSH ]; then
  rsync -rlpt ./ "${HOST}:${EXTP}-${BKUP}-${TIME}"
else
  echo "Any other idea to backup?"
  $FIND |xargs -0 -n 1 echo
fi

This is meant to be command examples. Please read script and test it by yourself.

[ティップ] ティップ

I keep this bkup in my "/usr/local/bin/" directory. I issue this bkup command without any option in the working directory whenever I need a temporary snapshot backup.

[ティップ] ティップ

For making snapshot history of a source file tree or a configuration file tree, it is easier and space efficient to use git(7) (see 「Git for recording configuration history」).

10.1.10. Removable mass storage device

Removable mass storage devices may be any one of

These removable mass storage devices can be automatically mounted as a user under modern desktop environment, such as GNOME using gnome-mount(1).

  • Mount point under GNOME is chosen as "/media/<disk_label>" which can be customized

    • by mlabel(1) for FAT filesystem,
    • by genisoimage(1) with "-V" option for ISO9660 filesystem, and
    • by tune2fs(1) with "-L" option for ext2/ext3 filesystem.
  • The choice of encoding may need to be provided as mount option (see 「Filename encoding」).
  • The ownership of the mounted filesystem may need to be adjusted for use by the normal user.
[注意] 注意

Automounting under modern desktop environment happens only when those removable media devices are not listed in "/etc/fstab".

[ティップ] ティップ

When providing wrong mount option causes problem, erase its corresponding setting under "/system/storage/" via gconf-editor(1).

表10.4 List of packages which permit normal users to mount removable devices without a matching "/etc/fstab" entry.

パッケージ popcon サイズ 説明
gnome-mount V:23, I:38 968 wrapper for (un)mounting and ejecting storage devices (used by GNOME)
pmount V:12, I:37 868 mount removable devices as normal user (used by KDE)
cryptmount V:0.09, I:0.5 304 Management and user-mode mounting of encrypted file systems
usbmount I:1.9 108 automatically mount and unmount USB mass storage devices

When sharing data with other system via removable mass storage device, you should format it with common filesystem supported by both systems. Here is a list of filesystem choices.

表10.5 List of filesystem choices for removable storage devices with typical usage scenarios.

ファイルシステム typical usage scenario
FAT12 Cross platform sharing of data on the floppy disk. (⇐32MiB)
FAT16 Cross platform sharing of data on the small harddisk like device. (⇐2GiB)
FAT32 Cross platform sharing of data on the large harddisk like device. (⇐8TiB, supported by newer than MS Windows95 OSR2)
NTFS Cross platform sharing of data on the large harddisk like device. (supported natively on MS Windows NT and later version, and supported by NTFS-3G via FUSE on Linux)
ISO9660 Cross platform sharing of static data on CD-R and DVD+/-R
UDF Incremental data writing on CD-R and DVD+/-R (new)
MINIXファイルシステム Space efficient unix file data storage on the floppy disk.
ext2ファイルシステム Sharing of data on the harddisk like device with older Linux systems.
ext3ファイルシステム Sharing of data on the harddisk like device with current Linux systems. (Journaling file system)

[ティップ] ティップ

See 「Removable disk encryption with dm-crypt/LUKS」 for cross platform sharing of data using device level encryption.

The FAT filesystem is supported by almost all modern operating systems and is quite useful for the data exchange purpose via removable harddisk like media (.

When formatting removable harddisk like devices for cross platform sharing of data with the FAT filesystem, the following should be safe choices:

  • Partitioning them with fdisk(8), cfdisk(8) or parted(8) (see 「パーティション設定」) into a single primary partition and to mark it as:

    • type-"6" for FAT16 for media smaller than 2GB or
    • type-"c" for FAT32 (LBA) for larger media.
  • Formatting the primary partition with mkfs.vfat(8)

    • with just its device name, e.g. "/dev/sda1" for FAT16, or
    • with the explicit option and its device name, e.g. "-F 32 /dev/sda1" for FAT32.

When using the FAT or ISO9660 filesystems for sharing data, the following should be the safe considerations:

  • Archiving files into an archive file first using tar(1), cpio(1), or afio(1) to retain the long filename, the symbolic link, the original Unix file permission and the owner information.
  • Splitting the archive file size into less than 2 GiB chunks with the split(1) command to protect it from the file size limitation.
  • Encrypting the archive file to secure its contents from the unauthorized access.
[注意] 注意

For FAT filesystems by its design, the maximum file size is (2^32 - 1) bytes = (4GiB - 1 byte). For some applications on the older 32 bit OS, the maximum file size was even smaller (2^31 - 1) bytes = (42GiB - 1 byte). Debian does not suffer the latter problem.

[注意] 注意

Microsoft itself does not recommend to use FAT for drives or partitions of over 200 MB. Microsoft highlights its short comings such as inefficient disk space usage in their "Overview of FAT, HPFS, and NTFS File Systems". Of course for the Linux, we should normally use the ext3 filesystem.

[ティップ] ティップ

For more on filesystems and accessing filesystems, please read "Filesystems HOWTO".

10.1.11. Sharing data via network

When sharing data with other system via network, you should use common service. Here are some hints.

表10.6 List of the network service to chose with the typical usage scenario.

network service typical usage scenario
SMB/CIFS network mounted filesystem with Samba Sharing files via "Microsoft Windows Network". See smb.conf(5) and The Official Samba 3.2.x HOWTO and Reference Guide or the samba-doc package.
NFS network mounted filesystem with the Linux kernel Sharing files via "Unix/Linux Network". See exports(5) and Linux NFS-HOWTO.
HTTPサービス Sharing file between the web server/client.
HTTPSサービス Sharing file between the web server/client with encrypted Secure Sockets Layer (SSL) or Transport Layer Security (TLS).
FTPサービス Sharing file between the FTP server/client.

Although these filesystems mounted over network or file transfer methods over network are quite convenient for sharing data, these may be insecure. Their network connection must be secured by:

10.1.12. アーカイブ媒体

When choosing computer data storage media for important data archive, you should be careful about their limitations. For small personal data back up, I use CD-R and DVD-R by the brand name company and store in a cool, dry, clean environment. (Tape archive media seem to be popular for professional use.)

[注意] 注意

A fire-resistant safe are usually meant for paper documents. Most of the computer data storage media have less temperature tolerance than paper. I usually rely on multiple secure encrypted copies stored in multiple secure locations.

Optimistic storage life of archive media seen on the net (mostly from vendor info):

  • 100+ years : acid free paper with ink
  • 100 years : optical storage (CD/DVD, CD/DVD-R)
  • 30 years : magnetic storage (tape, floppy)
  • 20 years : phase change optical storage (CD-RW) These do not count on the mechanical failures due to handling etc.

Optimistic write cycle of archive media seen on the net (mostly from vendor info):

  • 250,000+ cycles : Harddisk drive
  • 10,000+ cycles : Flash memory
  • 1,000 cycles : CD/DVD-RW
  • 1 cycles : CD/DVD-R, paper
[注意] 注意

Figures of storage life and write cycle here should not be used for decisions on any critical data storage. Please consult the specific product information provided by the manufacture.

[ティップ] ティップ

Since CD/DVD-R and paper have only 1 write cycle, they inherently prevent accidental data loss by overwriting. This is advantage!

[ティップ] ティップ

If you need fast and frequent backup of large amount of data, a harddisk on a remote host linked by a fast network connection, may be the only realistic option.

10.2. バイナリデータ

Here, we discuss direct manipulation of the binary data on storage media. See 「Data storage tips」, too.

10.2.1. Make the disk image file

The disk image file, "disk.img", of an unmounted device, e.g., the second SCSI drive "/dev/sdb", can be made using cp(1) or dd(1):

# cp /dev/sdb disk.img
# dd if=/dev/sdb of=disk.img

The disk image of the traditional PC's master boot record (MBR) (see 「パーティション設定」) which reside on the first sector on the primary IDE disk partial disk can be made by using dd(1):

# dd if=/dev/hda of=mbr.img bs=512 count=1
# dd if=/dev/hda of=mbr-nopart.img bs=446 count=1
# dd if=/dev/hda of=mbr-part.img skip=446 bs=1 count=66
  • "mbr.img": the MBR with the partition table.
  • "mbr-nopart.img": the MBR without the partition table.
  • "part.img": the partition table of the MBR only..

If you have a SCSI device (including the new serial ATA drive) as the boot disk, substitute "/dev/hda" with "/dev/sda".

If you are making an image of a disk partition of the original disk, substitute "/dev/hda" with "/dev/hda1" etc.

10.2.2. Writing directly to the disk

The disk image file, "disk.img" can be written to an unmounted device, e.g., the second SCSI drive "/dev/sdb" with matching size, by dd(1):

# dd if=disk.img of=/dev/sdb

Similarly, the disk partition image file, "disk.img" can be written to an unmounted partition, e.g., the first partition of the second SCSI drive "/dev/sdb1" with matching size, by dd(1):

# dd if=disk.img of=/dev/sdb1

10.2.3. View and edit binary data

The most basic viewing method of binary data is to use "od -t x1" command.

表10.7 バイナリデータを閲覧や編集するパッケージのリスト。

パッケージ popcon サイズ 説明
coreutils V:91, I:99 12868 This basic package has od(1) to dump files in octal and other formats.
bsdmainutils V:65, I:99 644 This utility package has hd(1) to dump files in ASCII, decimal, hexadecimal, and octal formats.
hexedit V:0.3, I:1.9 108 View and edit files in hexadecimal or in ASCII
bless V:0.07, I:0.3 1240 Full featured hexadecimal editor (GNOME)
khexedit V:1.6, I:11 NOT_FOUND Full featured hexadecimal editor (KDE).
okteta V:0.3, I:3 1252 Full featured hexadecimal editor (KDE4).
ncurses-hexedit V:0.08, I:0.6 192 Edit files/disks in HEX, ASCII and EBCDIC
lde V:0.04, I:0.5 992 Linux Disk Editor
beav V:0.04, I:0.3 164 Binary editor and viewer for HEX, ASCII, EBCDIC, OCTAL, DECIMAL, and BINARY formats.
hex V:0.01, I:0.11 84 Hexadecimal dumping tool for Japanese

[ティップ] ティップ

HEX is used as an acronym for hexadecimal format.

10.2.4. Mount the disk image file

If "disk.img" contains an image of the disk contents and the original disk had a disk configuration which gives xxxx = (bytes/sector) * (sectors/cylinder), then the following will mount it to "/mnt":

# mount -o loop,offset=xxxx disk.img /mnt

Note that most hard disks have 512 bytes/sector. This offset is to skip MBR of the hard disk. You can skip offset in the above example, if "disk.img" contains

  • only an image of a disk partition of the original hard disk, or
  • only an image of the original floppy disk.

10.2.5. Manipulating files without mounting disk

There are tools to read and write files without mounting disk.

表10.8 List of packages to manipulate files without mounting.

パッケージ popcon サイズ 説明
mtools V:5, I:57 412 Utilities for MSDOS files without mounting them.
hfsutils V:0.18, I:1.8 236 Utilities for HFS and HFS+ files without mounting them.

10.2.6. データファイルの回復と事故の証拠解析

データファイルの回復と事故の証拠解析のツールがあります。

表10.9 データファイルの回復と事故の証拠解析のリスト。

パッケージ popcon サイズ 説明
testdisk V:0.3, I:3 4616 Utilities for partition scan and disk recovery.
magicrescue V:0.09, I:0.5 336 Recovers files by looking for magic bytes.
scalpel V:0.03, I:0.2 124 A Frugal, High Performance File Carver.
recover V:0.09, I:0.9 104 Undelete files on ext2 partitions.
e2undel V:0.08, I:0.6 240 Undelete utility for the ext2 file system.
ext3grep V:0.07, I:0.5 300 Tool to help recover deleted files on ext3 filesystems.
scrounge-ntfs V:0.03, I:0.4 44 Data recovery program for NTFS filesystems.
gzrt V:0.02, I:0.17 68 Gzip recovery toolkit.
sleuthkit V:0.14, I:0.6 4072 Tools for forensics analysis. (Sleuthkit)
autopsy V:0.07, I:0.4 1372 Graphical interface to SleuthKit.
foremost V:0.09, I:0.6 140 Forensics application to recover data.
tct V:0.04, I:0.2 548 Forensics related utilities.
dcfldd V:0.03, I:0.15 124 Enhanced version of dd for forensics and security.
rdd V:0.02, I:0.13 200 A forensic copy program.

10.2.7. Make the ISO9660 image file

The ISO9660 image file, "cd.iso", from the source directory tree at "source_directory" can be made using genisoimage(1):

#  genisoimage -r -J -T -V volume_id -o cd.iso source_directory

Similary, the bootable ISO9660 image file, "cdboot.iso", can be made from debian-installer like directory tree at "source_directory":

#  genisoimage -r -o cdboot.iso -V volume_id \
   -b isolinux/isolinux.bin -c isolinux/boot.cat \
   -no-emul-boot -boot-load-size 4 -boot-info-table source_directory

Here Isolinux boot loader (see 「2段目: ブートローダ」) is used for booting.

To make the disk image directly from the CD-ROM device using cp(1) or dd(1) has a few problems. The first run of dd(1) may cause an error message and may yield a shorter disk image with a lost tail-end. The second run of dd(1) may yield a larger disk image with garbage data attached at the end on some systems if the data size is not specified. Only the second run of dd(1) with the correct data size specified, and without ejecting the CD after an error message, seems to avoid these problems. If for example the image size displayed by df(1) is 46301184 blocks, use the following command twice to get the right image (this is my empirical information):

# dd if=/dev/cdrom of=cd.iso bs=2048 count=$((46301184/2))

10.2.8. Writing directly to the CD/DVD-R/RW

[ティップ] ティップ

DVD is only a large CD to wodim(1).

You can find a usable device by:

# wodim --devices

Then the blank CD-R is inserted to the device, and the ISO9660 image file, "cd.iso" is written to this device, e.g., "/dev/hda", by wodim(1):

# wodim -v -eject dev=/dev/hda cd.iso

If CD-RW is used instead of CD-R, do this instead:

# wodim -v -eject blank=fast dev=/dev/hda cd.iso
[ティップ] ティップ

If your desktop system mounts CD automatically, unmount it by "sudo unmount /dev/hda" before using wodim(1).

10.2.9. Mount the ISO9660 image file

If "cd.iso" contains an ISO9660 image, then the following will manually mount it to "/cdrom":

# mount -t iso9660 -o ro,loop cd.iso /cdrom
[ティップ] ティップ

Modern desktop system mounts removable media automatically (see 「Removable mass storage device」).

10.2.10. Split a large file into small files

When a data is too big to backup, you can back up a large file into, e.g. 2000MiB chunks and merge those files into a large file.

$ split -b 2000m large_file
$ cat x* >large_file
[注意] 注意

Please make sure you do not have any file starting with "x" to avoid the file name crash.

10.2.11. Clear file contents

In order to clear the contents of a file such as a log file, do not use rm(1) to delete the file and then create a new empty file, because the file may still be accessed in the interval between commands. The following is the safe way to clear the contents of the file.

$ :>file_to_be_cleared

10.2.12. Dummy files

次のコマンドはダミーや空のファイルを作成します。

$ dd if=/dev/zero    of=5kb.file bs=1k count=5
$ dd if=/dev/urandom of=7mb.file bs=1M count=7
$ touch zero.file
$ : > alwayszero.file
  • "5kb.file" is 5KB of zeros.
  • "7mb.file" is 7MB of random data.
  • "zero.file" is 0 byte file (if file exists, the file contents are kept while updating mtime.)
  • "alwayszero.file" is always 0 byte file (if file exists, the file contents are not kept while updating mtime.)

10.2.13. Erase entire harddisk

There are several ways to completely erase data from an entire harddisk-like device, e.g., USB memory stick at "/dev/sda".

[注意] 注意

Check your USB memory stick location with mount(8) first before executing commands here. The device pointed by "/dev/sda" may be SCSI harddisk or serial-ATA harddisk where your entire system resides.

  • Erase all by resetting data to 0:
dd if=/dev/zero of=/dev/sda
  • Erase all by overwriting random data:
# dd if=/dev/urandom of=/dev/sda
  • Erase all by overwriting random data very efficiently (fast):
# shred -v -n 1 /dev/sda

Since dd(1) is available from the shell of many bootable Linux CDs such as Debian installer CD, you can erase your installed system completely by running an erase command from such media on the system hard disk, e.g., "/dev/hda", "/dev/sda", etc.

10.2.14. Undelete deleted but still open file

Even if you have accidentally deleted a file, as long as that file is still being used by some application (read or write mode), it is possible to recover such a file.

  • On one terminal:
$ echo foo > bar
$ less bar
  • Then on another terminal:
$ ps aux | grep ' less[ ]'
bozo    4775  0.0  0.0  92200   884 pts/8    S+   00:18   0:00 less bar
$ rm bar
$ ls -l /proc/4775/fd | grep bar
lr-x------ 1 bozo bozo 64 2008-05-09 00:19 4 -> /home/bozo/bar (deleted)
$ cat /proc/4775/fd/4 >bar
$ ls -l
-rw-r--r-- 1 bozo bozo 4 2008-05-09 00:25 bar
$ cat bar
foo
  • Alternatively, when you have the lsof package installed, on another terminal:
$ ls -li bar
2228329 -rw-r--r-- 1 bozo bozo 4 2008-05-11 11:02 bar
$ lsof |grep bar|grep less
less 4775 bozo 4r REG 8,3 4 2228329 /home/bozo/bar
$ rm bar
$ lsof |grep bar|grep less
less 4775 bozo 4r REG 8,3 4 2228329 /home/bozo/bar (deleted)
$ cat /proc/4775/fd/4 >bar
$ ls -li bar
2228302 -rw-r--r-- 1 bozo bozo 4 2008-05-11 11:05 bar
$ cat bar
foo

10.2.15. Searching all hardlinks

Files with hardlinks can be identified by "ls -li", e.g.:

$ ls -li
total 0
2738405 -rw-r--r-- 1 root root 0 2008-09-15 20:21 bar
2738404 -rw-r--r-- 2 root root 0 2008-09-15 20:21 baz
2738404 -rw-r--r-- 2 root root 0 2008-09-15 20:21 foo

Both "baz" and "foo" have link count of "2" (>1) showing them to have hardlinks. Their inode numbers are common "2738404". This means they are the same hardlinked file. If you do not happen to find all hardlinked files by chance, you can search it by the inode, e.g., "2738404":

# find /path/to/mount/point -xdev -inum 2738404

10.2.16. Invisible disk space consumption

All deleted but open files consumes disk space although they are not visible from normal du(1). They can be listed with their size by:

# lsof -s -X / |grep deleted

10.3. Data security infrastructure

The data security infrastructure is provided by the combination of data encryption tool, message digest tool, and signature tool.

表10.10 データセキュリティインフラツールのリスト。

パッケージ popcon サイズ 機能
gnupg V:39, I:99 5072 GNU privacy guard - OpenPGP encryption and signing tool. gpg(1)
gnupg-doc I:1.5 4124 GNU Privacy Guard documentation
gpgv V:61, I:98 392 GNU privacy guard - signature verification tool
cryptsetup V:3, I:4 904 Utilities for dm-crypto block device encryption supporting LUKS
ecryptfs-utils V:0.09, I:0.2 444 Utilities for ecryptfs stacked filesystem encryption
coreutils V:91, I:99 12868 The md5sum command computes and checks MD5 message digest
coreutils V:91, I:99 12868 The sha1sum command computes and checks SHA1 message digest
openssl V:29, I:90 2360 The "openssl dgst" command computes message digest (OpenSSL). dgst(1ssl)

See 「Data encryption tips」 on dm-crypto and ecryptfs which implement automatic data encryption infrastructure via Linux kernel modules.

10.3.1. Gnupgのためのキー管理

Here are GNU Privacy Guard commands for the basic key management:

表10.11 List of GNU Privacy Guard commands for the key management

コマンド 説明
gpg --gen-key generate a new key
gpg --gen-revoke my_user_ID generate revoke key for my_user_ID
gpg --edit-key user_ID edit key interactively, "help" for help
gpg -o file --exports export all keys to file
gpg --imports file import all keys from file
gpg --send-keys user_ID send key of user_ID to keyserver
gpg --recv-keys user_ID recv. key of user_ID from keyserver
gpg --list-keys user_ID list keys of user_ID
gpg --list-sigs user_ID list sig. of user_ID
gpg --check-sigs user_ID check sig. of user_ID
gpg --fingerprint user_ID check fingerprint of "user_ID"
gpg --refresh-keys update local keyring

Here is the meaning of trust code:

表10.12 信頼性コードの意味のリスト。

コード 信頼性
- No owner trust assigned / not yet calculated.
e Trust calculation has failed.
q Not enough information for calculation.
n Never trust this key.
m Marginally trusted.
f Fully trusted.
u Ultimately trusted.

The following will upload my key "A8061F32" to the popular keyserver "hkp://subkeys.pgp.net":

$ gpg --keyserver hkp://subkeys.pgp.net --send-keys A8061F32

A good default keyserver set up in "~/.gnupg/gpg.conf" (or old location "~/.gnupg/options") contains:

keyserver hkp://subkeys.pgp.net

The following will obtain unknown keys from the keyserver:

$ gpg --list-sigs | \
  sed -n '/^sig.*\[User ID not found\]/s/^sig..........\(\w\w*\)\W.*/\1/p' |\
  sort | uniq | xargs gpg --recv-keys

There was a bug in OpenPGP Public Key Server (pre version 0.9.6) which corrupted key with more than 2 sub-keys. The newer gnupg (>1.2.1-2) package can handle these corrupted subkeys. See gpg(1) under "--repair-pks-subkey-bug" option.

10.3.2. Using GnuPG with files

File handling:

表10.13 List of gnu privacy guard commands on files

コマンド 説明
gpg -a -s file sign file into ascii armored file.asc
gpg --armor --sign file , ,
gpg --clearsign file clear-sign message
gpg --clearsign --not-dash-escaped patchfile clear-sign patchfile
gpg --verify file verify clear-signed file
gpg -o file.sig -b file create detached signature
gpg -o file.sig --detach-sig file , ,
gpg --verify file.sig file verify file with file.sig
gpg -o crypt_file.gpg -r name -e file public-key encryption intended for name from file to binary crypt_file.gpg
gpg -o crypt_file.gpg --recipient name --encrypt file , ,
gpg -o crypt_file.asc -a -r name -e file public-key encryption intended for name from file to ASCII armored crypt_file.asc
gpg -o crypt_file.gpg -c file symmetric encryption from file to crypt_file.gpg
gpg -o crypt_file.gpg --symmetric file , ,
gpg -o crypt_file.asc -a -c file symmetric encryption intended for name from file to ASCII armored crypt_file.asc
gpg -o file -d crypt_file.gpg -r name 暗号解読
gpg -o file --decrypt crypt_file.gpg , ,

10.3.3. Using GnuPG with Mutt

Add the following to "~/.muttrc" to keep a slow GnuPG from automatically starting, while allowing it to be used by typing "S" at the index menu.

macro index S ":toggle pgp_verify_sig\n"
set pgp_verify_sig=no

10.3.4. Using GnuPG with Vim

The gnupg plugin let you run GnuPG transparently for files with extension ".gpg", ".asc", and ".ppg".

# aptitude install vim-scripts vim-addon-manager
$ vim-addons install gnupg

10.3.5. The MD5 sum

md5sum(1) provides utility to make a digest file using the method in rfc1321 and verifying each file with it.

$ md5sum foo bar >baz.md5
$ cat baz.md5
d3b07384d113edec49eaa6238ad5ff00  foo
c157a79031e1c40f85931829bc5fc552  bar
$ md5sum -c baz.md5
foo: OK
bar: OK
[注意] 注意

The computation for the MD5 sum is less CPU intensive than the one for the cryptographic signature by GNU Privacy Guard (GnuPG). Usually, only the top level digest file is cryptographically signed to ensure data integrity.

10.4. Source code merge tools

There are many merge tools for the source code. Following commands caught my eyes.:

表10.14 ソースコードマージツールのリスト。

コマンド パッケージ popcon サイズ 説明
diff(1) diff V:90, I:99 764 This compares files line by line.
diff3(1) diff V:90, I:99 764 This compares and merges three files line by line.
vimdiff(1) vim V:14, I:30 1740 This compares 2 files side by side in vim.
patch(1) patch V:11, I:93 204 This applies a diff file to an original.
dpatch(1) dpatch V:2, I:15 344 This manage series of patches for Debian package.
diffstat(1) diffstat V:2, I:14 84 This produces a histogram of changes by the diff.
combinediff(1) patchutils V:2, I:15 292 This creates a cumulative patch from two incremental patches.
dehtmldiff(1) patchutils V:2, I:15 292 This extracts a diff from an HTML page.
filterdiff(1) patchutils V:2, I:15 292 This extracts or excludes diffs from a diff file.
fixcvsdiff(1) patchutils V:2, I:15 292 This fixes diff files created by CVS that "patch" mis-interprets.
flipdiff(1) patchutils V:2, I:15 292 This exchanges the order of two patches.
grepdiff(1) patchutils V:2, I:15 292 This shows which files are modified by a patch matching a regex.
interdiff(1) patchutils V:2, I:15 292 This shows differences between two unified diff files.
lsdiff(1) patchutils V:2, I:15 292 This shows which files are modified by a patch.
recountdiff(1) patchutils V:2, I:15 292 This recomputes counts and offsets in unified context diffs.
rediff(1) patchutils V:2, I:15 292 This fixes offsets and counts of a hand-edited diff.
splitdiff(1) patchutils V:2, I:15 292 This separates out incremental patches.
unwrapdiff(1) patchutils V:2, I:15 292 This demangles patches that have been word-wrapped.
wiggle(1) wiggle V:0.02, I:0.11 204 This applies rejected patches.
quilt(1) quilt V:1.0, I:6 856 This manage series of patches.
meld(1) meld V:0.4, I:2 2304 This is a GTK graphical file comparator and merge tool.
xxdiff(1) xxdiff V:0.2, I:1.1 1352 This is a plain X graphical file comparator and merge tool.
dirdiff(1) dirdiff V:0.09, I:0.5 212 This displays and merges changes between directory trees.
docdiff(1) docdiff V:0.02, I:0.18 688 This compares two files word by word / char by char.
imediff2(1) imediff2 V:0.02, I:0.11 76 This is an interactive full screen 2-way merge tool.
makepatch(1) makepatch V:0.03, I:0.2 148 This generates extended patch files.
applypatch(1) makepatch V:0.03, I:0.2 148 This applies extended patch files.
wdiff(1) wdiff V:1.8, I:14 124 This displays word differences between text files.

10.4.1. Extract differences for source files

Following one of these procedures will extract differences between two source files and create unified diff files "file.patch0" or "file.patch1" depending on the file location:

$ diff -u file.old file.new > file.patch0
$ diff -u old/file new/file > file.patch1

10.4.2. Merge updates for source files

The diff file (alternatively called patch file) is used to send a program update. The receiving party will apply this update to another file by:

$ patch -p0 file < file.patch0
$ patch -p1 file < file.patch1

10.4.3. 3 way merge updates

If you have three versions of source code, you can merge them more effectively using diff3(1):

$ diff3 -m file.mine file.old file.yours > file

10.5. Version control systems

Here is a summary of the version control systems (VCS) on the Debian system:

[注意] 注意

If you are new to VCS systems, you should start learning with Git, which is growing fast in popularity.

表10.15 List of version control system tools.

パッケージ popcon サイズ tool VCS type comment
cssc V:0.01, I:0.05 2168 CSSC local Clone of the Unix SCCS (deprecated)
rcs V:1.7, I:9 772 RCS local "Unix SCCSの本来あるべき姿"
cvs V:4, I:25 3660 CVS remote The previous standard remote VCS
subversion V:11, I:32 4228 Subversion remote "CVS done right", the new de facto standard remote VCS
git-core V:6, I:10 14344 Git 分散型 fast DVCS in C (used by the Linux kernel and others)
mercurial V:1.0, I:4 324 Mercurial 分散型 DVCS in python and some C.
bzr V:0.5, I:2 19652 Bazaar 分散型 DVCS influenced by tla written in python (used by Ubuntu)
darcs V:0.3, I:1.6 7872 Darcs 分散型 DVCS with smart algebra of patches (slow).
tla V:0.19, I:1.4 1100 GNU arch 分散型 DVCS mainly by Tom Lord. (Historic)
monotone V:0.05, I:0.4 4656 Monotone 分散型 DVCS in C++

VCS is sometimes known as revision control system (RCS), or software configuration management (SCM).

Distributed VCS such as Git is the tool of choice these days. CVS and Subversion may still be useful to join some existing open source program activities.

Debian provides free VCS services via Debian Alioth service. It supports practically all VCSs. Its documentation can be found at http://wiki.debian.org/Alioth .

[注意] 注意

The git package is "GNU Interactive Tools" which is not the DVCS.

10.5.1. Native VCS commands

Here is an oversimplified comparison of native VCS commands to provide the big picture. The typical command sequence may require options and arguments.

表10.16 Comparison of native VCS commands.

CVS Subversion Git 機能
cvs init svn create git init create the (local) repository
cvs login - - login to the remote repository
cvs co svn co git clone check out the remote repository as the working tree
cvs up svn up git pull update the working tree by merging the remote repository
cvs add svn add git add . add file(s) in the working tree to the VCS
cvs rm svn rm git rm remove file(s) in working tree from the VCS
cvs ci svn ci - commit changes to the remote repository
- - git commit -a commit changes to the local repository
- - git push update the remote repository by the local repository
cvs status svn status git status display the working tree status from the VCS
cvs diff svn diff git diff diff <reference_repository> <working_tree>
- - git repack -a -d; git prune repack the local repository into single pack.

[注意] 注意

Invoking a git subcommand as "git-xyzzy" from the command line has been deprecated since early 2006.

[ティップ] ティップ

Git can work directly with different VCS repositories such as ones provided by CVS and Subversion, and provides the local repository for local changes with git-cvs and git-svn packages. See git for CVS users, Git for GNOME developers and 「Git」.

[ティップ] ティップ

Git has commands which have no equivalents in CVS and Subversion. "Fetch", "Rebase", "Cherrypick", …

10.5.2. CVS

Check

  • cvs(1),
  • "/usr/share/doc/cvs/html-cvsclient",
  • "/usr/share/doc/cvs/html-info",
  • "/usr/share/doc/cvsbook", and
  • "info cvs", for detailed information.

10.5.2.1. Installing a CVS server

The following setup will allow commits to the CVS repository only by a member of the "src" group, and administration of CVS only by a member of the "staff" group, thus reducing the chance of shooting oneself.

# cd /var/lib; umask 002; mkdir cvs
# export CVSROOT=/var/lib/cvs
# cd $CVSROOT
# chown root:src .
# chmod 2775 .
# cvs -d $CVSROOT init
# cd CVSROOT
# chown -R root:staff .
# chmod 2775 .
# touch val-tags
# chmod 664 history val-tags
# chown root:src history val-tags

You may restrict creation of new project by changing the owner of "$CVSROOT" directory to "root:staff" and its permission to "3775".

10.5.2.2. Use local CVS server

The following will set up shell environments for the local access to the CVS repository:

$ export CVSROOT=/var/lib/cvs

10.5.2.3. Use remote CVS pserver

The following will set up shell environments for the read-only remote access to the CVS repository without SSH (use RSH protocol capability in cvs(1)):

$ export CVSROOT=:pserver:account@cvs.foobar.com:/var/lib/cvs
$ cvs login

This is prone to eavesdropping attack.

10.5.2.4. Anonymous CVS (download only)

The following will set up shell environments for the read-only remote access to the CVS repository:

$ export CVSROOT=:pserver:anonymous@cvs.sf.net:/cvsroot/qref
$ cvs login
$ cvs -z3 co qref

10.5.2.5. Use remote CVS through ssh

The following will set up shell environments for the read-only remote access to the CVS repository with SSH:

$ export CVSROOT=:ext:account@cvs.foobar.com:/var/lib/cvs

or for SourceForge:

$ export CVSROOT=:ext:account@cvs.sf.net:/cvsroot/qref

You can also use public key authentication for SSH which eliminates the password prompt.

10.5.2.6. Create a new CVS archive

For,

表10.17 Assumption for the CVS archive.

ITEM VALUE MEANING
source tree ~/project-x All source codes
プロジェクト名 project-x Name for this project
Vendor Tag Main-branch 全ブランチに対するタグ
Release Tag Release-initial Tag for a specific release

Then,

$ cd ~/project-x
  • create a source tree …
$ cvs import -m "Start project-x" project-x Main-branch Release-initial
$ cd ..; rm -R ~/project-x

10.5.2.7. Work with CVS

To work with project-x using the local CVS repository:

$ mkdir -p /path/to; cd /path/to
$ cvs co project-x
  • get sources from CVS to local
$ cd project-x
  • make changes to the content …
$ cvs diff -u
  • similar to "diff -u repository/ local/"
$ cvs up -C modified_file
  • undo changes to a file
$ cvs ci -m "Describe change"
  • save local sources to CVS
$ vi newfile_added
$ cvs add newfile_added
$ cvs ci -m "Added newfile_added"
$ cvs up
  • merge latest version from CVS.
  • To create all newly created subdirectories from CVS, use "cvs up -d -P" instead.
  • Watch out for lines starting with "C filename" which indicates conflicting changes.
  • unmodified code is moved to .#filename.version .
  • search for "<<<<<<<" and ">>>>>>>" in the files for conflicting changes.
  • edit file to fix conflicts.
$ cvs tag Release-1
  • add release tag
  • edit further …
$ cvs tag -d Release-1
  • remove release tag
$ cvs ci -m "more comments"
$ cvs tag Release-1

* re-add release tag

$ cd /path/to
$ cvs co -r Release-initial -d old project-x
  • get original version to "/path/to/old" directory
$ cd old
$ cvs tag -b Release-initial-bugfixes
  • create branch (-b) tag "Release-initial-bugfixes"
  • now you can work on the old version (Tag is sticky)
$ cvs update -d -P
  • don't create empty directories
  • source tree now has sticky tag "Release-initial-bugfixes"
  • work on this branch … while someone else making changes too
$ cvs up -d -P
  • sync with files modified by others on this branch
$ cvs ci -m "check into this branch"
$ cvs update -kk -A -d -P
  • remove sticky tag and forget contents
  • update from main trunk without keyword expansion
$ cvs update -kk -d -P -j Release-initial-bugfixes
  • merge from Release-initial-bugfixes branch into the main
  • trunk without keyword expansion. Fix conflicts with editor.
$ cvs ci -m "merge Release-initial-bugfixes"
$ cd
$ tar -cvzf old-project-x.tar.gz old
  • make archive. use "-j" if you want ".tar.bz2".
$ cvs release -d old
  • remove local source (optional)

表10.18 Notable options for CVS commands (use as first argument(s) to cvs(1)).

オプション 意味
-n dry run, no effect
-t display messages showing steps of cvs activity

10.5.2.8. Export files from CVS

To get the latest version from CVS, use "tomorrow":

$ cvs ex -D tomorrow module_name

10.5.2.9. Administer CVS

Add alias to a project (local server):

$ export CVSROOT=/var/lib/cvs
$ cvs co CVSROOT/modules
$ cd CVSROOT
$ echo "px -a project-x" >>modules
$ cvs ci -m "Now px is an alias for project-x"
$ cvs release -d .
$ cvs co -d project px
  • check out project-x (alias:px) from CVS to directory project
$ cd project
  • make changes to the content …

In order to perform above procedure, you should have the appropriate file permission.

10.5.2.10. File permissions in repository

CVS will not overwrite the current repository file but replaces it with another one. Thus, write permission to the repository directory is critical. For every new repository creation, run the following to ensure this condition if needed.

# cd /var/lib/cvs
# chown -R root:src repository
# chmod -R ug+rwX   repository
# chmod    2775     repository

10.5.2.11. Execution bit

A file's execution bit is retained when checked out. Whenever you see execution permission problems in checked-out files, change permissions of the file in the CVS repository with the following command.

# chmod ugo-x filename

10.5.3. Subversion

Subversion is a next-generation version control system, intended to replace CVS, so it has most of CVS's features. Generally, Subversion's interface to a particular feature is similar to CVS's, except where there's a compelling reason to do otherwise.

10.5.3.1. Installing a Subversion server

You need to install subversion, libapache2-svn and subversion-tools packages to set up a server.

10.5.3.2. Setting up a repository

Currently, the subversion package does not set up a repository, so one must be set up manually. One possible location for a repository is in "/var/local/repos".

ディレクトリ作成

# mkdir -p /var/local/repos

Create the repository database:

# svnadmin create /var/local/repos

Make the repository writable by the WWW server:

# chown -R www-data:www-data /var/local/repos

10.5.3.3. Configuring Apache2

To allow access to the repository via user authentication, add (or uncomment) the following in "/etc/apache2/mods-available/dav_svn.conf":

<Location /repos>
  DAV svn
  SVNPath /var/local/repos
  AuthType Basic
  AuthName "Subversion repository"
  AuthUserFile /etc/subversion/passwd
<LimitExcept GET PROPFIND OPTIONS REPORT>
    Require valid-user
</LimitExcept>
</Location>

Then, create a user authentication file with the command:

# htpasswd2 -c /etc/subversion/passwd some-username

Restart Apache2, and your new Subversion repository will be accessible with the URL "http://hostname/repos".

10.5.3.4. Subversion usage examples

The following sections teach you how to use different commands in Subversion.

10.5.3.5. Create a new Subversion archive

To create a new Subversion archive, type the following:

$ cd ~/your-project         # go to your source directory
$ svn import http://localhost/repos your-project project-name -m "initial project import"

This creates a directory named project-name in your Subversion repository which contains your project files. Look at "http://localhost/repos/" to see if it's there.

10.5.3.6. Working with Subversion

Working with project-y using Subversion:

$ mkdir -p /path/to ;cd  /path/to
$ svn co http://localhost/repos/project-y
  • Check out sources
$ cd project-y
  • do some work …
$ svn diff

-similar to "diff -u repository/ local/"

$ svn revert modified_file
  • undo changes to a file
$ svn ci -m "Describe changes"
  • check in your changes to the repository
$ vi newfile_added
$ svn add newfile_added
$ svn add new_dir
  • recursively add all files in new_dir
$ svn add -N new_dir2
  • 非再帰的にディレクトリを追加
$ svn ci -m "Added newfile_added, new_dir, new_dir2"
$ svn up
  • merge in latest version from repository
$ svn log
  • shows all changes committed
$ svn copy http://localhost/repos/project-y \
      http://localhost/repos/project-y-branch \
      -m "creating my branch of project-y"
  • branching project-y
$ svn copy http://localhost/repos/project-y \
      http://localhost/repos/projct-y-release1.0 \
      -m "project-y 1.0 release"
  • added release tag.
  • note that branching and tagging are the same. The only difference is that branches get committed whereas tags do not.
  • make changes to branch …
$ svn merge http://localhost/repos/project-y \
   http://localhost/repos/project-y-branch
  • merge branched copy back to main copy
$ svn co -r 4 http://localhost/repos/project-y
  • get revision 4

10.5.4. Git

Git can do everything for both local and remote source code management. This means that you can record the source code changes without needing network connectivity to the remote repository.

10.5.4.1. Before using Git

You may wish to set several global configuration in "~/.gitconfig" such as your name and email address used by Git:

$ git config --global user.name "Name Surname"
$ git config --global user.email yourname@example.com

If you are too used to CVS or Subversion commands, you may wish to set several command aliases;

$ git config --global alias.ci "commit -a"
$ git config --global alias.co checkout

You can check your global configuration by:

$ git config --global --list

10.5.4.2. Gitリファレンス

There are good references for Git.

git-gui(1) and gitk(1) commands make using Git very easy.

[警告] 警告

Do not use the tag string with spaces in it even if some tools such as gitk(1) allow you to use it. It will choke some other git commands.

10.5.4.3. Git commands

Even if your upstream uses different VCS, it is good idea to use git(1) for local activity since you can manage your local copy of source tree without the network connection to the upstream. Here are commands used with git(1).

表10.19 gitパッケージとコマンドのリスト。

コマンド パッケージ popcon サイズ 説明
N/A git-doc I:2 5804 This provides the oficial documentation for Git.
N/A gitmagic I:0.2 504 "Git Magic" provides easier to understand guide for Git.
git(7) git-core V:6, I:10 14344 The main command for Git.
gitk(1) gitk V:0.7, I:3 752 The GUI Git repository browser with history.
git-gui(1) git-gui V:0.2, I:2 1428 The GUI for Git. (No history)
git-svnimport(1) git-svn V:0.4, I:2 492 This import the data out of Subversion into Git.
git-svn(1) git-svn V:0.4, I:2 492 This provides bidirectional operation between the Subversion and Git.
git-cvsimport(1) git-cvs V:0.17, I:1.3 620 This import the data out of CVS into Git.
git-cvsexportcommit(1) git-cvs V:0.17, I:1.3 620 This exports a commit to a CVS checkout from Git.
git-cvsserver(1) git-cvs V:0.17, I:1.3 620 A CVS server emulator for Git.
git-send-email(1) git-email V:0.12, I:1.2 364 This sends a collection of patches as email from the Git.
stg(1) stgit V:0.08, I:0.6 844 This is quilt on top of git. (Python)
git-buildpackage(1) git-buildpackage V:0.16, I:0.8 440 This automates the Debian packaging with the Git.
guilt(7) guilt V:0.02, I:0.09 336 This is quilt on top of git. (SH/AWK/SED/…)

10.5.4.4. Git for recording configuration history

You can manually record chronological history of configuration using Git tools. Here is a simple example for your practice to record "/etc/apt/" contents.:

$ cd /etc/apt/
$ sudo git init
$ sudo chmod 700 .git
$ sudo git add .
$ sudo git commit -a
  • commit configuration with description.
  • make modification to the configuration files
$ cd /etc/apt/
$ sudo git commit -a
  • commit configuration with description.
  • … continue your life …
$ cd /etc/apt/
$ sudo gitk --all
  • you have full configuration history with you.
[注意] 注意

sudo(8) is needed to work with permissions of configuration data. For user configuration data, you may skip sudo.

[注意] 注意

The "chmod 700 .git" command in the above example is needed to protect archive data from unauthorized read access.

[ティップ] ティップ

For more complete setup for recording configuration history, please look for the etckeeper package: 「設定ファイルの変更記録」.

第11章 データ変換

Tools and tips for converting data formats on the Debian system are described.

Standard based tools are in very good shape but support for proprietary data formats are limited.

11.1. Text data conversion tools

Following packages for the text data conversion caught my eyes:

表11.1 テキストデータ変換ツールのリスト。

パッケージ popcon サイズ keyword 機能
libc6 V:95, I:99 11496 charset The text encoding converter between locales by iconv(1). (fundamental)
recode V:1.7, I:7 780 charset+eol The text encoding converter between locales. (versatile, more aliases and features)
konwert V:0.4, I:4 192 charset The text encoding converter between locales. (fancy)
nkf V:0.3, I:2 300 charset The character set translator for Japanese.
tcs V:0.03, I:0.17 544 charset The character set translator.
unaccent V:0.03, I:0.10 60 charset Replace accented letters by their unaccented equivalent.
tofrodos V:1.3, I:8 80 eol The text format converter between DOS and Unix: fromdos(1) and todos(1)
macutils V:0.10, I:0.7 356 eol The text format converter between Macintosh and Unix: frommac(1) and tomac(1)

11.1.1. To convert a text file with iconv

iconv(1) is provided as a part of the libc6 package and it is always available on all system to convert the encoding of characters:

$ iconv -f encoding1 -t encoding2 input.txt >output.txt

Encoding values are case insensitive and ignore "-" and "_" for matching. Supported encodings can be checked by the "iconv -l" command.

表11.2 List of encoding values and their usage.

encoding value 使い方
ASCII. American Standard Code for Information Interchange. 7 bit code w/o accented characters.
UTF-8 Standard multilingual compatibility for all modern OSs.
ISO-8859-1 Old standard for western European languages, ASCII + accented characters.
ISO-8859-2 Old standard for eastern European languages, ASCII + accented characters.
ISO-8859-15 Old standard for western European languages, ISO-8859-1 with euro sign.
CP850 Code page 850, Microsoft DOS characters with graphics for western European languages. ISO-8859-1 variant.
CP932 Code page 932, Microsoft Windows style Shift-JIS variant, for Japanese.
CP936 Code page 936, Microsoft Windows style GB2312, GBK, or GB18030 variant, for Simplified Chinese.
CP949 Code page 949, Microsoft Windows style EUC-KR or Unified Hangul Code variant, for Korean.
CP950 Code page 950, Microsoft Windows style Big5 variant, for Traditional Chinese.
CP1251 Code page 1251, Microsoft Windows style encoding for the Cyrillic alphabet.
CP1252 Code page 1252, Microsoft Windows style ISO-8859-15 variant for western European languages.
KOI8-R Old Russian UNIX standard for the Cyrillic alphabet.
ISO-2022-JP Standard encoding for Japanese e-mail which uses only 7 bit codes.
eucJP Old Japanese UNIX standard 8 bit code and completely different from Shift-JIS.
Shift-JIS JIS X 0208 Appendix 1 standard, for Japanese. See CP932 above.

[注意] 注意

Some encodings are only supported for the data conversion and are not used as locale values (「Basics of encoding」).

For character sets which fit in single byte such as ASCII and ISO-8859 character sets, the character encoding means almost the same thing as the character set.

For character sets with many characters such as JIS X 0213 for Japanese or Universal Character Set (UCS, Unicode, ISO-10646-1) for practically all languages, there are many encoding schemes to fit them into the sequence of the byte data:

The code page is used as the synonym to the character encoding tables for some vendor specific ones.

[注意] 注意

Please note most encoding systems share the same code with ASCII for the 7 bit characters. But there are some exceptions. If you are converting old Japanese C programs and URLs data from the casually-called shift-JIS encoding format to UTF-8 format, use "CP932" as the encoding name instead of "shift-JIS" to get the expected results: 0x5C → "\" and 0x7E → "~" . Otherwise, these are converted to wrong characters.

[ティップ] ティップ

recode(1) may be used too and offers more than the combined functionality of iconv(1), fromdos(1), todos(1), frommac(1), and tomac(1). For more, see "info recode".

11.1.2. To convert file names with iconv

Here is an example script to convert encoding of file names from ones created under older OS to modern UTF-8 ones in a single directory.

#!/bin/sh
ENCDN=iso-8859-1
for x in *;
 do
 mv "$x" $(echo "$x" | iconv -f $ENCDN -t utf-8)
done

The "$ENCDN" variable should be set by the encoding value in 表11.2「List of encoding values and their usage.」.

For more complicated case, please mount disk drive containing such file names with proper encoding as the mount(8) option (see 「Filename encoding」) and copy entire disk to another disk drive mounted as UTF-8 with "cp -a" command.

11.1.3. EOL conversion

The text file format, specifically the end-of-line (EOL) code, is dependent on the platform:

表11.3 List of EOL conversion tools.

platform EOL code EOL control sequence EOL ASCII value
Debian (unix) LF ^J 10
MSDOS and Windows CR-LF ^M^J 13, 10
Apple's Macintosh CR ^M 13

The EOL format conversion programs, fromdos(1), todos(1), frommac(1), and tomac(1), are quite handy. recode(1) is also useful.

[注意] 注意

Some data on the Debian system, such as the wiki page data for the python-moinmoin package, use MSDOS style CR-LF as the EOL code. So the above rule is just a general rule.

[注意] 注意

Most editors (eg. vim, emacs, gedit, …) can handle files in MSDOS style EOL transparently.

[ティップ] ティップ

The use of "sed -e '/\r$/!s/$/\r/'" instead of todos(1) is better when you want to unify the EOL style to the MSDOS style from the mixed MSDOS and Unix style. (e.g., after merging 2 MSDOS style files with diff3(1).) This is because todos adds CR to all lines.

11.1.4. TAB conversion

There are few popular specialized programs to convert the tab codes:

表11.4 List of TAB conversion commands from bsdmainutils and coreutils packages.

機能 bsdmainutils coreutils
expand tab to spaces "col -x" expand
unexpand tab from spaces "col -h" unexpand

indent(1) from the indent package completely reformats whitespaces in the C program.

Editor programs such as vim and emacs can be used for TAB conversion, too. For example with vim, you can expand TAB with ":set expandtab" and ":%retab" command sequence. You can revert this with ":set noexpandtab" and ":%retab!" command sequence.

11.1.5. Editors with auto-conversion

Intelligent modern editors such as the vim program are quite smart and copes well with any encoding systems and any file formats. You should use these editors under the UTF-8 locale in the UTF-8 capable console for the best compatibility.

An old western European Unix text file, "u-file.txt", stored in the latin1 (iso-8859-1) encoding can be edited simply with vim as:

$ vim u-file.txt

This is possible since the auto detection mechanism of the file encoding in vim assumes the UTF-8 encoding first and, if it fails, assumes it to be latin1.

An old Polish Unix text file, "pu-file.txt", stored in the latin2 (iso-8859-2) encoding can be edited with vim as:

$ vim '+e ++enc=latin2 pu-file.txt'

An old Japanese unix text file, "ju-file.txt", stored in the eucJP encoding can be edited with vim as:

$ vim '+e ++enc=eucJP ju-file.txt'

An old Japanese MS-Windows text file, "jw-file.txt", stored in the so called shift-JIS encoding (more precisely: CP932) can be edited with vim as:

$ vim '+e ++enc=CP932 ++ff=dos jw-file.txt'

When a file is opened with "enc" and "ff" options, ":w" in the Vim command line stores it in the original format and overwrite the original file. You can also specify the saving format and the file name in the Vim command line, e.g., ":w ++enc=utf8 new.txt".

Please refer to the mbyte.txt "multi-byte text support" in vim on-line help.

The emacs family of programs can perform the equivalent functions.

11.1.6. Plain text extraction

Following will read a web page into a text file. This is very useful when copying configurations off the Web or applying basic Unix text tools such as grep(1) on the web page.

$ w3m -dump http://www.remote-site.com/help-info.html >textfile

Similarly, you can extract plain text data from other formats using followings:

表11.5 平文テキストデータ抽出ツールのリスト。

パッケージ popcon サイズ keyword 機能
w3m V:23, I:85 1968 html→text An HTML to text converter with the "w3m -dump" command.
html2text V:14, I:40 308 html→text An advanced HTML to text converter. (ISO 8859-1)
lynx V:2, I:25 48 html→text An HTML to text converter with the "lynx -dump" command.
elinks V:2, I:6 1452 html→text An HTML to text converter with the "elinks -dump" command.
links V:3, I:9 1372 html→text An HTML to text converter with the "links -dump" command.
links2 V:1.0, I:4 3280 html→text An HTML to text converter with the "links2 -dump" command.
antiword V:1.0, I:2 796 MSWord→text,ps This converts MSWord files to plain text or ps.
catdoc V:0.8, I:2 2664 MSWord→text,TeX This converts MSWord files to plain text or TeX.
pstotext V:0.9, I:1.6 160 ps/pdf→text Extract text from PostScript and PDF files.
unhtml V:0.02, I:0.19 76 html→text Remove the markup tags from an HTML file.
odt2txt V:0.6, I:1.1 104 odt→text The converter from OpenDocument Text to text.
wpd2sxw V:0.02, I:0.16 156 WordPerfect→sxw WordPerfect to OpenOffice.org/StarOffice writer document converter.

11.1.7. Highlighting and formatting plain text data

表11.6 平文テキストデータをハイライトするツールのリスト。

パッケージ popcon サイズ keyword 機能
vim-runtime V:3, I:35 24688 highlight Vim can convert source code to HTML with ":source $VIMRUNTIME/syntax/html.vim" (vim MACRO)
cxref V:0.08, I:0.6 1104 c→html The converter for the C program to latex and HTML. (C language)
src2tex V:0.03, I:0.3 1968 highlight This convert many source codes to TeX. (C language)
source-highlight V:0.13, I:0.8 1980 highlight This convert many source codes to HTML, XHTML, LaTeX, Texinfo, ANSI color escape sequences and DocBook files with highlight. (C++)
highlight V:0.07, I:0.4 680 highlight This convert many source codes to HTML, XHTML, RTF, LaTeX, TeX or XSL-FO files with highlight. (C++)
grc V:0.03, I:0.12 164 text→color The generic colouriser for everything. (Python)
txt2html V:0.08, I:0.4 296 text→html Text to HTML converter. (Perl)
markdown V:0.09, I:0.4 96 text→html Markdown text document formatter to (X)HTML. (Perl)
asciidoc V:0.13, I:0.8 4316 text→any AsciiDoc text document formatter to XML/HTML. (Python)
python-docutils V:0.4, I:2 5052 text→any ReStructured Text document formatter to XML. (Python)
txt2tags V:0.06, I:0.3 1556 text→any The document conversion from text to HTML, SGML, LaTeX, man page, MoinMoin, Magic Point and PageMaker. (Python)
udo V:0.01, I:0.08 556 text→any universal document - text processing utility. (C language)
stx2any V:0.00, I:0.05 484 text→any The document converter from structured plain text to other formats. (m4)
rest2web V:0.02, I:0.10 576 text→html The document converter from ReStructured Text to html. (Python)
aft V:0.01, I:0.08 336 text→any The "free form" document preparation system. (Perl)
yodl V:0.01, I:0.07 536 text→any A pre-document language and tools to process it. (C language)
sdf V:0.01, I:0.09 1940 text→any The simple document parser. (Perl)
sisu V:0.01, I:0.07 5484 text→any The document structuring, publishing and search framework. (Ruby)

11.2. XML data

The Extensible Markup Language (XML) is a markup language for documents containing structured information.

XML.COM has good introductory information:

11.2.1. Basic hints for XML

XML text looks somewhat like HTML. It enables us to manage multiple formats of output for a document. One easy XML system is the docbook-xsl package, which is used here.

Each XML file starts with standard XML declaration:

<?xml version="1.0" encoding="UTF-8"?>

The basic syntax for one XML element is marked up as:

<name attribute="value">content</name>

XML element with empty content is marked up in the short form as:

<name attribute="value"/>

The "attribute="value"" in the above examples are optional.

The comment section in XML is marked up as:

<!-- comment -->

Other than adding markups, XML requires minor conversion to the content using predefined entities for the following character:

表11.7 XMLで事前定義されているエントリーのリスト。

predefined entity character to be converted from
&quot; " : quote
&apos; ' : apostrophe
&lt; < : less-than
&gt; > : greater-than
&amp; & : ampersand

[注意] 注意

"<" or "&" can not be used in attributes or elements.

[注意] 注意

When SGML style user defined entities, e.g. "&some-tag:", are used, the first definition wins over others. The entity definition is expressed in "<!ENTITY some-tag "entity value">".

[注意] 注意

As long as the XML markup are done consistently with certain set of the tag name (either some data as content or attribute value), conversion to another XML is trivial task using Extensible Stylesheet Language Transformations (XSLT).

11.2.2. XML processing

There are many tools available to process XML files such as the Extensible Stylesheet Language (XSL).

Basically, once you create well formed XML file, you can convert it to any format using Extensible Stylesheet Language Transformations (XSLT).

The Extensible Stylesheet Language for Formatting Object (XSL-FO) is supposed to be solution for formatting. The fop package is in the Debian contrib (not main) archive still. So the LaTeX code is usually generated from XML using XSLT and the LaTeX system is used to create printable file such as DVI, PostScript, and PDF.

表11.8 List of XML tools.

パッケージ popcon サイズ keyword 機能
docbook-xml V:23, I:55 2488 xml This package contains the XML document type definition (DTD) for DocBook.
xsltproc V:5, I:52 180 xslt XSLT command line processor. (XML→ XML, HTML, plain text, etc.)
docbook-xsl V:0.7, I:6 12968 xml/xslt This contains XSL stylesheets for processing DocBook XML to various output formats with XSLT.
xmlto V:0.4, I:2 272 xml/xslt XML-to-any converter with XSLT.
dblatex V:0.18, I:1.2 6420 xml/xslt This converts Docbook files to DVI, PostScript, PDF documents with XSLT.
fop V:0.15, I:1.0 2296 xml/xsl-fo This converts Docbook XML files to PDF.

Since XML is subset of Standard Generalized Markup Language (SGML), it can be processed by the extensive tools available for SGML, such as Document Style Semantics and Specification Language (DSSSL).

表11.9 List of DSSL tools.

パッケージ popcon サイズ keyword 機能
openjade V:0.6, I:3 1212 dsssl Implementation of the DSSSL language based on James Clark's Jade software.
jade V:0.5, I:3 1056 dsssl James lark's DSSSL language.
docbook-dsssl V:0.7, I:5 3100 xml/dsssl This contains DSSSL stylesheets for processing DocBook XML to various output formats with DSSSL.
docbook-utils V:0.3, I:2 440 xml/dsssl The utilities for Docbook files including conversion to other formats (HTML, RTF, PS, man, PDF) with docbook2* commands with DSSSL.
sgml2x V:0.01, I:0.10 216 SGML/dsssl The converter from SGML and XML using DSSSL stylesheets.

11.2.3. The XML data extraction

You can extract HTML or XML data from other formats using followings:

表11.10 List of XML data extraction tools.

パッケージ popcon サイズ keyword 機能
wv V:1.5, I:3 2136 MSWord→any The document converter from Microsoft Word to HTML, LaTeX, etc..
texi2html V:0.4, I:3 1752 texi→html The converter from Texinfo to HTML.
man2html V:0.3, I:1.6 372 manpage→html The converter from manpage to HTML. (CGI support)
tex4ht V:0.2, I:2 932 tex↔html The converter between (La)TeX and HTML.
xlhtml V:0.6, I:1.6 184 MSExcel→html The converter from MSExcel .xls to HTML.
ppthtml V:0.6, I:1.6 120 MSPowerPoint→html The converter from MSPowerPoint to HTML.
unrtf V:0.4, I:1.0 276 rtf→html The document converter from RTF to HTML, etc..
info2www V:0.5, I:1.4 156 info→html The converter from GNU info to HTML. (CGI support)
ooo2dbk V:0.03, I:0.2 941 sxw→xml The converter from OpenOffice.org SXW documents to DocBook XML.
wp2x V:0.02, I:0.10 240 WordPerfect→any WordPerfect 5.0 and 5.1 files to TeX, LaTeX, troff, GML and HTML.
doclifter V:0.00, I:0.05 420 troff→xml The converter from troff to DocBook XML.

For non-XML HTML files, you can convert them to XHTML which is an instance of well formed XML and can be processed by XML tools.

表11.11 List of XML pretty print tools.

パッケージ popcon サイズ keyword 機能
libxml2-utils V:5, I:53 120 xml↔html↔xhtml The command line XML tool with xmllint(1). (syntax check, reformat, lint, …)
tidy V:1.8, I:15 108 xml↔html↔xhtml HTML syntax checker and reformatter.

Once proper XML is generated, you can use XSLT technology to extract data based on the mark-up context etc.

11.3. Printable data

Printable data is expressed in the PostScript format on the Debian system. Common Unix Printing System (CUPS) uses Ghostscript as its rasterizer backend program for non-PostScript printers.

11.3.1. Ghostscript

The core of printable data manipulation is the Ghostscript PostScript (PS) interpreter which generates raster image.

The latest upstream Ghostscript from Artifex was re-licensed from AFPL to GPL and merged all the latest ESP version changes such as CUPS related ones at 8.60 release as unified release.

表11.12 List of Ghostscript PostScript interpreters.

パッケージ popcon サイズ 説明
ghostscript V:17, I:47 3316 The GPL Ghostscript PostScript/PDF interpreter
ghostscript-x V:13, I:30 256 The GPL Ghostscript PostScript/PDF interpreter - X Display support
gs-cjk-resource I:0.5 4652 Resource files for gs-cjk, Ghostscript CJK-TrueType extension
cmap-adobe-cns1 I:0.4 1588 CMaps for Adobe-CNS1 (for traditional Chinese support)
cmap-adobe-gb1 I:0.4 1580 CMaps for Adobe-GB1 (for simplified Chinese support)
cmap-adobe-japan1 I:0.9 2476 CMaps for Adobe-Japan1 (for Japanese standard support)
cmap-adobe-japan2 I:0.4 440 CMaps for Adobe-Japan2 (for Japanese extra support)
cmap-adobe-korea1 I:0.2 912 CMaps for Adobe-Korea1 (for Korean support)
libpoppler4 I:12 2206 PDF rendering library based on xpdf PDF viewer
libpoppler-glib4 V:4, I:11 388 PDF rendering library (GLib-based shared library)
poppler-data I:0.3 12276 CMaps for PDF rendering library (for CJK support: Adobe-*)

[ティップ] ティップ

"gs -h" to display the configuration of Ghostscript.

11.3.2. Merge two PS or PDF files

You can merge two PostScript (PS) or Portable Document Format (PDF) files using gs(1) of Ghostscript.

$ gs -q -dNOPAUSE -dBATCH -sDEVICE=pswrite -sOutputFile=bla.ps -f foo1.ps foo2.ps
$ gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=bla.pdf -f foo1.pdf foo2.pdf
[注意] 注意

The PDF, which is widely used cross-platform printable data format, is essentially the compressed PS format with few additional features and extensions.

[ティップ] ティップ

From command line, psmerge(1) and other commands from the psutils package are useful for manipulating PostScript documents. Commands in the pdfjam package work similarly for manipulating PDF documents. pdftk(1) from the pdftk package is useful for manipulating PDF documents, too.

11.3.3. Printable data utilities

The following packages for the printable data utilities caught my eyes:

表11.13 プリントできるデータのユーティリティのリスト。

パッケージ popcon サイズ keyword 機能
poppler-utils V:6, I:51 428 pdf→ps,text,… PDF utilities. (pdftops, pdfinfo, pdfimages, pdftotext, and pdffonts)
psutils V:3, I:26 408 ps→ps PostScript document conversion tools
poster V:2, I:16 80 ps→ps Create large posters out of PostScript pages.
xpdf-utils V:1.9, I:8 4680 pdf→ps,text,… PDF utilities. (pdftops, pdfinfo, pdfimages, pdftotext, and pdffonts)
enscript V:2, I:21 2432 text→ps, html, rtf Converts ASCII text to Postscript, HTML, RTF or Pretty-Print.
a2ps V:1.7, I:9 4288 text→ps 'Anything to PostScript' converter and pretty-printer.
pdftk V:0.9, I:4 3292 pdf→pdf PDF document conversion tool: (pdftk)
mpage V:0.2, I:1.9 224 text,ps→ps Print multiple pages per sheet.
html2ps V:0.3, I:2 260 html→ps The converter from HTML to PostScript.
pdfjam V:0.3, I:1.8 112 pdf→pdf PDF document conversion tools: pdf90, pdfjoin, and pdfnup
gnuhtml2latex V:0.13, I:0.9 24 html→latex The converter from html to latex.
latex2rtf V:0.19, I:1.0 544 latex→rtf This converts documents from LaTeX to RTF which can be read by MS Word.
ps2eps V:1.4, I:10 116 ps→eps The converter from PostScript to EPS (Encapsulated PostScript).
e2ps V:0.02, I:0.17 188 text→ps Text to PostScript converter with Japanese encoding support.
impose+ V:0.03, I:0.19 180 ps→ps Postscript utilities.
trueprint V:0.02, I:0.17 188 text→ps This pretty print many source codes (C, C++, Java, Pascal, Perl, Pike, Sh, and Verilog) to PostScript. (C language)
pdf2svg V:0.08, I:0.4 60 ps→svg Converter from PDF to Scalable vector graphics format.
pdftoipe V:0.04, I:0.18 648 ps→ipe Converter from PDF to IPE's XML format.

11.3.4. Printing with CUPS

Both lp(1) and lpr(1) commands offered by Common Unix Printing System (CUPS) provides options for customized printing the printable data.

For printing 3 copies of a file collated:

$ lp -n 3 -o Collate=True filename

, or

$ lpr -#3 -o Collate=True filename

You can further customize printer operation by using printer option such as "-o number-up=2", "-o page-set=even", "-o page-set=odd", "-o scaling=200", "-o natural-scaling=200", etc., documented at Command-Line Printing and Options.

11.4. Type setting

The Unix troff program originally developed by AT&T can be used for simple type setting. It is usually used to create manpages.

TeX created by Donald Knuth is very powerful type setting tool and is the de facto standard. LaTeX originally written by Leslie Lamport enables a high-level access to the power of TeX.

表11.14 List of type setting tools.

パッケージ popcon サイズ keyword 機能
texlive-base V:6, I:20 17368 (La)TeX TeX system for typesetting, previewing and printing.
groff V:1.0, I:7 5540 troff GNU troff text-formatting system.

11.4.1. roff typesetting

Traditionally, roff is the main Unix text processing system. See roff(7), groff(7), groff(1), grotty(1), troff(1), groff_mdoc(7), groff_man(7), groff_ms(7), groff_me(7), groff_mm(7), and "info groff".

A good tutorial on "-me" macros is availabe:

  • Install the groff package,
  • find "/usr/share/doc/groff/meintro.me.gz", and
  • do the following:
$ zcat /usr/share/doc/groff/meintro.me.gz | \
     groff -Tascii -me - | less -R

The following will make a completely plain text file:

$ zcat /usr/share/doc/groff/meintro.me.gz | \
    GROFF_NO_SGR=1 groff -Tascii -me - | col -b -x > meintro.txt

For printing, use PostScript output.

$ groff -Tps meintro.txt | lpr
$ groff -Tps meintro.txt | mpage -2 | lpr

11.4.2. TeX/LaTeX

Preparation:

# aptitude install texlive

References for LaTeX:

  • The teTeX HOWTO: The Linux-teTeX Local Guide
  • tex(1)
  • latex(1)
  • "The TeXbook", by Donald E. Knuth, (Addison-Wesley)
  • "LaTeX - A Document Preparation System", by Leslie Lamport, (Addison-Wesley)
  • "The LaTeX Companion", by Goossens, Mittelbach, Samarin, (Addison-Wesley)

This is the most powerful typesetting environment. Many SGML processors use this as their back end text processor. Lyx provided by the lyx package and GNU TeXmacs provided by the texmacs package offer nice WYSIWYG editing environment for LaTeX while many use Emacs and Vim as the choice for the source editor.

There are many online resources available:

When documents become bigger, sometimes TeX may cause errors. You must increase pool size in "/etc/texmf/texmf.cnf" (or more appropriately edit "/etc/texmf/texmf.d/95NonPath" and run update-texmf(8)) to fix this.

[注意] 注意

The TeX source of "The TeXbook" is available at http://tug.ctan.org/tex-archive/systems/knuth/dist/tex/texbook.tex.

This file contains most of the required macros. I heard that you can process this document with tex(1) after commenting lines 7 to 10 and adding "\input manmac \proofmodefalse". It's strongly recommended to buy this book (and all other books from Donald E. Knuth) instead of using the online version but the source is a great example of TeX input!

11.4.3. Pretty print a manual page

The following will print a manual page in PostScript and print it.

$ man -Tps some_manpage | lpr
$ man -Tps some_manpage | mpage -2 | lpr

11.4.4. Creating a manual page

Although writing a manual page (manpage) in the plain troff format is possible, there are few helper packages to create it.

表11.15 マンページ作成を補助するパッケージのリスト。

パッケージ popcon サイズ keyword 機能
docbook-to-man V:0.5, I:3 248 SGML→manpage The converter from DocBook SGML into roff man macros.
help2man V:0.17, I:1.1 236 text→manpage Automatic manpage generator from --help.
info2man V:0.03, I:0.17 204 info→manpage The converter from GNU info to POD or man pages.
txt2man V:0.03, I:0.19 88 text→manpage Converts flat ASCII text to man page format.

11.5. The mail data conversion

The following packages for the mail data conversion caught my eyes:

表11.16 メールデータ変換を補助するパッケージのリスト。

パッケージ popcon サイズ keyword 機能
sharutils V:4, I:60 976 mail shar(1), unshar(1), uuencode(1), uudecode(1)
mpack V:3, I:51 84 mail The encoder and decoder MIME messages: mpack(1) and munpack(1).
tnef V:0.5, I:1.5 160 mail unpacking MIME attachments of type "application/ms-tnef" which is a Microsoft only format.
uudeview V:0.2, I:1.4 128 mail The encoder and decoder for the following formats: uuencode, xxencode, BASE64, quoted printable, and BinHex
mimedecode V:0.12, I:0.8 76 mail This decodes transfer encoded text type MIME messages.
readpst V:0.05, I:0.3 228 windows/mail This converts Outlook PST files to mbox format.

[ティップ] ティップ

The Internet Message Access Protocol version 4 (IMAP4) server (see 「POP3/IMAP4 server」) may be used to move mails out from proprietary mail systems if the mail client software can be configured to use IMAP4 server too.

11.5.1. Mail data basics

Mail (SMTP) data should be limited to 7 bit. So binary data and 8 bit text data are encoded into 7 bit format with the Multipurpose Internet Mail Extensions (MIME) and the selection of the charset (see 「Basics of encoding」).

The standard mail storage format is mbox formatted according to RFC2822 (updated RFC822). See mbox(5) (provided by the mutt package).

For European languages, "Content-Transfer-Encoding: quoted-printable" with the ISO-8859-1 charset is usually used since there are no much 8 bit characters. If the text is in UTF-8, "Content-Transfer-Encoding: quoted-printable" is also used since it is mostly 7 bit data.

For Japanese, traditionally "Content-Type: text/plain; charset=ISO-2022-JP" should be used to keep text in 7 bits. But mails from older Microsoft systems may use in Shift-JIS without proper declaration. For Japanese, if the text is in UTF-8, it contains many 8 bit data and is encoded into 7 bit data by Base64. The situation of other Asian languages is similar.

[注意] 注意

If your non-Unix mail data is accessible by a non-Debian client software which can talk to the IMAP4 server, you may be able to move them out by running your own IMAP4 server (see 「POP3/IMAP4 server」).

[注意] 注意

If you use other mail storage formats, moving them to mbox format is the good first step. The versatile client program such as mutt(1) may be handy for this.

You can split mailbox contents to each message using procmail(1) and formail(1).

Each mail message can be unpacked using munpack(1) from the mpack package (or other specialized tools) to obtain the MIME encoded contents.

11.6. Graphic data tools

The following packages for the graphic data conversion, editing, and organization tools caught my eyes:

表11.17 グラフィックデータツールのリスト。

パッケージ popcon サイズ keyword 機能
gimp V:14, I:50 13468 image(bitmap) The GNU Image Manipulation Program.
imagemagick V:15, I:32 304 image(bitmap) Image manipulation programs.
graphicsmagick V:1.5, I:3 3696 image(bitmap) Image manipulation programs. (folk of imagemagick)
xsane V:7, I:42 744 image(bitmap) GTK+-based X11 frontend for SANE (Scanner Access Now Easy).
netpbm V:4, I:23 4408 image(bitmap) Graphics conversion tools.
icoutils V:0.07, I:0.5 200 png↔ico(bitmap) Converts MS Windows icons and cursors to and from PNG formats (favicon.ico)
xpm2wico V:0.03, I:0.13 80 xpm→ico(bitmap) Converts XPM to MS Windows icon formats
scribus V:0.7, I:3 26864 ps/pdf/SVG/… The Scribus DTP editor.
openoffice.org-draw V:22, I:47 8808 image(vector) OpenOffice.org office suite - drawing
inkscape V:12, I:28 61584 image(vector) The SVG (Scalable Vector Graphics) editor.
dia-gnome V:1.6, I:4 596 image(vector) Diagram editor (GNOME)
dia V:2, I:5 596 image(vector) Diagram editor (Gtk)
xfig V:2, I:5 1768 image(vector) Facility for Interactive Generation of figures under X11
pstoedit V:1.1, I:9 880 ps/pdf→image(vector) PostScript and PDF files to editable vector graphics converter. (SVG)
libwmf-bin V:1.0, I:8 88 Windows/image(vector) Windows metafile (vector graphic data) conversion tools.
fig2sxd V:0.06, I:0.3 200 fig→sxd(vector) Convert XFig files to OpenOffice.org Draw format
unpaper V:0.2, I:1.4 736 image→image Post-processing tool for scanned pages for OCR.
tesseract-ocr V:0.4, I:2 2072 image→text Free OCR software based on the HP's commercial OCR engine.
tesseract-ocr-eng V:0.08, I:0.8 1760 image→text OCR engine data: tesseract-ocr language files for English text.
clara V:0.06, I:0.4 NOT_FOUND image→text Free OCR software.
gocr V:1.1, I:6 484 image→text Free OCR software.
ocrad V:0.9, I:6 364 image→text Free OCR software.
gtkam V:0.3, I:2 1348 image(Exif) Manipulates digital camera photo files (GNOME) - GUI
gphoto2 V:0.5, I:3 1008 image(Exif) Manipulates digital camera photo files (GNOME) - command line
kamera V:1.2, I:20 292 image(Exif) Manipulates digital camera photo files (KDE)
jhead V:0.6, I:3 128 image(Exif) Manipulates the non-image part of Exif compliant JPEG (digital camera photo) files
exif V:0.3, I:1.7 276 image(Exif) Command-line utility to show EXIF information in JPEG files
exiftags V:0.18, I:1.0 248 image(Exif) Utility to read Exif tags from a digital camera JPEG file
exiftran V:0.2, I:1.3 92 image(Exif) Transforms digital camera jpeg images
exifprobe V:0.06, I:0.3 484 image(Exif) Reads metadata from digital pictures
dcraw V:1.2, I:6 408 image(Raw)→ppm Decodes raw digital camera images
findimagedupes V:0.07, I:0.4 136 image→fingerprint Finds visually similar or duplicate images
ale V:0.03, I:0.2 812 image→image Merges images to increase fidelity or create mosaics
imageindex V:0.05, I:0.3 192 image(Exif)→html Generates static HTML galleries from images
f-spot V:0.6, I:1.8 10504 image(Exif) Personal photo management application (GNOME)
bins V:0.02, I:0.2 2008 image(Exif)→html Generates static HTML photo albums using XML and EXIF tags
galrey V:0.02, I:0.16 116 image(Exif)→html Generates browsable HTML photo albums with thumbnails
outguess V:0.03, I:0.16 252 jpeg,png Universal Steganographic tool
qcad V:1.3, I:2 3824 DXF CAD data editor (KDE)
blender V:0.7, I:3 28588 blend, TIFF, VRML, … 3D content editor for animation etc.
open-font-design-toolkit I:0.02 36 ttf, ps, … Metapackage for open font design
fontforge V:0.2, I:2 6112 ttf, ps, … Font editor for PS, TrueType and OpenType fonts
xgridfit V:0.00, I:0.05 724 ttf a program for gridfitting, or "hinting," TrueType fonts
gbdfed V:0.02, I:0.16 536 bdf Editor for BDF fonts

[ティップ] ティップ

Search more image tools using regex "~Gworks-with::image" in aptitude(8) (see 「aptitudeを使った探索方法」).

Although GUI programs such as gimp(1) are very powerful, command line tools such as imagemagick(1) are quite useful for automating image manipulation with the script.

The de facto image file format of the digital camera is the Exchangeable Image File Format (EXIF) which is the JPEG image file format with additional metadata tags. It can hold information such as date, time, and camera settings.

The Lempel-Ziv-Welch (LZW) lossless data compression patent has been expired. Graphics Interchange Format (GIF) utilities which use the LZW compression method are now freely available on the Debian system.

[ティップ] ティップ

Any digital camera or scanner with removable recording media will work with Linux through USB Mass Storage readers since it follows the Design rule for Camera File system.

11.7. Miscellaneous data conversion

There are many other programs for converting data. Following packages caught my eyes using regex "~Guse::converting" in aptitude(8) (see 「aptitudeを使った探索方法」):

表11.18 List of miscellaneous data conversion tools.

パッケージ popcon サイズ keyword 機能
alien V:1.6, I:12 276 rpm/tgz→deb The converter for the foreign package into the Debian package.
freepwing V:0.00, I:0.03 568 EB→EPWING The converter from "Electric Book" (popular in Japan) to a single JIS X 4081 format (a subset of the EPWING V1).

You can also extract data from RPM format with:

$ rpm2cpio file.src.rpm | cpio --extract

第12章 Programming

I provide some pointers for people to learn programming on the Debian system enough to trace the packaged source code. Here are notable packages and corresponding documentation packages for programing.

表12.1 プログラムをすることを補助するパッケージのリスト。

パッケージ popcon サイズ 文書
autoconf V:4, I:26 1868 "info autoconf" provided by autoconf-doc
automake V:3, I:18 1716 "info automake" provided by automake1.10-doc
bash V:91, I:99 1336 "info bash" provided by bash-doc
bison V:2, I:17 1820 "info bison" provided by bison-doc
cpp V:45, I:85 76 "info cpp" provided by cpp-doc
ddd V:0.4, I:3 4104 "info ddd" provided by ddd-doc
exuberant-ctags V:1.3, I:6 288 exuberant-ctags(1)
flex V:2, I:17 1004 "info flex" provided by flex-doc
gawk V:24, I:28 2116 "info gawk" provided by gawk-doc
gcc V:18, I:69 64 "info gcc" provided by gcc-doc
gdb V:6, I:34 7128 "info gdb" provided by gdb-doc
gettext V:9, I:51 7856 "info gettext" provided by gettext-doc
gfortran V:1.3, I:6 40 "info gfortran" provided by gfortran-doc
glade V:0.4, I:2 1397 Help provided via menu
glade-gnome V:0.17, I:1.5 434 Help provided via menu
libc6 V:95, I:99 11496 "info libc" provided by glibc-doc and glibc-doc-reference
make V:22, I:76 1220 "info make" provided by make-doc
mawk V:69, I:99 248 mawk(1)
perl V:89, I:99 18824 perl(1) and html pages provided by perl-doc and perl-doc-html
python V:62, I:96 620 python(1) and html pages provided by python-doc
tcl8.4 V:8, I:45 3336 tcl(3) and detail manual pages provided by tcl8.4-doc
tk8.4 V:6, I:35 2800 tk(3) and detail manual pages provided by tk8.4-doc
ruby V:10, I:25 100 ruby(1) and interactive reference provided by ri
vim V:14, I:30 1740 Help(F1) menu provided by vim-doc
susv2 I:0.03 48 Fetch "The Single Unix Specifications v2"
susv3 I:0.09 48 Fetch "The Single Unix Specifications v3"

Online references are available by typing "man name" after installing manpages and manpages-dev packages. Online references for the GNU tools are available by typing "info program_name" after installing the pertinent documentation packages. You may need to include the contrib and non-free archives in addition to the main archive since some GFDL documentations are not considered to be DSFG compliant.

[警告] 警告

Do not use "test" as the name of an executable test file. "test" is a shell builtin.

[注意] 注意

ソースから直接コンパイルしたソフトウエアプログラムは、システムプログラムとかち合わないように、"/usr/local"か"/opt"の中にインストールしましょう。

[ティップ] ティップ

Code examples of creating "Song 99 Bottles of Beer" should give you good idea of practically all the programming languages.

12.1. シェルスクリプト

The shell script is a text file with the execution bit set and contains the commands in the following format.

#!/bin/sh
... command lines ...

The first line specifies the shell interpreter which read and execute this file contents.

Reading shell scripts is the best way to understand how a Unix-like system works. Here, I give some pointers and reminders for shell programming. See "Shell Mistakes" (http://www.greenend.org.uk/rjk/2001/04/shell.html) to learn from mistakes.

Unlike shell interactive mode (see 「シェルプロンプト」 and 「Unix的テキスト処理」), parameters, conditionals, and loops are used frequently.

12.1.1. POSIX shell compatibility

Many system scripts may be interpreted by any one of POSIX shells (see 表1.14「シェルプログラムのリスト。」). The default shell for the system is "/bin/sh" which is a symlink pointing to the actual program:

  • bash(1) for lenny or older.
  • dash(1) for squeeze or newer.

Avoid writing a shell script with "bashisms" or "zshisms" to make it portable among all POSIX shells. You can check it using checkbashisms(1).

表12.2 List of typical bashisms.

Good: POSIX Avoid: bashism
if [ "$foo" = "$bar" ] ; then … if [ "$foo" == "$bar" ] ; then …
diff -u file.c.orig file.c diff -u file.c{.orig,}
mkdir /foobar /foobaz mkdir /foo{bar,baz}
octal format: "\377" hexadecimal format: "\xff"

The "echo" command must be used with care since its implementation differs among shell builtin commands and external command:

  • Avoid using any command options except "-n". (Notably avoid "-e" and "-E")
  • Avoid using escape sequences in the string since their handling varies.
[注意] 注意

Although "-n option is not really POSIX syntax, it is generally accepted.

[ティップ] ティップ

Use the "printf" command instead of the "echo" command if you need to embed escape sequences in the output string.

12.1.2. シェル変数

Special shell parameters are frequently used in the shell script:

表12.3 シェル変数のリスト。

シェル変数 変数値
$0 シェルまたはシェルスクリプトの名前
$1 最初(1番目)のシェル引数
$9 9番目のシェル引数
$# シェル引数の数
"$*" "$1 $2 $3 $4 … "
"$@" "$1" "$2" "$3" "$4" …
$? 最近実行のコマンドの終了状態
$$ このシェルスクリプトのPID
$! 最近スタートしたバックグラウンドジョブのPID

覚えておくべき基本的なパラメータ展開:

表12.4 List of shell parameter expansions.

parameter expression form value if var is set value if var is not set
${var:-string} "$var" "string"
${var:+string} "string" "null"
${var:=string} "$var" "string" (and run "var=string")
${var:?string} "$var" echo "string" to stderr (and exit with error)

Here, the colon ":" in all of these operators is actually optional.

  • With ":" = operator test for exist and not null.
  • Without ":" = operator test for exist only.

表12.5 List of key shell parameter substitutions.

parameter substitution form Result
${var%suffix} Remove smallest suffix pattern
${var%%suffix} Remove largest suffix pattern
${var#prefix} Remove smallest prefix pattern
${var##prefix} Remove largest prefix pattern

12.1.3. Shell conditionals

Each command returns an exit status which can be used for conditional expressions:

  • Success: 0 (True)
  • Error: 1--255 (False) Note that the use here of a 0 value to mean "true" differs from the usual convention in some other areas of computing. Also, "[" is the equivalent of the test command, which evaluates its arguments up to "]" as a conditional expression.

覚えておくべき基本的な定形条件文は次です:

  • "<command> && <if_success_run_this_command_too> || true",
  • "<command> || <if_not_success_run_this_command_too> || true", and
  • a multi-line script snippet:
if [ <conditional_expression> ]; then
 <if_success_run_this_command>
else
 <if_not_success_run_this_command>
fi

Here trailing "|| true" was needed to ensure this shell script will not exit at this line accidentally when shell is invoked with "-e" flag.

表12.6 List of file comparison operators in the conditional expression.

equation 変数値
-e <file> True if <file> exists.
-d <file> True if <file> exists and is a directory.
-f <file> True if <file> exists and is a regular file.
-w <file> True if <file> exists and is writable.
-x <file> True if <file> exists and is executable.
<file1> -nt <file2> True if <file1> is newer than <file2>. (modification).
<file1> -ot <file2> True if <file1> is older than <file2>. (modification).
<file1> -ef <file2> True if they are the same device and inode number.

表12.7 List of string comparison operators in the conditional expression.

equation 変数値
-z <str> True if the length of <str> is zero.
-n <str> True if the length of <str> is non-zero.
<str1> = <str2> True if <str1> and <str2> are equal.
<str1> != <str2> True if <str1> and <str2> are not equal.
<str1> < <str2> True if <str1> sorts before <str2>. (locale dependent)
<str1> > <str2> True if <str1> sorts after <str2>. (locale dependent)

Arithmetic integer comparison operators in the conditional expression are "-eq", "-ne", "-lt", "-le", "-gt", and "-ge".

12.1.4. シェルループ

There are several loop idioms to use in POSIX shell:

  • "for name in word ; do list ; done": loops over list of words.
  • "while list; do list; done": repeats while true.
  • "until list; do list; done": repeats while not true.
  • "break": enables to exit from the loop.
  • "continue" enables to resume the next iteration of the loop.
[ティップ] ティップ

The C-language like numeric iteration can be realized by using seq(1) as the "word" generator.

12.1.5. The shell command-line processing sequence

The shell processes a script as following sequence:

  • split line into tokens by the metacharacters: SPACE TAB NEWLINE ; ( ) < > | &
  • check keyword if not within "…" or '…' (loop)
  • expand alias if not within "…" or '…' (loop)
  • expand tilde, "~<user>" → <user>'s home directory, if not within "…" or '…'
  • expand parameter, "$PARAMETER", if not within '…'
  • expand command substitution, "$( command )", if not within '…'
  • split into words with "$IFS" if not within "…" or '…'
  • expand * ? [ ] in pathname if not within "…" or '…'
  • コマンド次から検索します:

    • 関数定義
    • ビルトインコマンド
    • "$PATH"中の実行ファイル
  • go to the next line and repeat this process again from the top of this sequence

Single quotes within double quotes have no effect.

Executing "set -x" in the shell or invoking the shell with "-x" option make the shell to print all of commands executed. This is quite handy for debugging.

12.1.6. Utility programs for shell script

In order to make your shell program as portable as possible across Debian system, it is good idea to limit utility programs used within Essential programs listed by "aptitude search ~E" as much as possible.

coreutils, bsdutils, and debianutils packages contain many useful small utilities.

12.1.7. Shell script dialog

The user interface of a simple shell program can be improved from dull interaction by echo and read commands to more interactive one by using one of the so-called dialog program etc.

表12.8 List of user interface programs.

パッケージ popcon サイズ 機能
x11-utils V:21, I:46 644 xmessage(1) displays a message or query in a window. (X)
whiptail V:49, I:99 64 displays user-friendly dialog boxes from shell scripts. (newt)
dialog V:5, I:24 1508 displays user-friendly dialog boxes from shell scripts. (ncurses)
zenity V:6, I:46 4032 display graphical dialog boxes from shell scripts. (gtk2.0)
gtkdialog V:0.07, I:0.3 488 GUI-creation command-line utility based on GTK+ library. (gtk2.0+glade2)
ssft V:0.01, I:0.12 152 Shell Scripts Frontend Tool. (wrapper for zenity, kdialog, and dialog with gettext)
gettext V:9, I:51 7856 "/usr/bin/gettext.sh" for translate message

12.1.8. Shell script example with zenity

Here is a simple script which creates ISO image with RS02 data supplemented by dvdisaster(1):

#!/bin/sh -e
# gmkrs02 : Copyright (C) 2007 Osamu Aoki <osamu@debian.org>, Public Domain
#set -x
error_exit()
{
  echo "$1" >&2
  exit 1
}
# Initialize variables
DATA_ISO="$HOME/Desktop/iso-$$.img"
LABEL=$(date +%Y%m%d-%H%M%S-%Z)
if [ $# != 0 ] && [ -d "$1" ]; then
  DATA_SRC="$1"
else
  # Select directory for creating ISO image from folder on desktop
  DATA_SRC=$(zenity --file-selection --directory  \
    --title="Select the directory tree root to create ISO image") \
    || error_exit "Exit on directory selection"
fi
# Check size of archive
xterm -T "Check size $DATA_SRC" -e du -s $DATA_SRC/*
SIZE=$(($(du -s $DATA_SRC | awk '{print $1}')/1024))
if [ $SIZE -le 520 ] ; then
  zenity --info --title="Dvdisaster RS02" --width 640  --height 400 \
    --text="The data size is good for CD backup:\\n $SIZE MB"
elif [ $SIZE -le 3500 ]; then
  zenity --info --title="Dvdisaster RS02" --width 640  --height 400 \
    --text="The data size is good for DVD backup :\\n $SIZE MB"
else
  zenity --info --title="Dvdisaster RS02" --width 640  --height 400 \
    --text="The data size is too big to backup : $SIZE MB"
  error_exit "The data size is too big to backup :\\n $SIZE MB"
fi
# only xterm is sure to have working -e option
# Create raw ISO image
rm -f "$DATA_ISO" || true
xterm -T "genisoimage $DATA_ISO" \
  -e genisoimage -r -J -V "$LABEL" -o "$DATA_ISO" "$DATA_SRC"
# Create RS02 supplemental redundancy
xterm -T "dvdisaster $DATA_ISO" -e  dvdisaster -i "$DATA_ISO" -mRS02 -c
zenity --info --title="Dvdisaster RS02" --width 640  --height 400 \
  --text="ISO/RS02 data ($SIZE MB) \\n created at: $DATA_ISO"
# EOF

You may wish to create launcher on the desktop with command set something like "/usr/local/bin/gmkrs02 %d".

12.2. Make

Make is a utility to maintain groups of programs. Upon execution of make(1), make read the rule file, "Makefile", and updates a target if it depends on prerequisite files that have been modified since the target was last modified, or if the target does not exist. The execution of these updates may occur concurrently.

The rule file syntax is :

target: [ prerequisites ... ]
 [TAB]  command1
 [TAB]  -command2 # ignore errors
 [TAB]  @command3 # suppress echoing

Here " [TAB] " is a TAB code. Each line is interpreted by the shell after make variable substitution. Use "\" at the end of a line to continue the script. Use "$$" to enter "$" for environment values for a shell script.

Implicit rules for the target and prerequisites can be written, for example, as:

%.o: %.c header.h

Here, the target contains the character "%" (exactly one of them). The "%" can match any nonempty substring in the actual target filenames. The prerequisites likewise use "%" to show how their names relate to the actual target name.

表12.9 makeの自動変数のリスト。

自動変数 変数値
$@ ターゲット
$< 最初の前提条件
$? 全ての新規の前提条件
$^ 全ての前提条件
$* "%"はターゲットパターンの軸にマッチします

表12.10 make変数の展開のリスト。

変数展開 説明
foo1 := bar 一回だけの展開
foo2 = bar 再帰的展開
foo3 += bar 後ろに追加

Run "make -p -f/dev/null" to see automatic internal rules.

12.3. C

You can set up proper environment to compile programs written in the C programming language by:

# aptitude install glibc-doc manpages-dev libc6-dev gcc build-essential

The libc6-dev package, i.e., GNU C Library, provides C standard library which is collection of header files and library routines used by the C programming language.

References for C:

  • "info libc" (C library function reference)
  • gcc(1) and "info gcc"
  • each_C_library_function_name(3)
  • Kernighan &amp; Ritchie, "The C Programming Language", 2nd edition (Prentice Hall).

12.3.1. Simple C program (gcc)

A simple example "example.c" is compiled with a library "libm" into an executable "run_example":

$ cat > example.c << EOF
#include <stdio.h>
#include <math.h>
#include <string.h>

int main(int argc, char **argv, char **envp){
        double x;
        char y[11];
        x=sqrt(argc+7.5);
        strncpy(y, argv[0], 10); /* prevent buffer overflow */
        y[10] = '\0'; /* fill to make sure string ends with '\0' */
        printf("%5i, %5.3f, %10s, %10s\n", argc, x, y, argv[1]);
        return 0;
}
EOF
$ gcc -Wall -g -o run_example example.c -lm
$ ./run_example
        1, 2.915, ./run_exam,     (null)
$ ./run_example 1234567890qwerty
        2, 3.082, ./run_exam, 1234567890qwerty

Here, "-lm" is needed to link library "/usr/lib/libm.so" from the libc6 package for sqrt(3). The actual library is in "/lib/" with filename "libm.so.6", which is a symlink to "libm-2.7.so".

Look at the last parameter in the output text. There are more than 10 characters even though "%10s" is specified.

The use of pointer memory operation functions without boundary checks, such as sprintf(3) and strcpy(3), is deprecated to prevent buffer overflow exploits that leverage the above overrun effects. Instead, use snprintf(3) and strncpy(3).

12.3.2. Debugging with gdb

In order to be a good Debian user, you must be able to produce meaningful bug report using debugger. The fist step is to install gdb:

# aptitude install gdb gdb-doc build-essential devscripts

Good tutorial of gdb is provided by "info gdb" or found elsewhere on the web.

12.3.2.1. 基本的なgdb実行

Here is a simple example of using gdb(1) on a "program" compiled with the "-g" option to produce debugging information.

$ gdb program
(gdb) b 1                # set break point at line 1
(gdb) run args           # run program with args
(gdb) next               # next line
...
(gdb) step               # step forward
...
(gdb) p parm             # print parm
...
(gdb) p parm=12          # set value to 12
...
(gdb) quit
[ティップ] ティップ

Many gdb commands can be abbreviated. Tab expansion works as in the shell.

12.3.2.2. Debianパッケージのデバグ

Since all installed binaries should be stripped on the Debian system by default, most debugging symbols are removed in the normal package. In order to debug Debian packages with gdb(1), corresponding *-dbg packages need to be installed (e.g. libc6-dbg in the case of libc6).

If a package to be debugged does not provide its *-dbg package, you need to install it after rebuilding it:

$ mkdir /path/new ; cd /path/new
$ sudo aptitude update
$ sudo aptitude dist-upgrade
$ sudo aptitude install fakeroot devscripts build-essential
$ sudo apt-get build-dep source_package_name
$ apt-get source package_name
$ cd package_name*
  • fix bugs if needed.
$ dch -i
  • bump package version to one which does not collide with official Debian versions, e.g. one appended with "+debug1" when recompiling existing package version, or one appended with "~pre1" when compiling unreleased package version.
$ export DEB_BUILD_OPTIONS=nostrip,noopt
$ debuild
$ cd ..
$ sudo debi package_name*.changes

You need to check build scripts of the package and ensure to use "CFLAGS=-g -Wall" for compiling binaries.

12.3.2.3. Obtaining backtrace

When you encounter program crash, reporting bug report with cut-and-pasted backtrace information is a good idea.

The backtrace can be obtained by the following steps:

  • run the program under gdb(1),
  • reproduce crash (causing you to be dropped back to the gdb prompt), and
  • type "bt" at the gdb prompt.

In case of program freeze, you can crash the program by pressing Ctrl-C in the terminal running gdb to obtain gdb prompt.

[ティップ] ティップ

Often, you will see a backtrace where one or more of the top lines is in "malloc()" or "g_malloc()". When this happens, chances are your backtrace isn't very useful. The easiest way to find some useful information is to set the environment variable "$MALLOC_CHECK_" to a value of 2 (malloc(3)). You can do this while running gdb by doing this:

 $ MALLOC_CHECK_=2 gdb hello

12.3.2.4. Advanced gdb commands

表12.11 上級のgdbコマンドのリスト

objective commands
To get a backtrace for all threads for multi-threaded program. (gdb) thread apply all bt
To get parameters came on the stack of function calls. (gdb) bt full
To get a backtrace and parameters as the combination of the preceding options. (gdb) thread apply all bt full
To get them for top 10 calls to cut off irrelevant output. (gdb) thread apply all bt full 10
To write log of gdb output to a file (the default is gdb.txt). (gdb) set logging on

12.3.2.5. Debugging X Errors

If the GNOME program has received an X error; i.e. you see a message of the form:

The program 'preview1' received an X Window System error.

then you can try running the program with "--sync", and break on the "gdk_x_error" function in order to obtain a backtrace.

12.3.3. ライブラリーへの依存の確認

Use ldd(1) to find out a program's dependency on libraries:

$ ldd /bin/ls
        librt.so.1 => /lib/librt.so.1 (0x4001e000)
        libc.so.6 => /lib/libc.so.6 (0x40030000)
        libpthread.so.0 => /lib/libpthread.so.0 (0x40153000)
        /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)

For ls(1) to work in a `chroot`ed environment, the above libraries must be available in your `chroot`ed environment.

See also 「Trace program activities」.

12.3.4. Debugging with memory leak detection tools

There are several memory leak detection tools available in Debian.

表12.12 List of memory leak detection tools

パッケージ popcon サイズ 説明
libc6-dev V:39, I:68 11152 mtrace(1): malloc debugging functionality in glibc
valgrind V:1.2, I:6 129599 memory debugger and profiler
kmtrace V:0.19, I:1.7 324 KDE memory leak tracer using glibc's mtrace(1)
alleyoop V:0.06, I:0.4 1516 GNOME front-end to the Valgrind memory checker
electric-fence V:0.06, I:0.9 108 malloc(3) debugger
ccmalloc V:0.05, I:0.4 232 memory profiler/debugger
leaktracer V:0.01, I:0.13 116 memory-leak tracer for C++ programs
libdmalloc5 V:0.02, I:0.13 356 debug memory allocation library
mpatrolc2 V:0.00, I:0.03 3592 library for debugging memory allocations

12.3.5. Disassemble binary

You can disassemble binary code with objdump(1). For example:

$  objdump -m i386 -b binary -D /usr/lib/grub/x86_64-pc/stage1
[注意] 注意

gdb(1) may be used to disassemble code interactively.

12.3.6. Flex — a better Lex

Flex is a a Lex-compatible fast lexical analyzer generator.

Tutorial for flex(1) can be found in "info flex".

You need to provide your own "main()" and "yywrap()", or your "program.l" should look like this to compile without a library ("yywrap" is a macro; "%option main" turns on "%option noyywrap" implicitly):

%option main
%%
.|\n    ECHO ;
%%

Alternatively, you may compile with the "-lfl" linker option at the end of your cc(1) command line (like AT&T-Lex with "-ll"). No "%option" is needed in this case.

12.3.7. Bison — a better Yacc

Several packages provide a Yacc-compatible lookahead LR parser or LALR parser generator in Debian:

表12.13 List of Yacc-compatible LALR parser generators

パッケージ popcon サイズ 説明
bison V:2, I:17 1820 GNU LALR parser generator
byacc V:0.15, I:1.2 160 The Berkeley LALR parser generator
btyacc V:0.00, I:0.06 248 Backtracking parser generator based on byacc

Tutorial for bison(1) can be found in "info bison".

You need to provide your own "main()" and "yyerror()". "main()" calls "yyparse()" which calls "yylex()", usually created with Flex.

%%

%%

12.4. Autoconf

Autoconf is a tool for producing shell scripts that automatically configure software source code packages to adapt to many kinds of Unix-like systems using the entire GNU build system.

autoconf(1) produces the configuration script "configure". "configure" automatically creates a customized "Makefile" using the "Makefile.in" template.

12.4.1. Compile and install a program

[警告] 警告

Do not overwrite system files with your compiled programs when installing them.

Debian does not touch files in "/usr/local/" or "/opt". So if you compile a program from source, install it into "/usr/local/" so it will not interfere with Debian.

$ cd src
$ ./configure --prefix=/usr/local
$ make
$ make install # this puts the files in the system

12.4.2. Uninstall program

If you still have the source and if it uses autoconf(1)/automake(1) and if you can remember how you configured it:

$ ./configure ''all-of-the-options-you-gave-it''
# make uninstall

Alternatively, if you are absolutely sure that the install process puts files only under "/usr/local/" and there is nothing important there, you can erase all its contents by:

# find /usr/local -type f -print0 | xargs -0 rm -f

If you are not sure where files are installed, you should consider using checkinstall(8) from the checkinstall package, which provides a clean path for the uninstall. It now supports to create a Debian package with "-D" option.

12.5. Perl short script madness

Although any AWK scripts can be automatically rewritten in Perl using a2p(1), one-liner AWK scripts are best converted to one-liner perl scripts manually. For example

awk '($2=="1957") { print $3 }' |

is equivalent to any one of the following lines:

perl -ne '@f=split; if ($f[1] eq "1957") { print "$f[2]\n"}' |
perl -ne 'if ((@f=split)[1] eq "1957") { print "$f[2]\n"}' |
perl -ne '@f=split; print $f[2] if ( $f[1]==1957 )' |
perl -lane 'print $F[2] if $F[1] eq "1957"' |
perl -lane 'print$F[2]if$F[1]eq+1957' |

The last one is a riddle. It took advantage of the Perl features that

  • the whitespace is optional and
  • the automatic conversion from number to the string. See perlrun(1) for the command-line options. For more crazy Perl scripts, Perl Golf may be interesting.

12.6. Web

Basic interactive dynamic web pages can be made as follows:

  • Queries are presented to the browser user using HTML forms.
  • Filling and clicking on the form entries will send an URL with encoded parameters from the browser to the web server. For example:

    • "http://www.foo.dom/cgi-bin/program.pl?VAR1=VAL1&VAR2=VAL2&VAR3=VAL3"
    • "http://www.foo.dom/cgi-bin/program.py?VAR1=VAL1&VAR2=VAL2&VAR3=VAL3"
    • "http://www.foo.dom/program.php?VAR1=VAL1&VAR2=VAL2&VAR3=VAL3"
  • "%nn" in URL is replaced with a character with hexadecimal nn value.
  • The environment variable is set as: "QUERY_STRING="VAR1=VAL1 VAR2=VAL2 VAR3=VAL3""
  • CGI program (any one of "program.*") on the web server executes itself with the environment variable "$QUERY_STRING".
  • stdout of CGI program will be sent to the web browser and is presented as an interactive dynamic web page.

For security reasons it is better not to hand craft new hacks for parsing CGI parameters. There are established modules for them in Perl and Python. PHP comes with these functionalities. When client data storage is needed, cookies are used. When client side data processing is needed, javascript is frequently used.

For more, see The Common Gateway Interface, The Apache Software Foundation, and JavaScript.

Searching "CGI tutorial" on Google by typing encoded URL http://www.google.com/search?hl=en&ie=UTF-8&q=CGI+tutorial directly to the browser address is a good way to see the CGI script in action on the Google server.

12.7. Static code analysis tools

There are lint like tools for static code analysis:

表12.14 静的コード分析ツールのリスト。

パッケージ popcon サイズ 説明
splint V:0.06, I:0.5 1836 A tool for statically checking C programs for bugs
rats V:0.06, I:0.2 768 Rough Auditing Tool for Security (C, C++, PHP, Perl, and Python code)
flawfinder V:0.03, I:0.2 192 A tool to examine C/C++ source code and looks for security weaknesses
perl V:89, I:99 18824 This package has internal code static checker: B::Lint(3perl)
pylint V:0.10, I:0.5 688 A python code static checker
jlint V:0.01, I:0.10 184 A Java program checker
weblint-perl V:0.14, I:0.8 64 A syntax and minimal style checker for HTML
linklint V:0.06, I:0.3 432 A fast link checker and web site maintenance tool
libxml2-utils V:5, I:53 120 This package provides xmllint(1) to validate XML files

12.8. ソースコード変換

ソースコード変換するプログラムがあります。

表12.15 ソースコードの変換ツールのリスト。

パッケージ popcon サイズ keyword 説明
perl V:89, I:99 18824 AWK→PERL a2p(1) converts source codes from AWK to PERL.
f2c V:0.17, I:1.1 440 FORTRAN→C f2c(1) converts source codes from A FORTRAN 77 to C/C++.
protoize V:0.01, I:0.07 172 ANSI C Create/remove ANSI prototypes from C code.
intel2gas V:0.01, I:0.08 344 intel→gas The converter from NASM (intel format) to the GNU Assembler (GAS).

12.9. Debianパッケージ作成

Debianパッケージを作りたい場合には、次を読みましょう:

dh-makedh-make-perl等のようなパッケージングを補助するパッケージもあります。

付録A 補遺

以下が本文書の背景です。

A.1. Debian迷路

Linuxシステムはネットワーク化されたコンピュータのための非常にパワフルなコンピュータプラットフォームです。しかし、Linuxの全能力を利用する方法を学ぶことはたやすいことではありません。非PostScriptプリンタが接続されたLPRプリンタの設定がこんなつまずく点の良い例でした。(新しいインストレーションではCUPSシステムが使われるのでもうこの様な問題はありません。)

"ソースコード"という完全かつ詳細なマップが存在します。これは非常に正確ですが理解することが難しいものです。また、HOWTOやmini-HOWTOと呼ばれるリファレンスもあります。これらは理解はしやすいのですが、詳細過ぎて全体像を失いがちです。ちょっとコマンドを実行する必要がある時に、長大なHOWTOの該当する章を探すのには骨が折れることが時々あります。

この"Debianリファレンス(第2版)"がDebian迷路の真っ只中にいる皆様にとって解決の糸口となることを望みます。

A.2. 著作権の経緯

Debianリファレンスは青木 修 <osamu at debian dot org> が自分のためのシステム管理メモとして書きはじめました。多くの内容がdebian-user メーリングリストや他のDebian のリソースから得られた知識由来です。

当時 Debian Documentation Projectで非常にアクティブであった、Josip Rodin氏の助言に従い、 DDP文書の一部として"Debianリファレンス(第1版、2001-2007)"を作りました。

6年経った時点で、青木はオリジナルの "Debianリファレンス(第1版、2001-2007)" が時代遅れとなっている事に気づき多くの内容を書き換え始めました。新たな "Debianリファレンス(第2版)" が2008年にリリースされました。

チュートリアルの内容はその内容とインスピレーションを次から得ました。

  • "Linux User's Guide" Larry Greenfield 著。 (1996年12月)

    • "Debian Tutorial"によって時代遅れとなりました。
  • "Debian Tutorial" Havoc Pennington著。 (1998年12年11日)

    • 内容の一部はOliver ElphickとOle TetlieとJames TreacyとCraig SawyerとIvan E. Moore IIによって書かれました。
    • "Debian GNU/Linux: Guide to Installation and Usage"によって時代遅れとなりました。
  • "Debian GNU/Linux: Guide to Installation and Usage" John Goerzen and Ossama Othman著。 (1999年)

    • "Debianリファレンス(第1版)"によって時代遅れとなりました。

パッケージやアーカイブに関する記述はそのオリジンやインスピレーションの一部を次に遡ることができます:

  • "Debian FAQ" (Josip Rodinが維持していた2002年3月版)

他の内容はそのオリジンやインスピレーションを次に遡ることができます:

  • "Debianリファレンス (第1版)" 青木 修著 (2001年〜2007年)

    • この新しい "Debianリファレンス(第2版)"によって時代遅れとなりました。

以前の "Debianリファレンス(第1版)" は次によって作られました,

  • ネットワークコンフィギュレーションに関する大部分の内容はThomas Hoodが寄稿、
  • X と VCS に関連するかなりの内容は Brian Nelson が寄稿、
  • ビルドスクリプトや多くの内容に関する訂正で Jens Seidel が寄与,
  • David Sewell による徹底的な校正と、
  • 翻訳者やコントリビューターやバグ報告者達による多くの寄与。

Debianシステム上の多くのマニュアルページやinfoページが本文書を書く上での第一義的参照情報として使われました。青木 修が公正な使用と考える範囲内で、それらの多くの部分、特にコマンドの定義が、本文書の文体と目的に合うように注意深い編集をした後、断片的文言として使われました。

gdbデバッガーに関する記述はArii PollakとLoïc MinierとDafydd Harriesの了承のもとbacktraceに関するDebian wikiの内容を拡張して使いました。

既に上記で触れた項目を除くほとんどの"Debianリファレンス(第2版)"の内容は私自身の仕事です。これらはコントリビュータ−によっても更新されています。

著者である青木 修は本文書を世に送ることにご助力戴いた皆様に感謝いたします。

A.3. 文書のフォーマット

英語のオリジナル文書のソースはAsciiDocのテキストファイルを用いて書かれました。これを使うと生のXMLのテキストよりタイプすることが少なくて済み、また非常に分かりやすいフォーマットで表をサポートできます。ビルドスクリプトによってDocBook XMLソースに変換され、更に自動的に生成されるデータを埋め込み最終的なDocBook XMLソースとされました。本文書はHTML,plaintext,PostScriptと,PDFとして見ることができます。現在はHTMLとplaintextへの変換のみが有効とされています。