【问题标题】:Bash Script : Read a file containing IP and run scriptBash 脚本:读取包含 IP 的文件并运行脚本
【发布时间】:2020-10-13 11:49:06
【问题描述】:

我在 bash 中创建了一个手动运行的 useradd 脚本(我可以在远程主机上复制脚本并运行该脚本)。

我希望该脚本读取 host.txt 文件,在该文件中提及必须通过登录远程主机运行的 ip

#!/bin/bash

# Unlock the crtical directory for modification

chattr -i /etc/passwd
chattr -i /etc/shadow
chattr -i /etc/group
chattr -i /etc/gshadow
chattr -i /etc/ssh/sshd_config

#Script to Add User

read -p 'Please Enter The Username To Add: ' name
echo "$name" > /tmp/userlist.txt
clear
echo -e "Hello $name\nYour Name Is Added To The List."
userfile=/tmp/userlist.txt
username=$(cat /tmp/userlist.txt | tr 'A-Z' 'a-z')
for user in $username
do
useradd $user -N -s /bin/bash
usermod -aG sudo $user
passwd $user
echo "AllowUsers ${user}" >> /etc/ssh/sshd_config                   \\Prefix the line with # if username is hard coded
#sed -i 's/tui/tui <hard coded username>/g' /etc/ssh/sshd_config                        \\remove # if the user is hard coded
#sed -i 's/<hard coded username>.*<hard coded username>/<hard coded username>/g' /etc/ssh/sshd_config       \\remove # if the user is hard coded
#sed -i 's/tui/tui <hard coded username>/g' /etc/security/access.conf                       \\remove # if the user is hard coded
done
echo "=================================="

echo "User $name Have Been Created."

echo "=================================="
tail /etc/passwd | cut -d: -f1

#lock the crtical directory for modification

chattr +i /etc/passwd
chattr +i /etc/shadow
chattr +i /etc/group
chattr +i /etc/gshadow
chattr +i /etc/ssh/sshd_config
systemctl restart ssh

【问题讨论】:

    标签: linux bash ssh


    【解决方案1】:

    假设您有一个名为 ip.txt 的 IP 文件

    while IFS= read -r dest; do
      scp useradd.sh "root@$dest:remote/path/"
      ssh root@$dest "/bin/bash remote/path/useradd.sh"
    done <ip.txt
    

    如果 root 无法登录(推荐),则替换为正确的用户,然后将 sudo 添加到命令中。

    这假设登录是通过密钥文件完成的并且没有密码。

    如果文件已经在主机上,则跳过 scp 阶段 - 或者您可以使用 xargs 之类的

    cat ip.txt | xargs -I{} ssh user@{} sudo remote/path/useradd.sh
    

    或者 - 我可以推荐使用 ansible。

    【讨论】:

    • 我想在本地机器上运行脚本,host.txt 也会保存在本地机器上
    • 好的,所以答案的第一部分应该适合你。该脚本在您的本地计算机上运行,​​使用 scp 将您的 useradd 脚本复制到服务器并使用 ssh 运行它。让我知道你过得怎么样。
    猜你喜欢
    • 2023-01-08
    • 2014-10-26
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 2016-07-17
    • 2015-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多