您好,登錄后才能下訂單哦!
最近項目上新上了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文件中的操作語句即可
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。