python 递归删除目录和文件_pysmb递归删除文件夹子文件夹和文件

该博客介绍了一个使用Python的pysmb库实现的函数,用于递归删除SMB服务器上的目录和文件。通过设置dry_run参数可以进行测试而不实际删除。首先建立SMB连接,然后遍历指定共享文件夹下的所有文件和子目录,对每个目录进行递归操作,最后删除文件和子目录。
摘要由CSDN通过智能技术生成

这是Michael为python 2.7编写的函数:from smb.SMBConnection import SMBConnection

dry_run = True # Set to True to test if all files/folders can be "walked". Set to False to perform the deletion.

userID = 'myuser'

password = 'mypassword'

client_machine_name = 'testclient' # Usually safe to use 'testclient'

server_name = 'MYSERVER' # Must match the NetBIOS name of the remote server

server_ip = '192.168.1.10' # Must point to the correct IP address

domain_name = '' # Safe to leave blank, or fill in the domain used for your remote server

shared_folder = 'smbtest' # Set to the shared folder name

conn = SMBConnection(userID, password, client_machine_name, server_name, domain=domain_name, use_ntlm_v2=True, is_direct_tcp=True)

conn.connect(server_ip, 445)

def walk_path(path):

print 'Walking path', path

for p in conn.listPath(shared_folder, path):

if p.filename!='.' and p.filename!='..':

parentPath = path

if not parentPath.endswith('/'):

parentPath += '/'

if p.isDirectory:

walk_path(parentPath+p.filename)

print 'Deleting folder (%s) in %s' % ( p.filename, path )

if not dry_run:

conn.deleteDirectory('smbtest', parentPath+p.filename)

else:

print 'Deleting file (%s) in %s' % ( p.filename, path )

if not dry_run:

conn.deleteFiles('smbtest', parentPath+p.filename)

# Start and delete everything at shared folder root

walk_path('/')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值