码迷,mamicode.com
首页 > 编程语言 > 详细

python练习-(秒转时分秒,时分秒转秒)-对比linux中文件的上次更改时间跟当前时间相差多久。

时间:2019-03-06 15:00:52      阅读:321      评论:0      收藏:0      [点我收藏+]

标签:add   图片   sys   exe   client   span   div   练习   转换   

 

具体代码如下>

技术图片
import  paramiko,re,datetime,time
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())               #允许连接不在hosts文件中的主机
ssh.connect(hostname="10.124.198.75",port=8122,username="admin",password=De@2019eR)
stdin,stdout,stderr=ssh.exec_command("stat  /etc/passwd | grep Change")
stdin_sys,stdout_sys,stderr_sys=ssh.exec_command("date +%s")
change_time=re.search(Change: (.+)\\.,stdout.read().decode(utf-8)).group(1)
time1=datetime.datetime.strptime(change_time,"%Y-%m-%d %H:%M:%S")
change_time_new=str(time.mktime(time1.timetuple())).strip(.0)
sys_time=stdout_sys.read().decode(utf-8).strip()
time_stay=int(sys_time) - int(change_time_new)
print("距离上次更改:",datetime.timedelta(seconds=time_stay))
View Code

 

详解>

 

import paramiko,re,datetime,time

#连接linux服务器

ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #允许连接不在hosts文件中的主机
ssh.connect(hostname="10.124.198.75",port=8122,username="admin",password=De@2019eR)

 

#执行命令,获取到当前的系统时间(秒),和对应文件的修改时间。

#命令执行完后,会存储在stdout里面。
stdin,stdout,stderr=ssh.exec_command("stat /etc/passwd | grep Change")
stdin_sys,stdout_sys,stderr_sys=ssh.exec_command("date +%s")

 

#读取stdout中的内容,并进行正则匹配,得到想要文件更改时间,并存储到变量中,格式如:(2019-01-23 16:44:15)

change_time=re.search(Change: (.+)\\.,stdout.read().decode(utf-8)).group(1)

 

#将时间转换为秒,,"%Y-%m-%d %H:%M:%S" 此处的定义根据我们时间的格式进行更改
time1=datetime.datetime.strptime(change_time,"%Y-%m-%d %H:%M:%S")
change_time_new=str(time.mktime(time1.timetuple())).strip(.0)

#获取系统当前时间,并将当前时间减去上次修改的时间(秒 - 秒)
sys_time=stdout_sys.read().decode(utf-8).strip()
time_stay=int(sys_time) - int(change_time_new)

 

#秒转换为可识别的时间(距离上次更改: 41 days, 21:30:03)

print("距离上次更改:",datetime.timedelta(seconds=time_stay))

 

 

 

#执行测试

距离上次更改,41天22小时3分钟41秒

技术图片

 

python练习-(秒转时分秒,时分秒转秒)-对比linux中文件的上次更改时间跟当前时间相差多久。

标签:add   图片   sys   exe   client   span   div   练习   转换   

原文地址:https://www.cnblogs.com/xiaodai12138/p/10482959.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!