繁体   English   中英

Bash 脚本:读取包含 IP 的文件并运行脚本

[英]Bash Script : Read a file containing IP and run script

我在手动运行的 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

假设您有一个名为 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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM