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

 

具体代码如下>

import  paramiko,re,datetime,time
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())              
ssh.connect(hostname="10.124.198.75",port=8122,username="admin",password='****',timeout=2)
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='****')

 

#执行命令,获取到当前的系统时间(秒),和对应文件的修改时间。
#命令执行完后,会存储在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" 此处的定义根据我们时间的格式进行更改(2019-01-23 16:44:15) 
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秒

 

posted @ 2019-03-06 14:19  xiaodai12138  Views(619)  Comments(0Edit  收藏  举报