python脚本实现Linux系统对时

 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()

 

转载于:https://www.cnblogs.com/zhangweiyi/p/10534040.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值