From d4541281a690b9c6ee455c552a29701efe6cdc4b Mon Sep 17 00:00:00 2001 From: Randall Date: Sat, 13 Jul 2024 02:59:40 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9ESSH=E5=85=AC=E9=92=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ssh/add_ssh_pubkey/README.md | 1 + ssh/add_ssh_pubkey/add_ssh_pubkey.sh | 41 ++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 ssh/add_ssh_pubkey/README.md create mode 100644 ssh/add_ssh_pubkey/add_ssh_pubkey.sh diff --git a/ssh/add_ssh_pubkey/README.md b/ssh/add_ssh_pubkey/README.md new file mode 100644 index 0000000..02e628f --- /dev/null +++ b/ssh/add_ssh_pubkey/README.md @@ -0,0 +1 @@ +# 新增SSH公钥 \ No newline at end of file diff --git a/ssh/add_ssh_pubkey/add_ssh_pubkey.sh b/ssh/add_ssh_pubkey/add_ssh_pubkey.sh new file mode 100644 index 0000000..6005aed --- /dev/null +++ b/ssh/add_ssh_pubkey/add_ssh_pubkey.sh @@ -0,0 +1,41 @@ +#!/bin/bash + +# 检查是否提供了公钥参数 +if [ -z "$1" ]; then + echo "Usage: $0 " + exit 1 +fi + +# 公钥变量 +SSH_KEY="$1" + +# 创建 .ssh 目录并设置权限 +mkdir -p ~/.ssh +chmod 700 ~/.ssh + +# 将公钥添加到 authorized_keys 文件 +echo "$SSH_KEY" >> ~/.ssh/authorized_keys +chmod 600 ~/.ssh/authorized_keys + +# 检查并配置sshd_config文件 +SSHD_CONFIG="/etc/ssh/sshd_config" +if grep -q "^#PasswordAuthentication" $SSHD_CONFIG; then + sudo sed -i 's/^#PasswordAuthentication.*/PasswordAuthentication no/' $SSHD_CONFIG +elif grep -q "^PasswordAuthentication" $SSHD_CONFIG; then + sudo sed -i 's/^PasswordAuthentication.*/PasswordAuthentication no/' $SSHD_CONFIG +else + echo "PasswordAuthentication no" | sudo tee -a $SSHD_CONFIG +fi + +if grep -q "^#PermitRootLogin" $SSHD_CONFIG; then + sudo sed -i 's/^#PermitRootLogin.*/PermitRootLogin prohibit-password/' $SSHD_CONFIG +elif grep -q "^PermitRootLogin" $SSHD_CONFIG; then + sudo sed -i 's/^PermitRootLogin.*/PermitRootLogin prohibit-password/' $SSHD_CONFIG +else + echo "PermitRootLogin prohibit-password" | sudo tee -a $SSHD_CONFIG +fi + +# 重启ssh服务以应用更改 +sudo systemctl restart sshd + +echo "SSH key added and password login disabled." \ No newline at end of file