python脚本实现Linux系统对时

2019/03/14 22:21
阅读数 10
 1 # _*_ coding:utf-8 _*_
 2 
 3 """
 4 __title__ = 'date update'
 5 __author__ = 'Lucky'
 6 __date__ = '2018/08/09'
 7 """
 8 
 9 import paramiko
10 import os
11 
12 class CTP_sec_ntp_date:
13 
14     def __init__(self,host_ip,username,password,command,port=22):
15         self.ssh = paramiko.SSHClient()
16         self.host_ip = host_ip
17         self.username = username
18         self.password = password
19         self.command = command
20         self.port = port
21 
22     def ssh_ntp_server(self):
23         self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
24         try:
25             self.ssh.connect(self.host_ip, self.port, self.username, self.password, timeout=8)
26             print("SSH连接(%s)成功." %self.host_ip)
27             return True
28         except Exception as e:
29             print("SSH(%s)连接失败,错误代码为:%s" %(self.host_ip,e))
30             return False
31 
32     def exec_ssh_command(self):
33         stdin,stdout,stderr = self.ssh.exec_command(self.command)
34         result_out,result_err = stdout.read(),stderr.read()
35         result_all = result_out if result_out else result_err
36         with open('/root/Sam_py/date_update.log','a+') as obj_log:
37             obj_log.write(result_all.decode() + "\n")
38 
39     def logout(self):
40         self.ssh.close()
41 
42 def main():
43     username = "root"
44     password = "123456"
45     ntp_date_update = "/usr/sbin/ntpdate -u 192.168.2.3"
46 
47     get_cmd_ip = 'cat /etc/hosts | awk \'{print $1}\' | grep -vE "#|127.0.0.1" | sort | uniq'
48     get_hosts_ip = os.popen(get_cmd_ip)
49     get_hosts_result = get_hosts_ip.readlines()
50 
51     for line in get_hosts_result:
52         client_ssh = CTP_sec_ntp_date(line.strip(), username, password, ntp_date_update)
53         if client_ssh.ssh_ntp_server():
54             client_ssh.exec_ssh_command()
55             client_ssh.logout()
56 
57 
58 if __name__ == "__main__":
59     main()

 

展开阅读全文
加载中

作者的其它热门文章

打赏
0
0 收藏
分享
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部