最近项目上新上了2台时钟设备,需要把网络内的一百多台linux服务器配置NTP服务,实现和时钟设备时间同步,为了避免每台设备挨个配置的麻烦,写了一个python脚本。脚本分3个文件,第一个是python脚本,第二个是主机清单,里面包含IP地址和密码两项,第三个是命令文件,包含从yum安装ntp软件包到配置ntp.conf参数文件到启动NTP服务所要执行的操作语句。执行脚本,调用这个两个文件,网络内的所有服务器NTP安装配置起服务就完成了。事实上这个脚本可以做各种批量操作,只需要改一下命令文件即可,脚本不用做任何更改。
cat cmd_list.txt
###配置NTP文件
mv /etc/ntp.conf /etc/ntp.conf.bak
echo 'server 192.168.5.200' >> /etc/ntp.conf
echo 'Fudge 192.168.5.200 stratum 10' >> /etc/ntp.conf
###安装NTP软件包并启动NTP服务
rm /etc/yum.repos.d/*.repo
echo '[ol7_u5_base]' >> /etc/yum.repos.d/local.repo
echo 'name=Oracle Linux' >> /etc/yum.repos.d/local.repo
echo 'baseurl=http://192.168.5.250/redhat7' >> /etc/yum.repos.d/local.repo
echo 'gpgkey=http://192.168.5.250/redhat7/RPM-GPG-KEY-redhat-release' >> /etc/yum.repos.d/local.repo
echo 'gpgcheck=1' >> /etc/yum.repos.d/local.repo
echo 'enabled=1' >> /etc/yum.repos.d/local.repo
yum install -y ntp*
systemctl start ntpd
systemctl enable ntpd
cat host.txt
192.168.5.1 pass1
192.168.5.2 pass2
...
192.168.5.254 pass254
cat auto_ntp.py
import paramiko
import time
import sys
import socket
host = open(sys.argv[1])
host_list = []
username="root"
for hosta in host.readlines():
host_list.append(hosta.strip().split())
f = open('log.txt', 'a')
cmd = open(sys.argv[2])
for hostname,password in host_list:
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh_client.connect(hostname=hostname, username=username, password=password)
print("Successfull connected to ", hostname)
cmd.seek(0)
stdin, stdout, stderr = ssh_client.exec_command('hostname')
f.write(hostname ' ' stdout.read().decode('utf-8') "n")
for ccc in cmd.readlines():
c = ccc.strip()
stdin, stdout, stderr = ssh_client.exec_command(c)
f.write(stdout.read().decode('utf-8') "n")
f.write(stderr.read().decode('utf-8') "n")
except paramiko.ssh_exception.AuthenticationException:
print("User authentication failed for " username)
except socket.error:
print(hostname " is not reachable.")
cmd.close()
f.close()
ssh_client.close()
执行:
python auto_ntp.py host.txt cmd_list.txt
批量做其他任意操作均可,只要修改cmd_list.txt文件中的操作语句即可
来自 “ 开源世界 ” ,链接:http://ym.baisou.ltd/post/544.html,如需转载,请注明出处,否则将追究法律责任。