本文整理汇总了Python中smb.SMBConnection.SMBConnection.deleteFiles方法的典型用法代码示例。如果您正苦于以下问题:Python SMBConnection.deleteFiles方法的具体用法?Python SMBConnection.deleteFiles怎么用?Python SMBConnection.deleteFiles使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类smb.SMBConnection.SMBConnection
的用法示例。
在下文中一共展示了SMBConnection.deleteFiles方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: SmbClient
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import deleteFiles [as 别名]
class SmbClient(object):
def __init__(self,ip,username,password,sharename):
self.ip = ip
self.username = username
self.password = password
self.sharename = sharename
def connect(self):
self.server = SMBConnection(self.username,
self.password,client,netbios_name,use_ntlm_v2=True)
self.server.connect(self.ip,139)
def upload(self,file):
data = open(file,'rb')
file = '/' + file
self.server.storeFile(self.sharename,file,data)
print "file has been uploaded"
def download(self,file):
fileobj = open(file,'wb')
self.server.retrieveFile(self.sharename,fileobj)
print "file has been downloaded in current dir"
def delete(self,file):
'remove file from remote share'
file = '/' + file
self.server.deleteFiles(self.sharename,file)
def list(self):
' list files of remote share '
filelist = self.server.listPath(self.sharename,'/')
for f in filelist:
print f.filename
示例2: FileServerConnection
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import deleteFiles [as 别名]
class FileServerConnection(object):
"""Connection to a Samba file server"""
def __init__(self, ip, port, clientName, serverName, username, password):
self.conn = SMBConnection(username, password, clientName, serverName)
self.conn.connect(ip, port)
try:
shares = self.conn.listShares()
sharesStr = ", ".join("{0.name} ({0.comments})".format(s) for s in shares)
logging.info("Visible shares on {} ({}:{}): {}".format(serverName,
ip,
port,
sharesStr))
except smb.base.NotReadyError as e:
raise FileServerException(e)
def append(self, share, path, data):
try:
# Get the existing contents of the file.
file = StringIO()
try:
self.conn.retrieveFile(share, path, file)
except smb.smb_structs.OperationFailure as e:
# The file might not exist yet.
if not e.message.endswith("Unable to open file"):
# Something else went wrong.
raise
# Append the data.
file.write(data)
file.seek(0)
# NOTE: Apparently storeFile fails if the target file exists. It
# must be deleted first.
# TODO: Rename the old file instead of deleting until the store
# operation is completed succesfully?
try:
self.conn.deleteFiles(share, path)
except smb.smb_structs.OperationFailure as e:
# The file might not exist yet.
if not e.message.endswith("Delete failed"):
# Something else went wrong.
raise
self.conn.storeFile(share, path, file)
except smb.smb_structs.OperationFailure as e:
raise FileServerException(e.message)
示例3: check_ip
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import deleteFiles [as 别名]
def check_ip(ip):
global timeout, verbose, user, password, domain, print_lock, debug
try:
# Connect to socket
conn = SMBConnection(user, password, "detect_unsecure_admin_share.py", ip, domain=domain, use_ntlm_v2=True, is_direct_tcp=True)
assert conn.connect(ip, 445, timeout=timeout)
if debug:
with print_lock:
print("#DEBUG: Successfully connected to ip: {}".format(ip))
f = tempfile.TemporaryFile()
f.write("Hello World!\n")
try:
conn.storeFile("C$", "detect_unsecure_admin_share.tmp", f, timeout=timeout)
with print_lock:
print("#SUCCESS: Successfully stored test file on C$ admin share at ip: {}".format(ip))
conn.deleteFiles("C$", "detect_unsecure_admin_share.tmp", timeout=timeout)
if debug:
with print_lock:
print("#DEBUG: Successfully deleted test file from C$ admin share at ip: {}".format(ip))
except Exception as ex:
if debug:
with print_lock:
print("#ERROR: Could not store file on C$ admin share on ip: {}".format(ip))
finally:
conn.close()
f.close()
except socket.timeout:
if debug:
with print_lock:
print("#DEBUG: Connection timed out for ip: {}".format(ip))
except Exception as ex:
if debug:
with print_lock:
print("#DEBUG: Connection failure for ip: {}".format(ip))
示例4: SMB_client
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import deleteFiles [as 别名]
#.........这里部分代码省略.........
offset = 0
transmit =0
while True:
if not buffersize:
file_attributes, filesize = self.conn.retrieveFile(self.service_name, path+filename, file_obj)
else:
file_attributes, filesize = self.conn.retrieveFileFromOffset(self.service_name, path+filename, file_obj,offset=offset,max_length=buffersize)
if callback:
transmit = transmit + filesize
callback(transmit)
file_obj.seek(offset)
for line in file_obj:
fw.write(line)
offset = offset + filesize
if (not buffersize) or (filesize == 0):
break
fw.close()
#print('download finished')
except Exception as e:
if self.print_errors:
print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
else:
self.error = 'Error on line {}'.format(sys.exc_info()[-1].tb_lineno) + str(type(e).__name__) + str(e)
def upload(self, path, filename,buffersize=None,callback=None, local_path=None):
try:
self.error = None
#print('Upload = ' + path + filename)
#print('Size = %.1f kB' % (os.path.getsize(filename) / 1024.0))
#print('start upload')
if local_path:
file_obj = open(local_path+filename, 'rb')
else:
file_obj = open(filename, 'rb')
offset = 0
while True:
if not buffersize:
filesize = self.conn.storeFile(self.service_name, path+filename, file_obj)
break
else:
buffer_obj = file_obj.read(buffersize)
if buffer_obj:
buffer_fileobj = BytesIO()
buffer_fileobj.write(buffer_obj)
buffer_fileobj.seek(0)
offset_new = self.conn.storeFileFromOffset(self.service_name, path+filename, buffer_fileobj, offset=offset, truncate=False)
#return the file position where the next byte will be written.
offset = offset_new
if callback:
callback(offset)
else:
break
file_obj.close()
#print('upload finished')
except Exception as e:
if self.print_errors:
print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
else:
self.error = 'Error on line {}'.format(sys.exc_info()[-1].tb_lineno) + str(type(e).__name__) + str(e)
def delete_remote_file(self,path, filename):
try:
self.error = None
self.conn.deleteFiles(self.service_name, path+filename)
#print('Remotefile ' + path + filename + ' deleted')
except Exception as e:
if self.print_errors:
print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
else:
self.error = 'Error on line {}'.format(sys.exc_info()[-1].tb_lineno) + str(type(e).__name__) + str(e)
def createRemoteDir(self, path):
try:
self.error = None
self.conn.createDirectory(self.service_name, path)
except Exception as e:
if self.print_errors:
print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
else:
self.error = 'Error on line {}'.format(sys.exc_info()[-1].tb_lineno) + str(type(e).__name__) + str(e)
def removeRemoteDir(self,path):
try:
self.error = None
self.conn.deleteDirectory(self.service_name, path)
except Exception as e:
if self.print_errors:
print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
else:
self.error = 'Error on line {}'.format(sys.exc_info()[-1].tb_lineno) + str(type(e).__name__) + str(e)
def renameRemoteFileOrDir(self,old_path, new_path):
try:
self.error = None
self.conn.rename(self.service_name, old_path, new_path)
except Exception as e:
if self.print_errors:
print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
else:
self.error = 'Error on line {}'.format(sys.exc_info()[-1].tb_lineno) + str(type(e).__name__) + str(e)
示例5: SMB_Connect
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import deleteFiles [as 别名]
def SMB_Connect(host,sharename,user,password,folder,writeable):
'''connects to a share with the given credentials and checks if it's writeable or not
host: hostname (FQDN)
sharename: Name of the share
username: username
password: password
writeable: if set to True, it will check if the share is writeable
'''
check_passed=False
check_file=''.join(['/', folder,'/nagioscheck.txt'])
hostname = host.split('.')
host_ip= socket.gethostbyname(host)
conn = SMBConnection(user, password, socket.gethostname(), hostname[0], use_ntlm_v2 = True)
try:
conn.connect(host_ip, 139)
except:
print "Connection to Host failed"
sys.exit(status['CRITICAL'])
if conn.auth_result:
#only check if share is listed
if not writeable:
shares = conn.listShares()
for share in shares:
if sharename == share.name:
print "Found ",share.name
check_passed = True
break
else:
#schreiben
check_value = "File Created from nagios "+str(datetime.now())
file_obj = tempfile.NamedTemporaryFile()
file_obj.write(check_value)
file_obj.flush()
file_obj.seek(0)
try:
conn.storeFile(sharename, check_file, file_obj)
except:
check_passed=False
file_obj.close()
#lesen
file_obj = tempfile.NamedTemporaryFile()
try:
file_attributes, filesize = conn.retrieveFile(sharename, check_file, file_obj)
file_obj.seek(0)
file_content= file_obj.read()
if file_content == check_value:
check_passed=True
except:
check_passed=False
file_obj.close()
conn.close()
#file loeschen
try:
conn = SMBConnection(user, password, socket.gethostname(), hostname[0], use_ntlm_v2 = True)
conn.connect(host_ip, 139)
conn.deleteFiles(sharename, check_file)
except Exception, e:
check_passed=False
conn.close()
示例6: CommonCIFSShare
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import deleteFiles [as 别名]
class CommonCIFSShare(object):
"""
Handle CIFS shares
"""
def __init__(self):
self.smb_conn = None
def com_cifs_connect(self, ip_addr, user_name='guest', user_password=''):
"""
Connect to share
"""
server_name = 'Server'
client_name = 'My Computer'
self.smb_conn = SMBConnection(user_name, user_password, client_name, server_name,
use_ntlm_v2=True)
self.smb_conn.connect(ip_addr, 139)
def com_cifs_share_list_by_connection(self):
"""
List shares
"""
share_names = []
for row_data in self.smb_conn.listShares():
share_names.append(row_data.name)
return share_names
def com_cifs_share_file_list_by_share(self, share_name, path_text='/'):
"""
List files in share
"""
file_names = []
for row_data in self.smb_conn.listPath(share_name, path_text):
common_global.es_inst.com_elastic_index('info', {'stuff': row_data.filename})
file_names.append(row_data.filename)
return file_names
def com_cifs_share_directory_check(self, share_name, dir_path):
"""
Verify smb directory
"""
# try due to fact invalid file/path freaks out the connection
try:
return self.smb_conn.getAttributes(share_name, dir_path).isDirectory
except:
pass
return False
def com_cifs_share_file_dir_info(self, share_name, file_path):
"""
Get specific path/file info
"""
return self.smb_conn.getAttributes(share_name, file_path)
def com_cifs_share_file_upload(self, file_path):
"""
Upload file to smb
"""
self.smb_conn.storeFile(os.path.join(
self.sharename, file_path), open(file_path, 'rb'))
def com_cifs_share_file_download(self, file_path):
"""
Download from smb
"""
self.smb_conn.retrieveFile(self.sharename, open(file_path, 'wb'))
def com_cifs_share_file_delete(self, share_name, file_path):
"""
Delete from smb
"""
self.smb_conn.deleteFiles(os.path.join(share_name, file_path))
def com_cifs_close(self):
"""
Close connection
"""
self.smb_conn.close()
def com_cifs_walk(self, share_name, file_path='/'):
"""
cifs directory walk
"""
dirs, nondirs = [], []
for name in self.smb_conn.listPath(share_name, file_path):
if name.isDirectory:
if name.filename not in ['.', '..']:
dirs.append(name.filename)
else:
nondirs.append(name.filename)
yield file_path, dirs, nondirs
for name in dirs:
# new_path = file_path + '\\' + name
# for ndx in self.com_cifs_walk(share_name, new_path):
for ndx in self.com_cifs_walk(share_name, os.path.join(file_path, name)):
yield ndx
示例7: handle_JobMessage
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import deleteFiles [as 别名]
def handle_JobMessage(self, msg):
try:
self.errors = ""
def set_status(s):
self.status = s
self.log.info(s)
set_status("Received job")
sim = msg.get_property("msg")
user_id = sim["user_id"]
sim_id = sim["sim_id"]
job_id = sim["job_id"]
sample = sim["sample"]
jar_hash = sim["jar_hash"]
set_status("Starting job %d %d %s %d" % (job_id, sim_id, user_id, sample))
self.send_status("Starting job", job_id, sim_id, user_id, sample)
out_name = os.path.join("results", self.worker_id)
jar_name = os.path.join("jars", "%s_%s.run" % (jar_hash, self.worker_id))
xml_name = os.path.join("xmls", "%s_%i_%i_%i.xml" % (user_id, job_id, sim_id, sample))
set_status("Writing input files")
self.send_status("Writing input files", job_id, sim_id, user_id, sample)
xml = construct_xml(sim, out_name)
if not xml:
self.errors = "Error constructing XML (check idrefs?)"
set_status(self.errors)
raise Exception(self.errors)
with open(xml_name, "w") as xml_file:
xml_file.write(xml)
if not os.path.exists(jar_name):
with open(jar_name, "wb") as jar_file:
jar_file.write(get_file(jar_hash))
process = Popen(["java", "-server", "-Xmx2400M", "-jar", jar_name, xml_name], stdout=PIPE, stderr=PIPE)
p_timer = time.time()
# Non-blocking process io: http://stackoverflow.com/questions/375427/non-blocking-read-on-a-subprocess-pipe-in-python
def enqueue_output(stream, queue, running):
while running.value:
queue.put(stream.read(128))
def create_thread_queue(stream, running):
q = Queue()
t = Thread(target=enqueue_output, args=(stream, q, running))
t.daemon = True
t.start()
return q
running = Value("b", True)
out_q = create_thread_queue(process.stdout, running)
err_q = create_thread_queue(process.stderr, running)
set_status("Execution started")
while process.poll() == None:
try:
status = out_q.get(timeout=0.1)
if time.time() - p_timer > 0.3:
s = re.findall("\(.*?\)", status)[-1]
self.send_status(s, job_id, sim_id, user_id, sample)
p_timer = time.time()
except:
pass
# Stop the queue threads
running.value = False
# Get the error if it exists, only needed here because thread is constantly checking the pipe
while not err_q.empty():
self.errors += err_q.get(False)
os.remove(xml_name)
set_status("Execution finished")
if self.errors:
set_status(self.errors)
raise Exception("CIlib error")
set_status("Posting results")
with open(out_name, "r") as result_file:
conn = SMBConnection(SMB_USER, SMB_PWD, "", "", use_ntlm_v2=True)
assert conn.connect(SMB_IP, timeout=SMB_TIMEOUT)
newFile = "%s_%i_%i_%i.txt" % (user_id, job_id, sim_id, sample)
existingFiles = [i.filename for i in conn.listPath(SMB_SHARE, "/")]
if newFile in existingFiles:
conn.deleteFiles(SMB_SHARE, newFile, timeout=SMB_TIMEOUT)
conn.storeFile(SMB_SHARE, newFile, result_file, timeout=SMB_TIMEOUT)
conn.close()
#.........这里部分代码省略.........