批量ssh登录
程序员文章站
2022-05-27 23:41:07
...
批量ssh登录
问题
需要在修改多台机器的防火墙策略,使用ssh批量处理。但是在使用过程中遇到一个问题。ssh到第一个机器后就不再继续往下执行了。
场景还原
[[email protected] test]# cat fhosts
192.168.0.42
192.168.0.43
[[email protected] test]# cat fhosts | while read line; do ssh $line hostname -i;done
192.168.0.42
[[email protected] test]#
脚本只对第一个IP做了检测,就直接跳出来了。
问题分析
while使用重定向机制,ip.txt文件中的信息都已经读入并重定向给了整个while语句,所以当我们在while循环中再一次调用read语 句,就会读取到下一条记录。问题就出在这里,ssh语句正好回读取输入中的所有东西。为了禁止ssh读所有东西增加一个< /dev/null,将ssh 的输入重定向输入。
解决方法
使用for循环代表while
for没有一次把文件内容缓存获取过来,代码段修改如下:
[[email protected] test]# for line in `cat fhosts`;do ssh $line hostname -i; done
192.168.0.42
192.168.0.43
[[email protected] test]#
使用while+ssh -n
通过man ssh查看-n参数的说明:
Redirects stdin from /dev/null (actually, prevents reading from stdin)
[[email protected] test]# cat fhosts | while read line; do ssh -n $line hostname -i;done
192.168.0.42
192.168.0.43
批量修改防火墙策略
[[email protected] test]# cat sshT.sh
#!/bin/bash
basePath=$(cd `dirname $0`; pwd)
iptablesFile=${basePath}/add_iptables.sh
dcvHostsFile=$1
forwardHostsFile=$2
if [ $# -lt 1 ]; then
echo "This script needs one args: file path of forwarding hosts file."
exit 1
fi
if [ ! -f ${dcvHostsFile} ]; then
echo "Dcv hosts file ${dcvHostsFile} not found."
exit 1
fi
for dcvHost in `cat ${dcvHostsFile}`; do
for forwardHost in $dcvHost `cat ${forwardHostsFile}`; do
echo ======$forwardHost
ssh [email protected]$forwardHost sh ${iptablesFile} $dcvHost $forwardHost
done
done
[[email protected] test]# cat add_iptables.sh
#!/bin/bash
port=8080
dcvHost=$1
forwardHost=$2
function writeIptables() {
echo ${forwardHost} ${port}
iptables -A INPUT -p tcp -m tcp --dport ${port} -j ACCEPT
iptables -t nat -A PREROUTING -d ${forwardHost} -p tcp -m tcp --dport ${port} -j DNAT --to-destination ${dcvHost}:${port}
iptables -t nat -A POSTROUTING -d ${dcvHost} -p tcp --dport ${port} -j SNAT --to-source ${forwardHost}
service iptables save
echo 1 > /proc/sys/net/ipv4/ip_forward
service iptables restart
}
writeIptables
[[email protected] test]# vim sshT.sh
[[email protected] test]# cat dcvhosts
192.168.0.41
[[email protected] test]# cat fhosts
192.168.0.42
192.168.0.43
[[email protected] test]# sh sshT.sh dcvhosts fhosts
======192.168.0.41
[email protected]'s password:
192.168.0.41 8080
iptables:将防火墙规则保存到 /etc/sysconfig/iptables:[确定]
iptables:将链设置为政策 ACCEPT:nat filter [确定]
iptables:清除防火墙规则:[确定]
iptables:正在卸载模块:[确定]
iptables:应用防火墙规则:[确定]
======192.168.0.42
192.168.0.42 8080
iptables:将防火墙规则保存到 /etc/sysconfig/iptables:[确定]
iptables:将链设置为政策 ACCEPT:nat filter [确定]
iptables:清除防火墙规则:[确定]
iptables:正在卸载模块:[确定]
iptables:应用防火墙规则:[确定]
======192.168.0.43
192.168.0.43 8080
iptables:将防火墙规则保存到 /etc/sysconfig/iptables:[确定]
iptables:将链设置为政策 ACCEPT:filter nat [确定]
iptables:清除防火墙规则:[确定]
iptables:正在卸载模块:[确定]
iptables:应用防火墙规则:[确定]
上一篇: 公网Linux服务器开启samba(smb)文件共享服务给家里电脑用
下一篇: Linux端口转发