栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python删除服务器文件代码示例

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python删除服务器文件代码示例

本文主要研究的是Python编程删除服务器文件,具体实现 代码如下。

实例1
#coding:utf-8
import paramiko
"""
  创建文件 删除文件 root权限
"""

ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname="192.168.1.37",port=22,username="test",password="test")
stdin,stdout,stderr=ssh.exec_command('sudo -i touch /a.txt',get_pty=True)
stdin.write("testn")
# stdin.write("n")
stdin.close()
stdout.close()
print(stderr.read())
stderr.close()
stdin,stdout,stderr=ssh.exec_command('sudo -i rm -f /a.txt',get_pty=True)
stdin.write("testn")
# stdin.write("n")
stdin.close()
print(stderr.read())
ssh.close()
实例2

用户微信目录因常年累月用户上传图片较多,造成硬盘资源将耗尽,但客户要求至少保存一个月的文件,

然而几十万张图片的文件夹,不论是打开,排序删除都是非常消耗服务器性能的,因为装载这10多个G的文件必然会造成内存和CPU的大量消耗,因此写了python脚本来自动删除30天以前的文件

代码如下:

#-*- coding:utf-8 -*-
import os
import time
import datetime

f = list(os.listdir(‘G:\qtp‘))
for i in range(len(f)):
  filedate = os.path.getmtime(‘G:\qtp\‘ + f[i])
  time1 = datetime.datetime.fromtimestamp(filedate).strftime(‘%Y-%m-%d‘)
  date1 = time.time()
  num1 =(date1 - filedate)/60/60/24
  if num1 >= 30:
    os.remove(‘G:\qtp\‘ + f[i])
    print("已删除文件:%s : %s" % (time1, f[i]))
else:
  print("there are no file more than 30 days")

结果:

总结

以上就是本文关于python删除服务器文件代码示例的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/31119.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号