SSH簡易クライアント
paramikoでSSH接続しコマンドを実行して出力を表示するシンプルSSHクライアント。接続情報の保存機能付き。
1. アプリ概要
paramikoでSSH接続しコマンドを実行して出力を表示するシンプルSSHクライアント。接続情報の保存機能付き。
このアプリはutilカテゴリの実践的なPythonアプリです。使用ライブラリは tkinter(標準ライブラリ)・paramiko、難易度は ★★★ です。
Pythonの豊富なライブラリを活用することで、実用的なアプリを短いコードで実装できます。ソースコードをコピーして実行し、仕組みを理解したうえでカスタマイズに挑戦してみてください。
GUIアプリ開発はプログラミングの楽しさを実感できる最も効果的な学習方法のひとつです。変数・関数・クラス・イベント処理などの重要な概念が自然と身につきます。
2. 機能一覧
- SSH簡易クライアントのメイン機能
- 直感的なGUIインターフェース
- 入力値のバリデーション
- エラーハンドリング
- 結果の見やすい表示
- クリア機能付き
3. 事前準備・環境
Python 3.10 以上 / Windows・Mac・Linux すべて対応
以下の環境で動作確認しています。
- Python 3.10 以上
- OS: Windows 10/11・macOS 12+・Ubuntu 20.04+
4. 完全なソースコード
右上の「コピー」ボタンをクリックするとコードをクリップボードにコピーできます。
import tkinter as tk
from tkinter import ttk, messagebox
import threading
import json
import os
try:
import paramiko
PARAMIKO_AVAILABLE = True
except ImportError:
PARAMIKO_AVAILABLE = False
SAVE_PATH = os.path.join(os.path.dirname(__file__), "ssh_hosts.json")
class App096:
"""SSH簡易クライアント"""
def __init__(self, root):
self.root = root
self.root.title("SSH簡易クライアント")
self.root.geometry("1000x640")
self.root.configure(bg="#0d1117")
self._client = None
self._channel = None
self._hosts = []
self._history = []
self._build_ui()
self._load_hosts()
self.root.protocol("WM_DELETE_WINDOW", self._on_close)
def _build_ui(self):
header = tk.Frame(self.root, bg="#161b22", pady=6)
header.pack(fill=tk.X)
tk.Label(header, text="🔐 SSH簡易クライアント",
font=("Noto Sans JP", 12, "bold"),
bg="#161b22", fg="#4fc3f7").pack(side=tk.LEFT, padx=12)
if not PARAMIKO_AVAILABLE:
tk.Label(self.root,
text="⚠ paramiko が未インストールです (pip install paramiko)",
bg="#fff3cd", fg="#856404", font=("Arial", 9),
anchor="w", padx=8).pack(fill=tk.X)
# 接続設定
conn_f = tk.LabelFrame(self.root, text="接続設定", bg="#161b22",
fg="#ccc", font=("Arial", 9), padx=8, pady=4)
conn_f.pack(fill=tk.X, padx=8, pady=4)
tk.Label(conn_f, text="ホスト:", bg="#161b22", fg="#ccc",
font=("Arial", 9)).grid(row=0, column=0, sticky="w")
self.host_var = tk.StringVar(value="localhost")
ttk.Entry(conn_f, textvariable=self.host_var, width=20).grid(
row=0, column=1, padx=4)
tk.Label(conn_f, text="ポート:", bg="#161b22", fg="#ccc",
font=("Arial", 9)).grid(row=0, column=2, sticky="w", padx=(8, 0))
self.port_var = tk.IntVar(value=22)
ttk.Entry(conn_f, textvariable=self.port_var, width=6).grid(
row=0, column=3, padx=4)
tk.Label(conn_f, text="ユーザー:", bg="#161b22", fg="#ccc",
font=("Arial", 9)).grid(row=0, column=4, sticky="w", padx=(8, 0))
self.user_var = tk.StringVar(value="root")
ttk.Entry(conn_f, textvariable=self.user_var, width=12).grid(
row=0, column=5, padx=4)
tk.Label(conn_f, text="パスワード:", bg="#161b22", fg="#ccc",
font=("Arial", 9)).grid(row=0, column=6, sticky="w", padx=(8, 0))
self.pass_var = tk.StringVar()
ttk.Entry(conn_f, textvariable=self.pass_var, width=14,
show="*").grid(row=0, column=7, padx=4)
tk.Button(conn_f, text="接続", command=self._connect,
bg="#1565c0", fg="white", relief=tk.FLAT,
font=("Arial", 9, "bold"), padx=10,
activebackground="#0d47a1", bd=0).grid(row=0, column=8, padx=4)
tk.Button(conn_f, text="切断", command=self._disconnect,
bg="#c62828", fg="white", relief=tk.FLAT,
font=("Arial", 9), padx=10,
activebackground="#b71c1c", bd=0).grid(row=0, column=9, padx=2)
# ホスト保存ボタン
ttk.Button(conn_f, text="💾 ホスト保存",
command=self._save_host).grid(row=0, column=10, padx=8)
# メインエリア
paned = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL)
paned.pack(fill=tk.BOTH, expand=True, padx=4, pady=2)
# 左: ホスト一覧 + ショートカット
left = tk.Frame(paned, bg="#161b22", width=220)
paned.add(left, weight=0)
tk.Label(left, text="保存済みホスト", bg="#161b22", fg="#8b949e",
font=("Arial", 8)).pack(anchor="w", padx=4)
self.host_listbox = tk.Listbox(left, bg="#0d1117", fg="#c9d1d9",
selectbackground="#1f6feb",
font=("Arial", 8), relief=tk.FLAT)
hlsb = ttk.Scrollbar(left, command=self.host_listbox.yview)
self.host_listbox.configure(yscrollcommand=hlsb.set)
hlsb.pack(side=tk.RIGHT, fill=tk.Y)
self.host_listbox.pack(fill=tk.BOTH, expand=True)
self.host_listbox.bind("<Double-1>", self._load_selected_host)
btn_row = tk.Frame(left, bg="#161b22")
btn_row.pack(fill=tk.X, pady=2)
ttk.Button(btn_row, text="読み込み",
command=self._load_selected_host).pack(side=tk.LEFT, padx=2)
ttk.Button(btn_row, text="削除",
command=self._delete_host).pack(side=tk.LEFT, padx=2)
# クイックコマンド
tk.Label(left, text="クイックコマンド", bg="#161b22", fg="#8b949e",
font=("Arial", 8)).pack(anchor="w", padx=4, pady=(8, 0))
quick_cmds = ["ls -la", "pwd", "df -h", "free -h", "top -bn1 | head -20",
"ps aux | head -20", "cat /etc/os-release", "uname -a",
"ifconfig || ip addr", "netstat -tlnp 2>/dev/null | head -20"]
self.cmd_listbox = tk.Listbox(left, bg="#0d1117", fg="#c9d1d9",
selectbackground="#1f6feb",
font=("Courier New", 7), relief=tk.FLAT,
height=10)
for cmd in quick_cmds:
self.cmd_listbox.insert(tk.END, cmd)
clsb = ttk.Scrollbar(left, command=self.cmd_listbox.yview)
self.cmd_listbox.configure(yscrollcommand=clsb.set)
clsb.pack(side=tk.RIGHT, fill=tk.Y)
self.cmd_listbox.pack(fill=tk.BOTH, expand=True)
self.cmd_listbox.bind("<Double-1>", self._run_quick_cmd)
# 右: ターミナル
right = tk.Frame(paned, bg="#0d1117")
paned.add(right, weight=1)
tk.Label(right, text="ターミナル", bg="#0d1117", fg="#8b949e",
font=("Arial", 8)).pack(anchor="w", padx=4)
self.terminal = tk.Text(right, bg="#0d1117", fg="#c9d1d9",
font=("Courier New", 9), relief=tk.FLAT,
state=tk.DISABLED, wrap=tk.NONE)
txsb = ttk.Scrollbar(right, orient=tk.VERTICAL,
command=self.terminal.yview)
self.terminal.configure(yscrollcommand=txsb.set)
txsb.pack(side=tk.RIGHT, fill=tk.Y)
self.terminal.pack(fill=tk.BOTH, expand=True)
self.terminal.tag_configure("prompt", foreground="#4fc3f7")
self.terminal.tag_configure("output", foreground="#c9d1d9")
self.terminal.tag_configure("error", foreground="#ef5350")
self.terminal.tag_configure("info", foreground="#8b949e")
# コマンド入力バー
input_f = tk.Frame(right, bg="#161b22")
input_f.pack(fill=tk.X, pady=2)
tk.Label(input_f, text="$", bg="#161b22", fg="#4fc3f7",
font=("Courier New", 10, "bold")).pack(side=tk.LEFT, padx=4)
self.cmd_var = tk.StringVar()
self.cmd_entry = ttk.Entry(input_f, textvariable=self.cmd_var,
font=("Courier New", 10))
self.cmd_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=4)
self.cmd_entry.bind("<Return>", lambda e: self._run_cmd())
self.cmd_entry.bind("<Up>", lambda e: self._history_up())
self.cmd_entry.bind("<Down>", lambda e: self._history_down())
ttk.Button(input_f, text="実行",
command=self._run_cmd).pack(side=tk.LEFT, padx=4)
self._hist_idx = -1
self.status_var = tk.StringVar(value="未接続")
tk.Label(self.root, textvariable=self.status_var,
bg="#21262d", fg="#8b949e", font=("Arial", 9),
anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)
def _append_terminal(self, text, tag="output"):
self.terminal.configure(state=tk.NORMAL)
self.terminal.insert(tk.END, text, tag)
self.terminal.see(tk.END)
self.terminal.configure(state=tk.DISABLED)
def _connect(self):
if not PARAMIKO_AVAILABLE:
messagebox.showerror("エラー", "pip install paramiko")
return
if self._client:
self._disconnect()
host = self.host_var.get().strip()
port = self.port_var.get()
user = self.user_var.get().strip()
pwd = self.pass_var.get()
self.status_var.set(f"接続中... {user}@{host}:{port}")
threading.Thread(
target=self._do_connect,
args=(host, port, user, pwd),
daemon=True).start()
def _do_connect(self, host, port, user, pwd):
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, port=port, username=user, password=pwd,
timeout=10)
self._client = client
self.root.after(0, self._append_terminal,
f"✔ 接続しました: {user}@{host}:{port}\n", "info")
self.root.after(0, self.status_var.set,
f"接続済: {user}@{host}:{port}")
except Exception as e:
self.root.after(0, self._append_terminal,
f"✘ 接続失敗: {e}\n", "error")
self.root.after(0, self.status_var.set, f"接続失敗: {e}")
def _disconnect(self):
if self._client:
try:
self._client.close()
except Exception:
pass
self._client = None
self.status_var.set("切断済")
self._append_terminal("切断しました\n", "info")
def _run_cmd(self):
cmd = self.cmd_var.get().strip()
if not cmd:
return
self.cmd_var.set("")
self._history.insert(0, cmd)
self._hist_idx = -1
self._append_terminal(f"$ {cmd}\n", "prompt")
if not self._client:
self._append_terminal(
"エラー: 接続されていません。先にSSH接続してください。\n", "error")
return
threading.Thread(target=self._do_run, args=(cmd,), daemon=True).start()
def _do_run(self, cmd):
try:
stdin, stdout, stderr = self._client.exec_command(cmd, timeout=30)
out = stdout.read().decode("utf-8", errors="replace")
err = stderr.read().decode("utf-8", errors="replace")
if out:
self.root.after(0, self._append_terminal, out, "output")
if err:
self.root.after(0, self._append_terminal, err, "error")
except Exception as e:
self.root.after(0, self._append_terminal, f"エラー: {e}\n", "error")
def _run_quick_cmd(self, _=None):
sel = self.cmd_listbox.curselection()
if sel:
cmd = self.cmd_listbox.get(sel[0])
self.cmd_var.set(cmd)
self._run_cmd()
def _history_up(self):
if self._history:
self._hist_idx = min(self._hist_idx + 1, len(self._history) - 1)
self.cmd_var.set(self._history[self._hist_idx])
def _history_down(self):
if self._hist_idx > 0:
self._hist_idx -= 1
self.cmd_var.set(self._history[self._hist_idx])
else:
self._hist_idx = -1
self.cmd_var.set("")
def _save_host(self):
host = {
"host": self.host_var.get(),
"port": self.port_var.get(),
"user": self.user_var.get(),
"label": f"{self.user_var.get()}@{self.host_var.get()}:{self.port_var.get()}",
}
self._hosts.append(host)
self.host_listbox.insert(tk.END, host["label"])
self._persist_hosts()
def _load_selected_host(self, _=None):
sel = self.host_listbox.curselection()
if not sel or sel[0] >= len(self._hosts):
return
h = self._hosts[sel[0]]
self.host_var.set(h["host"])
self.port_var.set(h["port"])
self.user_var.set(h["user"])
def _delete_host(self):
sel = self.host_listbox.curselection()
if not sel:
return
idx = sel[0]
if idx < len(self._hosts):
del self._hosts[idx]
self.host_listbox.delete(idx)
self._persist_hosts()
def _persist_hosts(self):
try:
with open(SAVE_PATH, "w", encoding="utf-8") as f:
json.dump(self._hosts, f, ensure_ascii=False, indent=2)
except Exception:
pass
def _load_hosts(self):
if os.path.exists(SAVE_PATH):
try:
with open(SAVE_PATH, encoding="utf-8") as f:
self._hosts = json.load(f)
for h in self._hosts:
self.host_listbox.insert(tk.END, h.get("label", ""))
except Exception:
self._hosts = []
def _on_close(self):
self._disconnect()
self.root.destroy()
if __name__ == "__main__":
root = tk.Tk()
app = App096(root)
root.mainloop()
5. コード解説
SSH簡易クライアントのコードを詳しく解説します。クラスベースの設計で各機能を整理して実装しています。
クラス設計とコンストラクタ
App096クラスにアプリの全機能をまとめています。__init__でウィンドウ設定、_build_ui()でUI構築、process()でメイン処理を担当します。責任の分離により、コードが読みやすくなります。
import tkinter as tk
from tkinter import ttk, messagebox
import threading
import json
import os
try:
import paramiko
PARAMIKO_AVAILABLE = True
except ImportError:
PARAMIKO_AVAILABLE = False
SAVE_PATH = os.path.join(os.path.dirname(__file__), "ssh_hosts.json")
class App096:
"""SSH簡易クライアント"""
def __init__(self, root):
self.root = root
self.root.title("SSH簡易クライアント")
self.root.geometry("1000x640")
self.root.configure(bg="#0d1117")
self._client = None
self._channel = None
self._hosts = []
self._history = []
self._build_ui()
self._load_hosts()
self.root.protocol("WM_DELETE_WINDOW", self._on_close)
def _build_ui(self):
header = tk.Frame(self.root, bg="#161b22", pady=6)
header.pack(fill=tk.X)
tk.Label(header, text="🔐 SSH簡易クライアント",
font=("Noto Sans JP", 12, "bold"),
bg="#161b22", fg="#4fc3f7").pack(side=tk.LEFT, padx=12)
if not PARAMIKO_AVAILABLE:
tk.Label(self.root,
text="⚠ paramiko が未インストールです (pip install paramiko)",
bg="#fff3cd", fg="#856404", font=("Arial", 9),
anchor="w", padx=8).pack(fill=tk.X)
# 接続設定
conn_f = tk.LabelFrame(self.root, text="接続設定", bg="#161b22",
fg="#ccc", font=("Arial", 9), padx=8, pady=4)
conn_f.pack(fill=tk.X, padx=8, pady=4)
tk.Label(conn_f, text="ホスト:", bg="#161b22", fg="#ccc",
font=("Arial", 9)).grid(row=0, column=0, sticky="w")
self.host_var = tk.StringVar(value="localhost")
ttk.Entry(conn_f, textvariable=self.host_var, width=20).grid(
row=0, column=1, padx=4)
tk.Label(conn_f, text="ポート:", bg="#161b22", fg="#ccc",
font=("Arial", 9)).grid(row=0, column=2, sticky="w", padx=(8, 0))
self.port_var = tk.IntVar(value=22)
ttk.Entry(conn_f, textvariable=self.port_var, width=6).grid(
row=0, column=3, padx=4)
tk.Label(conn_f, text="ユーザー:", bg="#161b22", fg="#ccc",
font=("Arial", 9)).grid(row=0, column=4, sticky="w", padx=(8, 0))
self.user_var = tk.StringVar(value="root")
ttk.Entry(conn_f, textvariable=self.user_var, width=12).grid(
row=0, column=5, padx=4)
tk.Label(conn_f, text="パスワード:", bg="#161b22", fg="#ccc",
font=("Arial", 9)).grid(row=0, column=6, sticky="w", padx=(8, 0))
self.pass_var = tk.StringVar()
ttk.Entry(conn_f, textvariable=self.pass_var, width=14,
show="*").grid(row=0, column=7, padx=4)
tk.Button(conn_f, text="接続", command=self._connect,
bg="#1565c0", fg="white", relief=tk.FLAT,
font=("Arial", 9, "bold"), padx=10,
activebackground="#0d47a1", bd=0).grid(row=0, column=8, padx=4)
tk.Button(conn_f, text="切断", command=self._disconnect,
bg="#c62828", fg="white", relief=tk.FLAT,
font=("Arial", 9), padx=10,
activebackground="#b71c1c", bd=0).grid(row=0, column=9, padx=2)
# ホスト保存ボタン
ttk.Button(conn_f, text="💾 ホスト保存",
command=self._save_host).grid(row=0, column=10, padx=8)
# メインエリア
paned = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL)
paned.pack(fill=tk.BOTH, expand=True, padx=4, pady=2)
# 左: ホスト一覧 + ショートカット
left = tk.Frame(paned, bg="#161b22", width=220)
paned.add(left, weight=0)
tk.Label(left, text="保存済みホスト", bg="#161b22", fg="#8b949e",
font=("Arial", 8)).pack(anchor="w", padx=4)
self.host_listbox = tk.Listbox(left, bg="#0d1117", fg="#c9d1d9",
selectbackground="#1f6feb",
font=("Arial", 8), relief=tk.FLAT)
hlsb = ttk.Scrollbar(left, command=self.host_listbox.yview)
self.host_listbox.configure(yscrollcommand=hlsb.set)
hlsb.pack(side=tk.RIGHT, fill=tk.Y)
self.host_listbox.pack(fill=tk.BOTH, expand=True)
self.host_listbox.bind("<Double-1>", self._load_selected_host)
btn_row = tk.Frame(left, bg="#161b22")
btn_row.pack(fill=tk.X, pady=2)
ttk.Button(btn_row, text="読み込み",
command=self._load_selected_host).pack(side=tk.LEFT, padx=2)
ttk.Button(btn_row, text="削除",
command=self._delete_host).pack(side=tk.LEFT, padx=2)
# クイックコマンド
tk.Label(left, text="クイックコマンド", bg="#161b22", fg="#8b949e",
font=("Arial", 8)).pack(anchor="w", padx=4, pady=(8, 0))
quick_cmds = ["ls -la", "pwd", "df -h", "free -h", "top -bn1 | head -20",
"ps aux | head -20", "cat /etc/os-release", "uname -a",
"ifconfig || ip addr", "netstat -tlnp 2>/dev/null | head -20"]
self.cmd_listbox = tk.Listbox(left, bg="#0d1117", fg="#c9d1d9",
selectbackground="#1f6feb",
font=("Courier New", 7), relief=tk.FLAT,
height=10)
for cmd in quick_cmds:
self.cmd_listbox.insert(tk.END, cmd)
clsb = ttk.Scrollbar(left, command=self.cmd_listbox.yview)
self.cmd_listbox.configure(yscrollcommand=clsb.set)
clsb.pack(side=tk.RIGHT, fill=tk.Y)
self.cmd_listbox.pack(fill=tk.BOTH, expand=True)
self.cmd_listbox.bind("<Double-1>", self._run_quick_cmd)
# 右: ターミナル
right = tk.Frame(paned, bg="#0d1117")
paned.add(right, weight=1)
tk.Label(right, text="ターミナル", bg="#0d1117", fg="#8b949e",
font=("Arial", 8)).pack(anchor="w", padx=4)
self.terminal = tk.Text(right, bg="#0d1117", fg="#c9d1d9",
font=("Courier New", 9), relief=tk.FLAT,
state=tk.DISABLED, wrap=tk.NONE)
txsb = ttk.Scrollbar(right, orient=tk.VERTICAL,
command=self.terminal.yview)
self.terminal.configure(yscrollcommand=txsb.set)
txsb.pack(side=tk.RIGHT, fill=tk.Y)
self.terminal.pack(fill=tk.BOTH, expand=True)
self.terminal.tag_configure("prompt", foreground="#4fc3f7")
self.terminal.tag_configure("output", foreground="#c9d1d9")
self.terminal.tag_configure("error", foreground="#ef5350")
self.terminal.tag_configure("info", foreground="#8b949e")
# コマンド入力バー
input_f = tk.Frame(right, bg="#161b22")
input_f.pack(fill=tk.X, pady=2)
tk.Label(input_f, text="$", bg="#161b22", fg="#4fc3f7",
font=("Courier New", 10, "bold")).pack(side=tk.LEFT, padx=4)
self.cmd_var = tk.StringVar()
self.cmd_entry = ttk.Entry(input_f, textvariable=self.cmd_var,
font=("Courier New", 10))
self.cmd_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=4)
self.cmd_entry.bind("<Return>", lambda e: self._run_cmd())
self.cmd_entry.bind("<Up>", lambda e: self._history_up())
self.cmd_entry.bind("<Down>", lambda e: self._history_down())
ttk.Button(input_f, text="実行",
command=self._run_cmd).pack(side=tk.LEFT, padx=4)
self._hist_idx = -1
self.status_var = tk.StringVar(value="未接続")
tk.Label(self.root, textvariable=self.status_var,
bg="#21262d", fg="#8b949e", font=("Arial", 9),
anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)
def _append_terminal(self, text, tag="output"):
self.terminal.configure(state=tk.NORMAL)
self.terminal.insert(tk.END, text, tag)
self.terminal.see(tk.END)
self.terminal.configure(state=tk.DISABLED)
def _connect(self):
if not PARAMIKO_AVAILABLE:
messagebox.showerror("エラー", "pip install paramiko")
return
if self._client:
self._disconnect()
host = self.host_var.get().strip()
port = self.port_var.get()
user = self.user_var.get().strip()
pwd = self.pass_var.get()
self.status_var.set(f"接続中... {user}@{host}:{port}")
threading.Thread(
target=self._do_connect,
args=(host, port, user, pwd),
daemon=True).start()
def _do_connect(self, host, port, user, pwd):
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, port=port, username=user, password=pwd,
timeout=10)
self._client = client
self.root.after(0, self._append_terminal,
f"✔ 接続しました: {user}@{host}:{port}\n", "info")
self.root.after(0, self.status_var.set,
f"接続済: {user}@{host}:{port}")
except Exception as e:
self.root.after(0, self._append_terminal,
f"✘ 接続失敗: {e}\n", "error")
self.root.after(0, self.status_var.set, f"接続失敗: {e}")
def _disconnect(self):
if self._client:
try:
self._client.close()
except Exception:
pass
self._client = None
self.status_var.set("切断済")
self._append_terminal("切断しました\n", "info")
def _run_cmd(self):
cmd = self.cmd_var.get().strip()
if not cmd:
return
self.cmd_var.set("")
self._history.insert(0, cmd)
self._hist_idx = -1
self._append_terminal(f"$ {cmd}\n", "prompt")
if not self._client:
self._append_terminal(
"エラー: 接続されていません。先にSSH接続してください。\n", "error")
return
threading.Thread(target=self._do_run, args=(cmd,), daemon=True).start()
def _do_run(self, cmd):
try:
stdin, stdout, stderr = self._client.exec_command(cmd, timeout=30)
out = stdout.read().decode("utf-8", errors="replace")
err = stderr.read().decode("utf-8", errors="replace")
if out:
self.root.after(0, self._append_terminal, out, "output")
if err:
self.root.after(0, self._append_terminal, err, "error")
except Exception as e:
self.root.after(0, self._append_terminal, f"エラー: {e}\n", "error")
def _run_quick_cmd(self, _=None):
sel = self.cmd_listbox.curselection()
if sel:
cmd = self.cmd_listbox.get(sel[0])
self.cmd_var.set(cmd)
self._run_cmd()
def _history_up(self):
if self._history:
self._hist_idx = min(self._hist_idx + 1, len(self._history) - 1)
self.cmd_var.set(self._history[self._hist_idx])
def _history_down(self):
if self._hist_idx > 0:
self._hist_idx -= 1
self.cmd_var.set(self._history[self._hist_idx])
else:
self._hist_idx = -1
self.cmd_var.set("")
def _save_host(self):
host = {
"host": self.host_var.get(),
"port": self.port_var.get(),
"user": self.user_var.get(),
"label": f"{self.user_var.get()}@{self.host_var.get()}:{self.port_var.get()}",
}
self._hosts.append(host)
self.host_listbox.insert(tk.END, host["label"])
self._persist_hosts()
def _load_selected_host(self, _=None):
sel = self.host_listbox.curselection()
if not sel or sel[0] >= len(self._hosts):
return
h = self._hosts[sel[0]]
self.host_var.set(h["host"])
self.port_var.set(h["port"])
self.user_var.set(h["user"])
def _delete_host(self):
sel = self.host_listbox.curselection()
if not sel:
return
idx = sel[0]
if idx < len(self._hosts):
del self._hosts[idx]
self.host_listbox.delete(idx)
self._persist_hosts()
def _persist_hosts(self):
try:
with open(SAVE_PATH, "w", encoding="utf-8") as f:
json.dump(self._hosts, f, ensure_ascii=False, indent=2)
except Exception:
pass
def _load_hosts(self):
if os.path.exists(SAVE_PATH):
try:
with open(SAVE_PATH, encoding="utf-8") as f:
self._hosts = json.load(f)
for h in self._hosts:
self.host_listbox.insert(tk.END, h.get("label", ""))
except Exception:
self._hosts = []
def _on_close(self):
self._disconnect()
self.root.destroy()
if __name__ == "__main__":
root = tk.Tk()
app = App096(root)
root.mainloop()
UIレイアウトの構築
LabelFrameで入力エリアと結果エリアを視覚的に分けています。pack()で縦に並べ、expand=Trueで結果エリアが画面いっぱいに広がるよう設定しています。
import tkinter as tk
from tkinter import ttk, messagebox
import threading
import json
import os
try:
import paramiko
PARAMIKO_AVAILABLE = True
except ImportError:
PARAMIKO_AVAILABLE = False
SAVE_PATH = os.path.join(os.path.dirname(__file__), "ssh_hosts.json")
class App096:
"""SSH簡易クライアント"""
def __init__(self, root):
self.root = root
self.root.title("SSH簡易クライアント")
self.root.geometry("1000x640")
self.root.configure(bg="#0d1117")
self._client = None
self._channel = None
self._hosts = []
self._history = []
self._build_ui()
self._load_hosts()
self.root.protocol("WM_DELETE_WINDOW", self._on_close)
def _build_ui(self):
header = tk.Frame(self.root, bg="#161b22", pady=6)
header.pack(fill=tk.X)
tk.Label(header, text="🔐 SSH簡易クライアント",
font=("Noto Sans JP", 12, "bold"),
bg="#161b22", fg="#4fc3f7").pack(side=tk.LEFT, padx=12)
if not PARAMIKO_AVAILABLE:
tk.Label(self.root,
text="⚠ paramiko が未インストールです (pip install paramiko)",
bg="#fff3cd", fg="#856404", font=("Arial", 9),
anchor="w", padx=8).pack(fill=tk.X)
# 接続設定
conn_f = tk.LabelFrame(self.root, text="接続設定", bg="#161b22",
fg="#ccc", font=("Arial", 9), padx=8, pady=4)
conn_f.pack(fill=tk.X, padx=8, pady=4)
tk.Label(conn_f, text="ホスト:", bg="#161b22", fg="#ccc",
font=("Arial", 9)).grid(row=0, column=0, sticky="w")
self.host_var = tk.StringVar(value="localhost")
ttk.Entry(conn_f, textvariable=self.host_var, width=20).grid(
row=0, column=1, padx=4)
tk.Label(conn_f, text="ポート:", bg="#161b22", fg="#ccc",
font=("Arial", 9)).grid(row=0, column=2, sticky="w", padx=(8, 0))
self.port_var = tk.IntVar(value=22)
ttk.Entry(conn_f, textvariable=self.port_var, width=6).grid(
row=0, column=3, padx=4)
tk.Label(conn_f, text="ユーザー:", bg="#161b22", fg="#ccc",
font=("Arial", 9)).grid(row=0, column=4, sticky="w", padx=(8, 0))
self.user_var = tk.StringVar(value="root")
ttk.Entry(conn_f, textvariable=self.user_var, width=12).grid(
row=0, column=5, padx=4)
tk.Label(conn_f, text="パスワード:", bg="#161b22", fg="#ccc",
font=("Arial", 9)).grid(row=0, column=6, sticky="w", padx=(8, 0))
self.pass_var = tk.StringVar()
ttk.Entry(conn_f, textvariable=self.pass_var, width=14,
show="*").grid(row=0, column=7, padx=4)
tk.Button(conn_f, text="接続", command=self._connect,
bg="#1565c0", fg="white", relief=tk.FLAT,
font=("Arial", 9, "bold"), padx=10,
activebackground="#0d47a1", bd=0).grid(row=0, column=8, padx=4)
tk.Button(conn_f, text="切断", command=self._disconnect,
bg="#c62828", fg="white", relief=tk.FLAT,
font=("Arial", 9), padx=10,
activebackground="#b71c1c", bd=0).grid(row=0, column=9, padx=2)
# ホスト保存ボタン
ttk.Button(conn_f, text="💾 ホスト保存",
command=self._save_host).grid(row=0, column=10, padx=8)
# メインエリア
paned = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL)
paned.pack(fill=tk.BOTH, expand=True, padx=4, pady=2)
# 左: ホスト一覧 + ショートカット
left = tk.Frame(paned, bg="#161b22", width=220)
paned.add(left, weight=0)
tk.Label(left, text="保存済みホスト", bg="#161b22", fg="#8b949e",
font=("Arial", 8)).pack(anchor="w", padx=4)
self.host_listbox = tk.Listbox(left, bg="#0d1117", fg="#c9d1d9",
selectbackground="#1f6feb",
font=("Arial", 8), relief=tk.FLAT)
hlsb = ttk.Scrollbar(left, command=self.host_listbox.yview)
self.host_listbox.configure(yscrollcommand=hlsb.set)
hlsb.pack(side=tk.RIGHT, fill=tk.Y)
self.host_listbox.pack(fill=tk.BOTH, expand=True)
self.host_listbox.bind("<Double-1>", self._load_selected_host)
btn_row = tk.Frame(left, bg="#161b22")
btn_row.pack(fill=tk.X, pady=2)
ttk.Button(btn_row, text="読み込み",
command=self._load_selected_host).pack(side=tk.LEFT, padx=2)
ttk.Button(btn_row, text="削除",
command=self._delete_host).pack(side=tk.LEFT, padx=2)
# クイックコマンド
tk.Label(left, text="クイックコマンド", bg="#161b22", fg="#8b949e",
font=("Arial", 8)).pack(anchor="w", padx=4, pady=(8, 0))
quick_cmds = ["ls -la", "pwd", "df -h", "free -h", "top -bn1 | head -20",
"ps aux | head -20", "cat /etc/os-release", "uname -a",
"ifconfig || ip addr", "netstat -tlnp 2>/dev/null | head -20"]
self.cmd_listbox = tk.Listbox(left, bg="#0d1117", fg="#c9d1d9",
selectbackground="#1f6feb",
font=("Courier New", 7), relief=tk.FLAT,
height=10)
for cmd in quick_cmds:
self.cmd_listbox.insert(tk.END, cmd)
clsb = ttk.Scrollbar(left, command=self.cmd_listbox.yview)
self.cmd_listbox.configure(yscrollcommand=clsb.set)
clsb.pack(side=tk.RIGHT, fill=tk.Y)
self.cmd_listbox.pack(fill=tk.BOTH, expand=True)
self.cmd_listbox.bind("<Double-1>", self._run_quick_cmd)
# 右: ターミナル
right = tk.Frame(paned, bg="#0d1117")
paned.add(right, weight=1)
tk.Label(right, text="ターミナル", bg="#0d1117", fg="#8b949e",
font=("Arial", 8)).pack(anchor="w", padx=4)
self.terminal = tk.Text(right, bg="#0d1117", fg="#c9d1d9",
font=("Courier New", 9), relief=tk.FLAT,
state=tk.DISABLED, wrap=tk.NONE)
txsb = ttk.Scrollbar(right, orient=tk.VERTICAL,
command=self.terminal.yview)
self.terminal.configure(yscrollcommand=txsb.set)
txsb.pack(side=tk.RIGHT, fill=tk.Y)
self.terminal.pack(fill=tk.BOTH, expand=True)
self.terminal.tag_configure("prompt", foreground="#4fc3f7")
self.terminal.tag_configure("output", foreground="#c9d1d9")
self.terminal.tag_configure("error", foreground="#ef5350")
self.terminal.tag_configure("info", foreground="#8b949e")
# コマンド入力バー
input_f = tk.Frame(right, bg="#161b22")
input_f.pack(fill=tk.X, pady=2)
tk.Label(input_f, text="$", bg="#161b22", fg="#4fc3f7",
font=("Courier New", 10, "bold")).pack(side=tk.LEFT, padx=4)
self.cmd_var = tk.StringVar()
self.cmd_entry = ttk.Entry(input_f, textvariable=self.cmd_var,
font=("Courier New", 10))
self.cmd_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=4)
self.cmd_entry.bind("<Return>", lambda e: self._run_cmd())
self.cmd_entry.bind("<Up>", lambda e: self._history_up())
self.cmd_entry.bind("<Down>", lambda e: self._history_down())
ttk.Button(input_f, text="実行",
command=self._run_cmd).pack(side=tk.LEFT, padx=4)
self._hist_idx = -1
self.status_var = tk.StringVar(value="未接続")
tk.Label(self.root, textvariable=self.status_var,
bg="#21262d", fg="#8b949e", font=("Arial", 9),
anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)
def _append_terminal(self, text, tag="output"):
self.terminal.configure(state=tk.NORMAL)
self.terminal.insert(tk.END, text, tag)
self.terminal.see(tk.END)
self.terminal.configure(state=tk.DISABLED)
def _connect(self):
if not PARAMIKO_AVAILABLE:
messagebox.showerror("エラー", "pip install paramiko")
return
if self._client:
self._disconnect()
host = self.host_var.get().strip()
port = self.port_var.get()
user = self.user_var.get().strip()
pwd = self.pass_var.get()
self.status_var.set(f"接続中... {user}@{host}:{port}")
threading.Thread(
target=self._do_connect,
args=(host, port, user, pwd),
daemon=True).start()
def _do_connect(self, host, port, user, pwd):
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, port=port, username=user, password=pwd,
timeout=10)
self._client = client
self.root.after(0, self._append_terminal,
f"✔ 接続しました: {user}@{host}:{port}\n", "info")
self.root.after(0, self.status_var.set,
f"接続済: {user}@{host}:{port}")
except Exception as e:
self.root.after(0, self._append_terminal,
f"✘ 接続失敗: {e}\n", "error")
self.root.after(0, self.status_var.set, f"接続失敗: {e}")
def _disconnect(self):
if self._client:
try:
self._client.close()
except Exception:
pass
self._client = None
self.status_var.set("切断済")
self._append_terminal("切断しました\n", "info")
def _run_cmd(self):
cmd = self.cmd_var.get().strip()
if not cmd:
return
self.cmd_var.set("")
self._history.insert(0, cmd)
self._hist_idx = -1
self._append_terminal(f"$ {cmd}\n", "prompt")
if not self._client:
self._append_terminal(
"エラー: 接続されていません。先にSSH接続してください。\n", "error")
return
threading.Thread(target=self._do_run, args=(cmd,), daemon=True).start()
def _do_run(self, cmd):
try:
stdin, stdout, stderr = self._client.exec_command(cmd, timeout=30)
out = stdout.read().decode("utf-8", errors="replace")
err = stderr.read().decode("utf-8", errors="replace")
if out:
self.root.after(0, self._append_terminal, out, "output")
if err:
self.root.after(0, self._append_terminal, err, "error")
except Exception as e:
self.root.after(0, self._append_terminal, f"エラー: {e}\n", "error")
def _run_quick_cmd(self, _=None):
sel = self.cmd_listbox.curselection()
if sel:
cmd = self.cmd_listbox.get(sel[0])
self.cmd_var.set(cmd)
self._run_cmd()
def _history_up(self):
if self._history:
self._hist_idx = min(self._hist_idx + 1, len(self._history) - 1)
self.cmd_var.set(self._history[self._hist_idx])
def _history_down(self):
if self._hist_idx > 0:
self._hist_idx -= 1
self.cmd_var.set(self._history[self._hist_idx])
else:
self._hist_idx = -1
self.cmd_var.set("")
def _save_host(self):
host = {
"host": self.host_var.get(),
"port": self.port_var.get(),
"user": self.user_var.get(),
"label": f"{self.user_var.get()}@{self.host_var.get()}:{self.port_var.get()}",
}
self._hosts.append(host)
self.host_listbox.insert(tk.END, host["label"])
self._persist_hosts()
def _load_selected_host(self, _=None):
sel = self.host_listbox.curselection()
if not sel or sel[0] >= len(self._hosts):
return
h = self._hosts[sel[0]]
self.host_var.set(h["host"])
self.port_var.set(h["port"])
self.user_var.set(h["user"])
def _delete_host(self):
sel = self.host_listbox.curselection()
if not sel:
return
idx = sel[0]
if idx < len(self._hosts):
del self._hosts[idx]
self.host_listbox.delete(idx)
self._persist_hosts()
def _persist_hosts(self):
try:
with open(SAVE_PATH, "w", encoding="utf-8") as f:
json.dump(self._hosts, f, ensure_ascii=False, indent=2)
except Exception:
pass
def _load_hosts(self):
if os.path.exists(SAVE_PATH):
try:
with open(SAVE_PATH, encoding="utf-8") as f:
self._hosts = json.load(f)
for h in self._hosts:
self.host_listbox.insert(tk.END, h.get("label", ""))
except Exception:
self._hosts = []
def _on_close(self):
self._disconnect()
self.root.destroy()
if __name__ == "__main__":
root = tk.Tk()
app = App096(root)
root.mainloop()
イベント処理
ボタンのcommand引数でクリックイベントを、bind('
import tkinter as tk
from tkinter import ttk, messagebox
import threading
import json
import os
try:
import paramiko
PARAMIKO_AVAILABLE = True
except ImportError:
PARAMIKO_AVAILABLE = False
SAVE_PATH = os.path.join(os.path.dirname(__file__), "ssh_hosts.json")
class App096:
"""SSH簡易クライアント"""
def __init__(self, root):
self.root = root
self.root.title("SSH簡易クライアント")
self.root.geometry("1000x640")
self.root.configure(bg="#0d1117")
self._client = None
self._channel = None
self._hosts = []
self._history = []
self._build_ui()
self._load_hosts()
self.root.protocol("WM_DELETE_WINDOW", self._on_close)
def _build_ui(self):
header = tk.Frame(self.root, bg="#161b22", pady=6)
header.pack(fill=tk.X)
tk.Label(header, text="🔐 SSH簡易クライアント",
font=("Noto Sans JP", 12, "bold"),
bg="#161b22", fg="#4fc3f7").pack(side=tk.LEFT, padx=12)
if not PARAMIKO_AVAILABLE:
tk.Label(self.root,
text="⚠ paramiko が未インストールです (pip install paramiko)",
bg="#fff3cd", fg="#856404", font=("Arial", 9),
anchor="w", padx=8).pack(fill=tk.X)
# 接続設定
conn_f = tk.LabelFrame(self.root, text="接続設定", bg="#161b22",
fg="#ccc", font=("Arial", 9), padx=8, pady=4)
conn_f.pack(fill=tk.X, padx=8, pady=4)
tk.Label(conn_f, text="ホスト:", bg="#161b22", fg="#ccc",
font=("Arial", 9)).grid(row=0, column=0, sticky="w")
self.host_var = tk.StringVar(value="localhost")
ttk.Entry(conn_f, textvariable=self.host_var, width=20).grid(
row=0, column=1, padx=4)
tk.Label(conn_f, text="ポート:", bg="#161b22", fg="#ccc",
font=("Arial", 9)).grid(row=0, column=2, sticky="w", padx=(8, 0))
self.port_var = tk.IntVar(value=22)
ttk.Entry(conn_f, textvariable=self.port_var, width=6).grid(
row=0, column=3, padx=4)
tk.Label(conn_f, text="ユーザー:", bg="#161b22", fg="#ccc",
font=("Arial", 9)).grid(row=0, column=4, sticky="w", padx=(8, 0))
self.user_var = tk.StringVar(value="root")
ttk.Entry(conn_f, textvariable=self.user_var, width=12).grid(
row=0, column=5, padx=4)
tk.Label(conn_f, text="パスワード:", bg="#161b22", fg="#ccc",
font=("Arial", 9)).grid(row=0, column=6, sticky="w", padx=(8, 0))
self.pass_var = tk.StringVar()
ttk.Entry(conn_f, textvariable=self.pass_var, width=14,
show="*").grid(row=0, column=7, padx=4)
tk.Button(conn_f, text="接続", command=self._connect,
bg="#1565c0", fg="white", relief=tk.FLAT,
font=("Arial", 9, "bold"), padx=10,
activebackground="#0d47a1", bd=0).grid(row=0, column=8, padx=4)
tk.Button(conn_f, text="切断", command=self._disconnect,
bg="#c62828", fg="white", relief=tk.FLAT,
font=("Arial", 9), padx=10,
activebackground="#b71c1c", bd=0).grid(row=0, column=9, padx=2)
# ホスト保存ボタン
ttk.Button(conn_f, text="💾 ホスト保存",
command=self._save_host).grid(row=0, column=10, padx=8)
# メインエリア
paned = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL)
paned.pack(fill=tk.BOTH, expand=True, padx=4, pady=2)
# 左: ホスト一覧 + ショートカット
left = tk.Frame(paned, bg="#161b22", width=220)
paned.add(left, weight=0)
tk.Label(left, text="保存済みホスト", bg="#161b22", fg="#8b949e",
font=("Arial", 8)).pack(anchor="w", padx=4)
self.host_listbox = tk.Listbox(left, bg="#0d1117", fg="#c9d1d9",
selectbackground="#1f6feb",
font=("Arial", 8), relief=tk.FLAT)
hlsb = ttk.Scrollbar(left, command=self.host_listbox.yview)
self.host_listbox.configure(yscrollcommand=hlsb.set)
hlsb.pack(side=tk.RIGHT, fill=tk.Y)
self.host_listbox.pack(fill=tk.BOTH, expand=True)
self.host_listbox.bind("<Double-1>", self._load_selected_host)
btn_row = tk.Frame(left, bg="#161b22")
btn_row.pack(fill=tk.X, pady=2)
ttk.Button(btn_row, text="読み込み",
command=self._load_selected_host).pack(side=tk.LEFT, padx=2)
ttk.Button(btn_row, text="削除",
command=self._delete_host).pack(side=tk.LEFT, padx=2)
# クイックコマンド
tk.Label(left, text="クイックコマンド", bg="#161b22", fg="#8b949e",
font=("Arial", 8)).pack(anchor="w", padx=4, pady=(8, 0))
quick_cmds = ["ls -la", "pwd", "df -h", "free -h", "top -bn1 | head -20",
"ps aux | head -20", "cat /etc/os-release", "uname -a",
"ifconfig || ip addr", "netstat -tlnp 2>/dev/null | head -20"]
self.cmd_listbox = tk.Listbox(left, bg="#0d1117", fg="#c9d1d9",
selectbackground="#1f6feb",
font=("Courier New", 7), relief=tk.FLAT,
height=10)
for cmd in quick_cmds:
self.cmd_listbox.insert(tk.END, cmd)
clsb = ttk.Scrollbar(left, command=self.cmd_listbox.yview)
self.cmd_listbox.configure(yscrollcommand=clsb.set)
clsb.pack(side=tk.RIGHT, fill=tk.Y)
self.cmd_listbox.pack(fill=tk.BOTH, expand=True)
self.cmd_listbox.bind("<Double-1>", self._run_quick_cmd)
# 右: ターミナル
right = tk.Frame(paned, bg="#0d1117")
paned.add(right, weight=1)
tk.Label(right, text="ターミナル", bg="#0d1117", fg="#8b949e",
font=("Arial", 8)).pack(anchor="w", padx=4)
self.terminal = tk.Text(right, bg="#0d1117", fg="#c9d1d9",
font=("Courier New", 9), relief=tk.FLAT,
state=tk.DISABLED, wrap=tk.NONE)
txsb = ttk.Scrollbar(right, orient=tk.VERTICAL,
command=self.terminal.yview)
self.terminal.configure(yscrollcommand=txsb.set)
txsb.pack(side=tk.RIGHT, fill=tk.Y)
self.terminal.pack(fill=tk.BOTH, expand=True)
self.terminal.tag_configure("prompt", foreground="#4fc3f7")
self.terminal.tag_configure("output", foreground="#c9d1d9")
self.terminal.tag_configure("error", foreground="#ef5350")
self.terminal.tag_configure("info", foreground="#8b949e")
# コマンド入力バー
input_f = tk.Frame(right, bg="#161b22")
input_f.pack(fill=tk.X, pady=2)
tk.Label(input_f, text="$", bg="#161b22", fg="#4fc3f7",
font=("Courier New", 10, "bold")).pack(side=tk.LEFT, padx=4)
self.cmd_var = tk.StringVar()
self.cmd_entry = ttk.Entry(input_f, textvariable=self.cmd_var,
font=("Courier New", 10))
self.cmd_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=4)
self.cmd_entry.bind("<Return>", lambda e: self._run_cmd())
self.cmd_entry.bind("<Up>", lambda e: self._history_up())
self.cmd_entry.bind("<Down>", lambda e: self._history_down())
ttk.Button(input_f, text="実行",
command=self._run_cmd).pack(side=tk.LEFT, padx=4)
self._hist_idx = -1
self.status_var = tk.StringVar(value="未接続")
tk.Label(self.root, textvariable=self.status_var,
bg="#21262d", fg="#8b949e", font=("Arial", 9),
anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)
def _append_terminal(self, text, tag="output"):
self.terminal.configure(state=tk.NORMAL)
self.terminal.insert(tk.END, text, tag)
self.terminal.see(tk.END)
self.terminal.configure(state=tk.DISABLED)
def _connect(self):
if not PARAMIKO_AVAILABLE:
messagebox.showerror("エラー", "pip install paramiko")
return
if self._client:
self._disconnect()
host = self.host_var.get().strip()
port = self.port_var.get()
user = self.user_var.get().strip()
pwd = self.pass_var.get()
self.status_var.set(f"接続中... {user}@{host}:{port}")
threading.Thread(
target=self._do_connect,
args=(host, port, user, pwd),
daemon=True).start()
def _do_connect(self, host, port, user, pwd):
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, port=port, username=user, password=pwd,
timeout=10)
self._client = client
self.root.after(0, self._append_terminal,
f"✔ 接続しました: {user}@{host}:{port}\n", "info")
self.root.after(0, self.status_var.set,
f"接続済: {user}@{host}:{port}")
except Exception as e:
self.root.after(0, self._append_terminal,
f"✘ 接続失敗: {e}\n", "error")
self.root.after(0, self.status_var.set, f"接続失敗: {e}")
def _disconnect(self):
if self._client:
try:
self._client.close()
except Exception:
pass
self._client = None
self.status_var.set("切断済")
self._append_terminal("切断しました\n", "info")
def _run_cmd(self):
cmd = self.cmd_var.get().strip()
if not cmd:
return
self.cmd_var.set("")
self._history.insert(0, cmd)
self._hist_idx = -1
self._append_terminal(f"$ {cmd}\n", "prompt")
if not self._client:
self._append_terminal(
"エラー: 接続されていません。先にSSH接続してください。\n", "error")
return
threading.Thread(target=self._do_run, args=(cmd,), daemon=True).start()
def _do_run(self, cmd):
try:
stdin, stdout, stderr = self._client.exec_command(cmd, timeout=30)
out = stdout.read().decode("utf-8", errors="replace")
err = stderr.read().decode("utf-8", errors="replace")
if out:
self.root.after(0, self._append_terminal, out, "output")
if err:
self.root.after(0, self._append_terminal, err, "error")
except Exception as e:
self.root.after(0, self._append_terminal, f"エラー: {e}\n", "error")
def _run_quick_cmd(self, _=None):
sel = self.cmd_listbox.curselection()
if sel:
cmd = self.cmd_listbox.get(sel[0])
self.cmd_var.set(cmd)
self._run_cmd()
def _history_up(self):
if self._history:
self._hist_idx = min(self._hist_idx + 1, len(self._history) - 1)
self.cmd_var.set(self._history[self._hist_idx])
def _history_down(self):
if self._hist_idx > 0:
self._hist_idx -= 1
self.cmd_var.set(self._history[self._hist_idx])
else:
self._hist_idx = -1
self.cmd_var.set("")
def _save_host(self):
host = {
"host": self.host_var.get(),
"port": self.port_var.get(),
"user": self.user_var.get(),
"label": f"{self.user_var.get()}@{self.host_var.get()}:{self.port_var.get()}",
}
self._hosts.append(host)
self.host_listbox.insert(tk.END, host["label"])
self._persist_hosts()
def _load_selected_host(self, _=None):
sel = self.host_listbox.curselection()
if not sel or sel[0] >= len(self._hosts):
return
h = self._hosts[sel[0]]
self.host_var.set(h["host"])
self.port_var.set(h["port"])
self.user_var.set(h["user"])
def _delete_host(self):
sel = self.host_listbox.curselection()
if not sel:
return
idx = sel[0]
if idx < len(self._hosts):
del self._hosts[idx]
self.host_listbox.delete(idx)
self._persist_hosts()
def _persist_hosts(self):
try:
with open(SAVE_PATH, "w", encoding="utf-8") as f:
json.dump(self._hosts, f, ensure_ascii=False, indent=2)
except Exception:
pass
def _load_hosts(self):
if os.path.exists(SAVE_PATH):
try:
with open(SAVE_PATH, encoding="utf-8") as f:
self._hosts = json.load(f)
for h in self._hosts:
self.host_listbox.insert(tk.END, h.get("label", ""))
except Exception:
self._hosts = []
def _on_close(self):
self._disconnect()
self.root.destroy()
if __name__ == "__main__":
root = tk.Tk()
app = App096(root)
root.mainloop()
Textウィジェットでの結果表示
tk.Textウィジェットをstate=DISABLED(読み取り専用)で作成し、更新時はNORMALに変更してinsert()で内容を書き込み、再びDISABLEDに戻します。
import tkinter as tk
from tkinter import ttk, messagebox
import threading
import json
import os
try:
import paramiko
PARAMIKO_AVAILABLE = True
except ImportError:
PARAMIKO_AVAILABLE = False
SAVE_PATH = os.path.join(os.path.dirname(__file__), "ssh_hosts.json")
class App096:
"""SSH簡易クライアント"""
def __init__(self, root):
self.root = root
self.root.title("SSH簡易クライアント")
self.root.geometry("1000x640")
self.root.configure(bg="#0d1117")
self._client = None
self._channel = None
self._hosts = []
self._history = []
self._build_ui()
self._load_hosts()
self.root.protocol("WM_DELETE_WINDOW", self._on_close)
def _build_ui(self):
header = tk.Frame(self.root, bg="#161b22", pady=6)
header.pack(fill=tk.X)
tk.Label(header, text="🔐 SSH簡易クライアント",
font=("Noto Sans JP", 12, "bold"),
bg="#161b22", fg="#4fc3f7").pack(side=tk.LEFT, padx=12)
if not PARAMIKO_AVAILABLE:
tk.Label(self.root,
text="⚠ paramiko が未インストールです (pip install paramiko)",
bg="#fff3cd", fg="#856404", font=("Arial", 9),
anchor="w", padx=8).pack(fill=tk.X)
# 接続設定
conn_f = tk.LabelFrame(self.root, text="接続設定", bg="#161b22",
fg="#ccc", font=("Arial", 9), padx=8, pady=4)
conn_f.pack(fill=tk.X, padx=8, pady=4)
tk.Label(conn_f, text="ホスト:", bg="#161b22", fg="#ccc",
font=("Arial", 9)).grid(row=0, column=0, sticky="w")
self.host_var = tk.StringVar(value="localhost")
ttk.Entry(conn_f, textvariable=self.host_var, width=20).grid(
row=0, column=1, padx=4)
tk.Label(conn_f, text="ポート:", bg="#161b22", fg="#ccc",
font=("Arial", 9)).grid(row=0, column=2, sticky="w", padx=(8, 0))
self.port_var = tk.IntVar(value=22)
ttk.Entry(conn_f, textvariable=self.port_var, width=6).grid(
row=0, column=3, padx=4)
tk.Label(conn_f, text="ユーザー:", bg="#161b22", fg="#ccc",
font=("Arial", 9)).grid(row=0, column=4, sticky="w", padx=(8, 0))
self.user_var = tk.StringVar(value="root")
ttk.Entry(conn_f, textvariable=self.user_var, width=12).grid(
row=0, column=5, padx=4)
tk.Label(conn_f, text="パスワード:", bg="#161b22", fg="#ccc",
font=("Arial", 9)).grid(row=0, column=6, sticky="w", padx=(8, 0))
self.pass_var = tk.StringVar()
ttk.Entry(conn_f, textvariable=self.pass_var, width=14,
show="*").grid(row=0, column=7, padx=4)
tk.Button(conn_f, text="接続", command=self._connect,
bg="#1565c0", fg="white", relief=tk.FLAT,
font=("Arial", 9, "bold"), padx=10,
activebackground="#0d47a1", bd=0).grid(row=0, column=8, padx=4)
tk.Button(conn_f, text="切断", command=self._disconnect,
bg="#c62828", fg="white", relief=tk.FLAT,
font=("Arial", 9), padx=10,
activebackground="#b71c1c", bd=0).grid(row=0, column=9, padx=2)
# ホスト保存ボタン
ttk.Button(conn_f, text="💾 ホスト保存",
command=self._save_host).grid(row=0, column=10, padx=8)
# メインエリア
paned = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL)
paned.pack(fill=tk.BOTH, expand=True, padx=4, pady=2)
# 左: ホスト一覧 + ショートカット
left = tk.Frame(paned, bg="#161b22", width=220)
paned.add(left, weight=0)
tk.Label(left, text="保存済みホスト", bg="#161b22", fg="#8b949e",
font=("Arial", 8)).pack(anchor="w", padx=4)
self.host_listbox = tk.Listbox(left, bg="#0d1117", fg="#c9d1d9",
selectbackground="#1f6feb",
font=("Arial", 8), relief=tk.FLAT)
hlsb = ttk.Scrollbar(left, command=self.host_listbox.yview)
self.host_listbox.configure(yscrollcommand=hlsb.set)
hlsb.pack(side=tk.RIGHT, fill=tk.Y)
self.host_listbox.pack(fill=tk.BOTH, expand=True)
self.host_listbox.bind("<Double-1>", self._load_selected_host)
btn_row = tk.Frame(left, bg="#161b22")
btn_row.pack(fill=tk.X, pady=2)
ttk.Button(btn_row, text="読み込み",
command=self._load_selected_host).pack(side=tk.LEFT, padx=2)
ttk.Button(btn_row, text="削除",
command=self._delete_host).pack(side=tk.LEFT, padx=2)
# クイックコマンド
tk.Label(left, text="クイックコマンド", bg="#161b22", fg="#8b949e",
font=("Arial", 8)).pack(anchor="w", padx=4, pady=(8, 0))
quick_cmds = ["ls -la", "pwd", "df -h", "free -h", "top -bn1 | head -20",
"ps aux | head -20", "cat /etc/os-release", "uname -a",
"ifconfig || ip addr", "netstat -tlnp 2>/dev/null | head -20"]
self.cmd_listbox = tk.Listbox(left, bg="#0d1117", fg="#c9d1d9",
selectbackground="#1f6feb",
font=("Courier New", 7), relief=tk.FLAT,
height=10)
for cmd in quick_cmds:
self.cmd_listbox.insert(tk.END, cmd)
clsb = ttk.Scrollbar(left, command=self.cmd_listbox.yview)
self.cmd_listbox.configure(yscrollcommand=clsb.set)
clsb.pack(side=tk.RIGHT, fill=tk.Y)
self.cmd_listbox.pack(fill=tk.BOTH, expand=True)
self.cmd_listbox.bind("<Double-1>", self._run_quick_cmd)
# 右: ターミナル
right = tk.Frame(paned, bg="#0d1117")
paned.add(right, weight=1)
tk.Label(right, text="ターミナル", bg="#0d1117", fg="#8b949e",
font=("Arial", 8)).pack(anchor="w", padx=4)
self.terminal = tk.Text(right, bg="#0d1117", fg="#c9d1d9",
font=("Courier New", 9), relief=tk.FLAT,
state=tk.DISABLED, wrap=tk.NONE)
txsb = ttk.Scrollbar(right, orient=tk.VERTICAL,
command=self.terminal.yview)
self.terminal.configure(yscrollcommand=txsb.set)
txsb.pack(side=tk.RIGHT, fill=tk.Y)
self.terminal.pack(fill=tk.BOTH, expand=True)
self.terminal.tag_configure("prompt", foreground="#4fc3f7")
self.terminal.tag_configure("output", foreground="#c9d1d9")
self.terminal.tag_configure("error", foreground="#ef5350")
self.terminal.tag_configure("info", foreground="#8b949e")
# コマンド入力バー
input_f = tk.Frame(right, bg="#161b22")
input_f.pack(fill=tk.X, pady=2)
tk.Label(input_f, text="$", bg="#161b22", fg="#4fc3f7",
font=("Courier New", 10, "bold")).pack(side=tk.LEFT, padx=4)
self.cmd_var = tk.StringVar()
self.cmd_entry = ttk.Entry(input_f, textvariable=self.cmd_var,
font=("Courier New", 10))
self.cmd_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=4)
self.cmd_entry.bind("<Return>", lambda e: self._run_cmd())
self.cmd_entry.bind("<Up>", lambda e: self._history_up())
self.cmd_entry.bind("<Down>", lambda e: self._history_down())
ttk.Button(input_f, text="実行",
command=self._run_cmd).pack(side=tk.LEFT, padx=4)
self._hist_idx = -1
self.status_var = tk.StringVar(value="未接続")
tk.Label(self.root, textvariable=self.status_var,
bg="#21262d", fg="#8b949e", font=("Arial", 9),
anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)
def _append_terminal(self, text, tag="output"):
self.terminal.configure(state=tk.NORMAL)
self.terminal.insert(tk.END, text, tag)
self.terminal.see(tk.END)
self.terminal.configure(state=tk.DISABLED)
def _connect(self):
if not PARAMIKO_AVAILABLE:
messagebox.showerror("エラー", "pip install paramiko")
return
if self._client:
self._disconnect()
host = self.host_var.get().strip()
port = self.port_var.get()
user = self.user_var.get().strip()
pwd = self.pass_var.get()
self.status_var.set(f"接続中... {user}@{host}:{port}")
threading.Thread(
target=self._do_connect,
args=(host, port, user, pwd),
daemon=True).start()
def _do_connect(self, host, port, user, pwd):
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, port=port, username=user, password=pwd,
timeout=10)
self._client = client
self.root.after(0, self._append_terminal,
f"✔ 接続しました: {user}@{host}:{port}\n", "info")
self.root.after(0, self.status_var.set,
f"接続済: {user}@{host}:{port}")
except Exception as e:
self.root.after(0, self._append_terminal,
f"✘ 接続失敗: {e}\n", "error")
self.root.after(0, self.status_var.set, f"接続失敗: {e}")
def _disconnect(self):
if self._client:
try:
self._client.close()
except Exception:
pass
self._client = None
self.status_var.set("切断済")
self._append_terminal("切断しました\n", "info")
def _run_cmd(self):
cmd = self.cmd_var.get().strip()
if not cmd:
return
self.cmd_var.set("")
self._history.insert(0, cmd)
self._hist_idx = -1
self._append_terminal(f"$ {cmd}\n", "prompt")
if not self._client:
self._append_terminal(
"エラー: 接続されていません。先にSSH接続してください。\n", "error")
return
threading.Thread(target=self._do_run, args=(cmd,), daemon=True).start()
def _do_run(self, cmd):
try:
stdin, stdout, stderr = self._client.exec_command(cmd, timeout=30)
out = stdout.read().decode("utf-8", errors="replace")
err = stderr.read().decode("utf-8", errors="replace")
if out:
self.root.after(0, self._append_terminal, out, "output")
if err:
self.root.after(0, self._append_terminal, err, "error")
except Exception as e:
self.root.after(0, self._append_terminal, f"エラー: {e}\n", "error")
def _run_quick_cmd(self, _=None):
sel = self.cmd_listbox.curselection()
if sel:
cmd = self.cmd_listbox.get(sel[0])
self.cmd_var.set(cmd)
self._run_cmd()
def _history_up(self):
if self._history:
self._hist_idx = min(self._hist_idx + 1, len(self._history) - 1)
self.cmd_var.set(self._history[self._hist_idx])
def _history_down(self):
if self._hist_idx > 0:
self._hist_idx -= 1
self.cmd_var.set(self._history[self._hist_idx])
else:
self._hist_idx = -1
self.cmd_var.set("")
def _save_host(self):
host = {
"host": self.host_var.get(),
"port": self.port_var.get(),
"user": self.user_var.get(),
"label": f"{self.user_var.get()}@{self.host_var.get()}:{self.port_var.get()}",
}
self._hosts.append(host)
self.host_listbox.insert(tk.END, host["label"])
self._persist_hosts()
def _load_selected_host(self, _=None):
sel = self.host_listbox.curselection()
if not sel or sel[0] >= len(self._hosts):
return
h = self._hosts[sel[0]]
self.host_var.set(h["host"])
self.port_var.set(h["port"])
self.user_var.set(h["user"])
def _delete_host(self):
sel = self.host_listbox.curselection()
if not sel:
return
idx = sel[0]
if idx < len(self._hosts):
del self._hosts[idx]
self.host_listbox.delete(idx)
self._persist_hosts()
def _persist_hosts(self):
try:
with open(SAVE_PATH, "w", encoding="utf-8") as f:
json.dump(self._hosts, f, ensure_ascii=False, indent=2)
except Exception:
pass
def _load_hosts(self):
if os.path.exists(SAVE_PATH):
try:
with open(SAVE_PATH, encoding="utf-8") as f:
self._hosts = json.load(f)
for h in self._hosts:
self.host_listbox.insert(tk.END, h.get("label", ""))
except Exception:
self._hosts = []
def _on_close(self):
self._disconnect()
self.root.destroy()
if __name__ == "__main__":
root = tk.Tk()
app = App096(root)
root.mainloop()
例外処理とエラーハンドリング
try-exceptでValueErrorとExceptionを捕捉し、messagebox.showerror()でエラーメッセージを表示します。予期しないエラーも処理することで、アプリの堅牢性が向上します。
import tkinter as tk
from tkinter import ttk, messagebox
import threading
import json
import os
try:
import paramiko
PARAMIKO_AVAILABLE = True
except ImportError:
PARAMIKO_AVAILABLE = False
SAVE_PATH = os.path.join(os.path.dirname(__file__), "ssh_hosts.json")
class App096:
"""SSH簡易クライアント"""
def __init__(self, root):
self.root = root
self.root.title("SSH簡易クライアント")
self.root.geometry("1000x640")
self.root.configure(bg="#0d1117")
self._client = None
self._channel = None
self._hosts = []
self._history = []
self._build_ui()
self._load_hosts()
self.root.protocol("WM_DELETE_WINDOW", self._on_close)
def _build_ui(self):
header = tk.Frame(self.root, bg="#161b22", pady=6)
header.pack(fill=tk.X)
tk.Label(header, text="🔐 SSH簡易クライアント",
font=("Noto Sans JP", 12, "bold"),
bg="#161b22", fg="#4fc3f7").pack(side=tk.LEFT, padx=12)
if not PARAMIKO_AVAILABLE:
tk.Label(self.root,
text="⚠ paramiko が未インストールです (pip install paramiko)",
bg="#fff3cd", fg="#856404", font=("Arial", 9),
anchor="w", padx=8).pack(fill=tk.X)
# 接続設定
conn_f = tk.LabelFrame(self.root, text="接続設定", bg="#161b22",
fg="#ccc", font=("Arial", 9), padx=8, pady=4)
conn_f.pack(fill=tk.X, padx=8, pady=4)
tk.Label(conn_f, text="ホスト:", bg="#161b22", fg="#ccc",
font=("Arial", 9)).grid(row=0, column=0, sticky="w")
self.host_var = tk.StringVar(value="localhost")
ttk.Entry(conn_f, textvariable=self.host_var, width=20).grid(
row=0, column=1, padx=4)
tk.Label(conn_f, text="ポート:", bg="#161b22", fg="#ccc",
font=("Arial", 9)).grid(row=0, column=2, sticky="w", padx=(8, 0))
self.port_var = tk.IntVar(value=22)
ttk.Entry(conn_f, textvariable=self.port_var, width=6).grid(
row=0, column=3, padx=4)
tk.Label(conn_f, text="ユーザー:", bg="#161b22", fg="#ccc",
font=("Arial", 9)).grid(row=0, column=4, sticky="w", padx=(8, 0))
self.user_var = tk.StringVar(value="root")
ttk.Entry(conn_f, textvariable=self.user_var, width=12).grid(
row=0, column=5, padx=4)
tk.Label(conn_f, text="パスワード:", bg="#161b22", fg="#ccc",
font=("Arial", 9)).grid(row=0, column=6, sticky="w", padx=(8, 0))
self.pass_var = tk.StringVar()
ttk.Entry(conn_f, textvariable=self.pass_var, width=14,
show="*").grid(row=0, column=7, padx=4)
tk.Button(conn_f, text="接続", command=self._connect,
bg="#1565c0", fg="white", relief=tk.FLAT,
font=("Arial", 9, "bold"), padx=10,
activebackground="#0d47a1", bd=0).grid(row=0, column=8, padx=4)
tk.Button(conn_f, text="切断", command=self._disconnect,
bg="#c62828", fg="white", relief=tk.FLAT,
font=("Arial", 9), padx=10,
activebackground="#b71c1c", bd=0).grid(row=0, column=9, padx=2)
# ホスト保存ボタン
ttk.Button(conn_f, text="💾 ホスト保存",
command=self._save_host).grid(row=0, column=10, padx=8)
# メインエリア
paned = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL)
paned.pack(fill=tk.BOTH, expand=True, padx=4, pady=2)
# 左: ホスト一覧 + ショートカット
left = tk.Frame(paned, bg="#161b22", width=220)
paned.add(left, weight=0)
tk.Label(left, text="保存済みホスト", bg="#161b22", fg="#8b949e",
font=("Arial", 8)).pack(anchor="w", padx=4)
self.host_listbox = tk.Listbox(left, bg="#0d1117", fg="#c9d1d9",
selectbackground="#1f6feb",
font=("Arial", 8), relief=tk.FLAT)
hlsb = ttk.Scrollbar(left, command=self.host_listbox.yview)
self.host_listbox.configure(yscrollcommand=hlsb.set)
hlsb.pack(side=tk.RIGHT, fill=tk.Y)
self.host_listbox.pack(fill=tk.BOTH, expand=True)
self.host_listbox.bind("<Double-1>", self._load_selected_host)
btn_row = tk.Frame(left, bg="#161b22")
btn_row.pack(fill=tk.X, pady=2)
ttk.Button(btn_row, text="読み込み",
command=self._load_selected_host).pack(side=tk.LEFT, padx=2)
ttk.Button(btn_row, text="削除",
command=self._delete_host).pack(side=tk.LEFT, padx=2)
# クイックコマンド
tk.Label(left, text="クイックコマンド", bg="#161b22", fg="#8b949e",
font=("Arial", 8)).pack(anchor="w", padx=4, pady=(8, 0))
quick_cmds = ["ls -la", "pwd", "df -h", "free -h", "top -bn1 | head -20",
"ps aux | head -20", "cat /etc/os-release", "uname -a",
"ifconfig || ip addr", "netstat -tlnp 2>/dev/null | head -20"]
self.cmd_listbox = tk.Listbox(left, bg="#0d1117", fg="#c9d1d9",
selectbackground="#1f6feb",
font=("Courier New", 7), relief=tk.FLAT,
height=10)
for cmd in quick_cmds:
self.cmd_listbox.insert(tk.END, cmd)
clsb = ttk.Scrollbar(left, command=self.cmd_listbox.yview)
self.cmd_listbox.configure(yscrollcommand=clsb.set)
clsb.pack(side=tk.RIGHT, fill=tk.Y)
self.cmd_listbox.pack(fill=tk.BOTH, expand=True)
self.cmd_listbox.bind("<Double-1>", self._run_quick_cmd)
# 右: ターミナル
right = tk.Frame(paned, bg="#0d1117")
paned.add(right, weight=1)
tk.Label(right, text="ターミナル", bg="#0d1117", fg="#8b949e",
font=("Arial", 8)).pack(anchor="w", padx=4)
self.terminal = tk.Text(right, bg="#0d1117", fg="#c9d1d9",
font=("Courier New", 9), relief=tk.FLAT,
state=tk.DISABLED, wrap=tk.NONE)
txsb = ttk.Scrollbar(right, orient=tk.VERTICAL,
command=self.terminal.yview)
self.terminal.configure(yscrollcommand=txsb.set)
txsb.pack(side=tk.RIGHT, fill=tk.Y)
self.terminal.pack(fill=tk.BOTH, expand=True)
self.terminal.tag_configure("prompt", foreground="#4fc3f7")
self.terminal.tag_configure("output", foreground="#c9d1d9")
self.terminal.tag_configure("error", foreground="#ef5350")
self.terminal.tag_configure("info", foreground="#8b949e")
# コマンド入力バー
input_f = tk.Frame(right, bg="#161b22")
input_f.pack(fill=tk.X, pady=2)
tk.Label(input_f, text="$", bg="#161b22", fg="#4fc3f7",
font=("Courier New", 10, "bold")).pack(side=tk.LEFT, padx=4)
self.cmd_var = tk.StringVar()
self.cmd_entry = ttk.Entry(input_f, textvariable=self.cmd_var,
font=("Courier New", 10))
self.cmd_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=4)
self.cmd_entry.bind("<Return>", lambda e: self._run_cmd())
self.cmd_entry.bind("<Up>", lambda e: self._history_up())
self.cmd_entry.bind("<Down>", lambda e: self._history_down())
ttk.Button(input_f, text="実行",
command=self._run_cmd).pack(side=tk.LEFT, padx=4)
self._hist_idx = -1
self.status_var = tk.StringVar(value="未接続")
tk.Label(self.root, textvariable=self.status_var,
bg="#21262d", fg="#8b949e", font=("Arial", 9),
anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)
def _append_terminal(self, text, tag="output"):
self.terminal.configure(state=tk.NORMAL)
self.terminal.insert(tk.END, text, tag)
self.terminal.see(tk.END)
self.terminal.configure(state=tk.DISABLED)
def _connect(self):
if not PARAMIKO_AVAILABLE:
messagebox.showerror("エラー", "pip install paramiko")
return
if self._client:
self._disconnect()
host = self.host_var.get().strip()
port = self.port_var.get()
user = self.user_var.get().strip()
pwd = self.pass_var.get()
self.status_var.set(f"接続中... {user}@{host}:{port}")
threading.Thread(
target=self._do_connect,
args=(host, port, user, pwd),
daemon=True).start()
def _do_connect(self, host, port, user, pwd):
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, port=port, username=user, password=pwd,
timeout=10)
self._client = client
self.root.after(0, self._append_terminal,
f"✔ 接続しました: {user}@{host}:{port}\n", "info")
self.root.after(0, self.status_var.set,
f"接続済: {user}@{host}:{port}")
except Exception as e:
self.root.after(0, self._append_terminal,
f"✘ 接続失敗: {e}\n", "error")
self.root.after(0, self.status_var.set, f"接続失敗: {e}")
def _disconnect(self):
if self._client:
try:
self._client.close()
except Exception:
pass
self._client = None
self.status_var.set("切断済")
self._append_terminal("切断しました\n", "info")
def _run_cmd(self):
cmd = self.cmd_var.get().strip()
if not cmd:
return
self.cmd_var.set("")
self._history.insert(0, cmd)
self._hist_idx = -1
self._append_terminal(f"$ {cmd}\n", "prompt")
if not self._client:
self._append_terminal(
"エラー: 接続されていません。先にSSH接続してください。\n", "error")
return
threading.Thread(target=self._do_run, args=(cmd,), daemon=True).start()
def _do_run(self, cmd):
try:
stdin, stdout, stderr = self._client.exec_command(cmd, timeout=30)
out = stdout.read().decode("utf-8", errors="replace")
err = stderr.read().decode("utf-8", errors="replace")
if out:
self.root.after(0, self._append_terminal, out, "output")
if err:
self.root.after(0, self._append_terminal, err, "error")
except Exception as e:
self.root.after(0, self._append_terminal, f"エラー: {e}\n", "error")
def _run_quick_cmd(self, _=None):
sel = self.cmd_listbox.curselection()
if sel:
cmd = self.cmd_listbox.get(sel[0])
self.cmd_var.set(cmd)
self._run_cmd()
def _history_up(self):
if self._history:
self._hist_idx = min(self._hist_idx + 1, len(self._history) - 1)
self.cmd_var.set(self._history[self._hist_idx])
def _history_down(self):
if self._hist_idx > 0:
self._hist_idx -= 1
self.cmd_var.set(self._history[self._hist_idx])
else:
self._hist_idx = -1
self.cmd_var.set("")
def _save_host(self):
host = {
"host": self.host_var.get(),
"port": self.port_var.get(),
"user": self.user_var.get(),
"label": f"{self.user_var.get()}@{self.host_var.get()}:{self.port_var.get()}",
}
self._hosts.append(host)
self.host_listbox.insert(tk.END, host["label"])
self._persist_hosts()
def _load_selected_host(self, _=None):
sel = self.host_listbox.curselection()
if not sel or sel[0] >= len(self._hosts):
return
h = self._hosts[sel[0]]
self.host_var.set(h["host"])
self.port_var.set(h["port"])
self.user_var.set(h["user"])
def _delete_host(self):
sel = self.host_listbox.curselection()
if not sel:
return
idx = sel[0]
if idx < len(self._hosts):
del self._hosts[idx]
self.host_listbox.delete(idx)
self._persist_hosts()
def _persist_hosts(self):
try:
with open(SAVE_PATH, "w", encoding="utf-8") as f:
json.dump(self._hosts, f, ensure_ascii=False, indent=2)
except Exception:
pass
def _load_hosts(self):
if os.path.exists(SAVE_PATH):
try:
with open(SAVE_PATH, encoding="utf-8") as f:
self._hosts = json.load(f)
for h in self._hosts:
self.host_listbox.insert(tk.END, h.get("label", ""))
except Exception:
self._hosts = []
def _on_close(self):
self._disconnect()
self.root.destroy()
if __name__ == "__main__":
root = tk.Tk()
app = App096(root)
root.mainloop()
6. ステップバイステップガイド
このアプリをゼロから自分で作る手順を解説します。コードをコピーするだけでなく、実際に手順を追って自分で書いてみましょう。
-
1ファイルを作成する
新しいファイルを作成して app096.py と保存します。
-
2クラスの骨格を作る
App096クラスを定義し、__init__とmainloop()の最小構成を作ります。
-
3タイトルバーを作る
Frameを使ってカラーバー付きのタイトルエリアを作ります。
-
4入力フォームを実装する
LabelFrameとEntryウィジェットで入力エリアを作ります。
-
5処理ロジックを実装する
_execute()メソッドにメインロジックを実装します。
-
6結果表示を実装する
TextウィジェットかLabelに結果を表示する_show_result()を実装します。
-
7エラー処理を追加する
try-exceptとmessageboxでエラーハンドリングを追加します。
7. カスタマイズアイデア
基本機能を習得したら、以下のカスタマイズに挑戦してみましょう。
💡 ダークモードを追加する
bg色・fg色を辞書で管理し、ボタン1つでダークモード・ライトモードを切り替えられるようにしましょう。
💡 データの保存機能
処理結果をCSV・TXTファイルに保存する機能を追加しましょう。filedialog.asksaveasfilename()でファイル保存ダイアログが使えます。
💡 設定ダイアログ
フォントサイズや色などの設定をユーザーが変更できるオプションダイアログを追加しましょう。
8. よくある問題と解決法
❌ 日本語フォントが表示されない
原因:システムに日本語フォントが見つからない場合があります。
解決法:font引数を省略するかシステムに合ったフォントを指定してください。
❌ ライブラリのインポートエラー
原因:必要なライブラリがインストールされていません。
解決法:pip install コマンドで必要なライブラリをインストールしてください。
❌ ウィンドウサイズが合わない
原因:画面解像度や表示スケールによって異なる場合があります。
解決法:root.geometry()で適切なサイズに調整してください。
9. 練習問題
アプリの理解を深めるための練習問題です。
-
課題1:機能拡張
SSH簡易クライアントに新しい機能を1つ追加してみましょう。
-
課題2:UIの改善
色・フォント・レイアウトを変更して、より使いやすいUIにカスタマイズしましょう。
-
課題3:保存機能の追加
処理結果をファイルに保存する機能を追加しましょう。