我目前正在尝试实现一个bash脚本,该脚本将验证服务器上的SSH密钥是否仍链接到局域网中活动的已知主机。您可以在我的bash脚本的开头下面找到实现此目标的方法:
#!/bin/bash
# LAN SSH KEYS DISCOVERY SCRIPT
# TRYING TO FIND THOSE SSH KEYS NOW
cat /etc/passwd | grep /bin/bash > bash_users
cat bash_users | cut -d ":" -f 6 > cutted.bash_users_home_dir
for bash_users in $(cat cutted.bash_users_home_dir)
do
ls -al $bash_users/.ssh/*id_* >> ssh-keys.txt
done
# DISCOVERING THE KNOWN_HOSTS NOW
for known_hosts in $(cat cutted.bash_users_home_dir)
do
cat $bash_users/.ssh/known_hosts | awk '{print $1}' | sort -u >>
hosts_known.txt
sleep 2
done
hosts_known=$(wc -l hosts_known.txt)
echo "We have $hosts_known known hosts that could be still active via SSH
keys"
# TIME TO TEST WHICH SSH servers are still active with the SSH keys
# AND THIS IS WHERE I AM FROZEN...
# Would love to have bash script that could
# ssh -l $users_that_have_/bin/bash -i $ssh_keys $ssh_servers
# Would also be very nice if it could save active
# SSH servers with the valid keys in output.txt in the format
# username:local-IP:/path/to/SSH_key
如果上面的bash脚本可以更好地实现上述目标,请对其进行编辑/修改。
任何帮助将不胜感激,
谢谢
答案 0 :(得分:0)
以下作品很酷:
</etc/passwd \
grep /bin/bash |
cut -d: -f6 |
sudo xargs -i -- sh -c '
[ -e "$1" ] && cat "$1"
' -- {}/.ssh/known_hosts |
cut -d' ' -f1 |
tr ',' '\n' |
sed '
/^\[/{
s/\[\(.*\)\]:\(.*\)/\1 \2/;
t;
};
s/$/ 22/;
' |
sort -u |
xargs -l1 -- sh -c '
if echo "~" | nc -q1 -w3 "$1" "$2" | grep -q "^SSH"; then
echo "#### SUCCESS $1 $2";
else
echo "#### ERROR $1 $2";
fi
' --
所以:
/etc/passwd
开头cut -d: -f6
sudo xargs -i --
运行
[
开头,则表示其格式为[host]:port
,而我想用host port
代替[
开头,则在该行的末尾添加22
,使其为host 22
sort -u
现在每行:
echo "~" | nc hostname port
获取ssh版本,返回的内容为“ SSH-2.0-OpenSSH_6.0” +换行符+“协议不匹配”。nc hostname port
返回的行以SSH
开头,则意味着另一端正在运行ssh nc -w timeout
选项。可能还应该指定nc -q 1
。现在真正的乐趣是,当将max-procs选项添加到最后一个xargs行时,可以同时检查所有主机。在我的主机上,我有47
个唯一的地址,xargs -P30
会在2秒钟内全部检查它们。
但是确实存在一些问题。该脚本需要root才能从所有用户known_hosts读取。但更糟糕的是,known_hosts可能会被散列。最好先了解网络上的主机列表,然后从中生成known_hosts。看起来像ssh-keyscan -f list_of_hosts > ~/.ssh/known_hosts
或类似的东西。如果已知主机中存在主机,则应使用常规ssh-keygen -F hostname
,可悲的是没有列表命令。在ssh documentation中可以找到known_hosts文件格式。