本文整理汇总了Python中smb.SMBConnection.SMBConnection.listShares方法的典型用法代码示例。如果您正苦于以下问题:Python SMBConnection.listShares方法的具体用法?Python SMBConnection.listShares怎么用?Python SMBConnection.listShares使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类smb.SMBConnection.SMBConnection
的用法示例。
在下文中一共展示了SMBConnection.listShares方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: performSMBConnection
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import listShares [as 别名]
def performSMBConnection(self, host='127.0.0.1', port=139, user="", passwd=""):
client_name =socket.gethostname()
smbClient = SMBConnection(user, passwd, client_name, "")
if smbClient.connect(host, port):
print "[+] SMB Connection Success ... "
print "[+] Listing the Shared resources"
for share in smbClient.listShares():
print "[*][*] Resource name: %s " %(share.name)
return True
else:
return False
示例2: main
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import listShares [as 别名]
def main(argv):
parser = OptionParser()
parser.add_option("-u", "--username",
help="Username that will be used for authentication")
parser.add_option("-p", "--password",
help="Password that will be used for authentication")
parser.add_option("-f", "--file", dest="filename",
help="Read systems list from file")
parser.add_option("-d", "--domain",
help="Domain name that will be used for authentication")
(options, args) = parser.parse_args()
with open(options.filename) as f:
for system_name in f:
try:
print('### Analyzing system: ' + system_name)
# parameterize an smb connection with a system
conn = SMBConnection(options.username,
options.password,
'enumerator',
system_name,
options.domain,
use_ntlm_v2=True,
sign_options=SMBConnection.SIGN_WHEN_SUPPORTED,
is_direct_tcp=True)
# establish the actual connection
connected = conn.connect(system_name,445)
try:
Response = conn.listShares(timeout=30) # obtain a list of shares
print('Shares on: ' + system_name)
for i in range(len(Response)): # iterate through the list of shares
print(" Share[",i,"] =", Response[i].name)
try:
# list the files on each share (recursivity?)
Response2 = conn.listPath(Response[i].name,'/',timeout=30)
print(' Files on: ' + system_name + '/' + " Share[",i,"] =",
Response[i].name)
for i in range(len(Response2)):
print(" File[",i,"] =", Response2[i].filename)
except:
print('### can not access the resource')
except:
print('### can not list shares')
except:
print('### can not access the system')
示例3: searchTarget
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import listShares [as 别名]
def searchTarget(self, host, username, password, domainname):
success = False
try:
self.display.debug('### Analyzing system: ' + host)
# parameterize an smb connection with a system
conn = SMBConnection(username,
password,
'enumerator',
host,
domainname,
use_ntlm_v2=True,
sign_options=SMBConnection.SIGN_WHEN_SUPPORTED,
is_direct_tcp=True)
# establish the actual connection
connected = conn.connect(host, 445)
if connected:
success = True
try:
Response = conn.listShares(timeout=30) # obtain a list of shares
self.display.debug('Shares on: ' + host)
for i in range(len(Response)): # iterate through the list of shares
self.display.debug(" Share[" + str(i) + "] =" + str(Response[i].name))
self.searchDir(host, conn, Response[i].name, '/')
# try:
# # list the files on each share (recursivity?)
# Response2 = conn.listPath(Response[i].name, '/', timeout=30)
# self.display.debug(' Files on: ' + host + '/' + " Share[" + str(i) + "] =" + str(Response[i].name))
# for i in range(len(Response2)):
# for pattern in self.filepatterns:
# try:
# re.compile(pattern)
# result = re.match(pattern, Response2[i].filename)
# if (result):
# # TODO
# # host.download(fpath, self.config["proofsDir"] + ip + fpath.replace("/", "_"))
# self.display.debug(" File[" + str(i) + "] =" + str(Response2[i].filename))
# except re.error:
# self.display.debug("Invalid File Pattern --> %s <--" % pattern)
# except:
# self.display.error('### can not access the resource')
except:
self.display.debug('### can not list shares')
except:
self.display.debug('### can not access the system (%s) (%s) (%s) (%s)' % (host, username, password, domainname))
return success
示例4: dotransform
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import listShares [as 别名]
def dotransform(args):
mt = MaltegoTransform()
mt.debug(pprint(args))
mt.parseArguments(args)
ip = mt.getVar("ip")
port = mt.getVar("port")
hostid = mt.getVar("hostid")
server = mt.getVar("server")
workgroup = mt.getVar("workgroup")
account = mt.getVar("account_used")
path = mt.getVar("sambapath")
domaindns = mt.getVar("domain_dns")
if not path:
path = "/"
conn = SMBConnection('admin', 'admin', "localhost", server, domain=workgroup, use_ntlm_v2=True,
is_direct_tcp=True)
conn.connect(ip, int(port))
shares = conn.listShares()
regex = re.compile("^\.{1,2}$")
for share in shares:
if not share.isSpecial and share.name not in ['NETLOGON', 'SYSVOL']:
sharename = unicodedata.normalize("NFKD", share.name).encode('ascii', 'ignore')
for file in conn.listPath(share.name, path):
filename = unicodedata.normalize("NFKD", file.filename).encode('ascii', 'ignore')
if file.isDirectory:
if not regex.match(filename):
entityname = "msploitego.SambaShare"
newpath = "{}/{}/".format(path,filename)
else:
continue
# subpath = conn.listPath(share.name, '/{}'.format(filename))
else:
entityname = "msploitego.SambaFile"
newpath = "{}/{}".format(path, filename)
sambaentity = mt.addEntity(entityname,"{}/{}/{}".format(ip,sharename,filename))
sambaentity.setValue("{}/{}/{}".format(ip,sharename,filename))
sambaentity.addAdditionalFields("ip", "IP Address", False, ip)
sambaentity.addAdditionalFields("port", "Port", False, port)
sambaentity.addAdditionalFields("server", "Server", False, server)
sambaentity.addAdditionalFields("workgroup", "Workgroup", False, workgroup)
sambaentity.addAdditionalFields("filename", "Filename", False, filename)
sambaentity.addAdditionalFields("path", "Path", False, newpath)
sambaentity.addAdditionalFields("hostid", "Hostid", False, hostid)
sambaentity.addAdditionalFields("domain_dns", "Domain DNS", False, domaindns)
sambaentity.addAdditionalFields("sharename", "Share Name", False, sharename)
mt.returnOutput()
mt.addUIMessage("completed!")
示例5: createList
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import listShares [as 别名]
def createList(self, ipList, outfile):
with open(outfile, 'a') as out:
for ip in ipList:
out.write("\n----------------------------------------------------\n")
print "Attempting to access: ", ip
out.write("Attempting to access: %s \n" % ip)
try:
conn = SMBConnection('guest', '', client_machine_name, remote_machine_name, use_ntlm_v2 = True)
conn.connect(ip, 139)
print "Connected to: ", ip
out.write("Connected To: %s \n" % ip)
except:
print "Failed to Connect"
out.write("Failed to Connect To: %s \n" % ip)
pass
try:
shareList = conn.listShares()
except:
out.write("Failed to open Shares\n")
shareList = None
if shareList != None:
for x in shareList:
try:
out.write("found Share: %s \n" % x.name)
print "Listing files in share: ", x.name
out.write("Listing files in share: %s \n" % x.name)
filelist = conn.listPath(x.name, '/')
for y in filelist:
if y.isDirectory:
print "DIR", y.filename
out.write("-----")
out.write(y.filename)
out.write('\n')
except:
print "failed to open share: ", x.name
out.write("Failed to open Share: %s \n" % x.name)
print "report written to outfile.txt"
示例6: FileServerConnection
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import listShares [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)
示例7: enumerateShares
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import listShares [as 别名]
def enumerateShares(ip):
print "Enumerating file shares on: ", ip
try:
conn = SMBConnection('guest', '', client_machine_name, remote_machine_name, use_ntlm_v2 = True)
conn.connect(ip, 445)
except:
print "Failed to Connect"
pass
try:
shareList = conn.listShares(timeout=10)
except:
shareList=None
if shareList != None:
shareNameList=[]
for x in shareList:
shareName = x.name
print shareName
return shareList
示例8: searchTarget
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import listShares [as 别名]
def searchTarget(self, host, username, password, domainname):
success = False
try:
self.display.debug('### Analyzing system: ' + system_name)
# parameterize an smb connection with a system
conn = SMBConnection(username,
password,
'enumerator',
host,
domainname,
use_ntlm_v2=True,
sign_options=SMBConnection.SIGN_WHEN_SUPPORTED,
is_direct_tcp=True)
# establish the actual connection
connected = conn.connect(system_name, 445)
success = True
try:
Response = conn.listShares(timeout=30) # obtain a list of shares
self.display.debug('Shares on: ' + system_name)
for i in range(len(Response)): # iterate through the list of shares
self.display.debug(" Share[", i, "] =", Response[i].name)
try:
# list the files on each share (recursivity?)
Response2 = conn.listPath(Response[i].name, '/', timeout=30)
self.display.debug(' Files on: ' + system_name + '/' + " Share[", i, "] =",
Response[i].name)
for i in range(len(Response2)):
for pattern in self.filepatterns:
match_list = fnmatch.filter(Response2[i].filename, pattern)
for fname in match_list:
# host.download(fpath, self.config["proofsDir"] + ip + fpath.replace("/", "_"))
self.display.debug(" File[", i, "] =", Response2[i].filename)
except:
self.display.error('### can not access the resource')
except:
self.display.error('### can not list shares')
except:
self.display.error('### can not access the system')
return success
示例9: get_smb_connection_with_shares
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import listShares [as 别名]
def get_smb_connection_with_shares(self, host):
connection = SMBConnection("RaspBerryPi$", "K3ks3!", "Testtest", host["hostname"], use_ntlm_v2 = True)
if not connection.connect(host["address"], 139):
raise NotConnectedError()
shares = connection.listShares()
smb_connection = {
"connection": connection,
"shares": [],
}
for share in shares:
if share.isSpecial or share.isTemporary:
continue
smb_connection["shares"].append(share)
return smb_connection
示例10: getNetworkShares
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import listShares [as 别名]
def getNetworkShares(self, hostip, hostname):
sharelist = []
self.sharecache_file = None
self.sharecache_file = eEnv.resolve("${sysconfdir}/enigma2/") + hostname.strip() + '.cache' #Path to cache directory
username = "guest"
password = ""
if os_path.exists(self.sharecache_file):
print '[Networkbrowser] Loading userinfo from ',self.sharecache_file
try:
self.hostdata = load_cache(self.sharecache_file)
username = self.hostdata['username']
password = self.hostdata['password']
except:
pass
for port in (445, 139):
try:
smbconn = SMBConnection(username, password, self._myhostname, hostname, is_direct_tcp=(port == 445))
if smbconn.connect(hostip, port=port, timeout=1):
print '[Networkbrowser] established SMB connection to %s:%d' % (hostip, port)
for share in smbconn.listShares(timeout=1):
if share.type == SharedDevice.DISK_TREE and not share.isSpecial:
sharelist.append( NetworkItemSmb(hostname, hostip, share.name.encode('utf-8'), 'Disk', comment=share.comments.encode('utf-8')) )
smbconn.close()
break
except Exception as e:
Log.w('[Networkbrowser] SMBConnection: ' + str(e))
try:
exports = showmount(hostip)
except IOError as e:
Log.w('[Networkbrowser] showmount: ' + str(e))
else:
for ex in exports:
sharelist.append( NetworkItemNfs(os_path.basename(ex['dir']), hostip, ex['dir'], ','.join(ex['groups'])) )
return sharelist
示例11: SMB_client
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import listShares [as 别名]
class SMB_client():
def __init__(self,username=None,password=None,smb_name=None,print_errors=True):
self.username = username
self.password = password
self.smb_name = smb_name
self.print_errors = print_errors
self.smb_ip = None
self.conn = None
self.service_name = None
self.my_name = None
self.error = None
self.tree = []
def getBIOSName(self, remote_smb_ip, timeout=5): # unused if dynamic IP
# ip -> smb name
try:
self.error = None
bios = NetBIOS()
srv_name = bios.queryIPForName(remote_smb_ip, timeout=timeout)
return srv_name[0]
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)
return None
def getIP(self):
# smb name -> ip
try:
self.error = None
bios = NetBIOS()
ip = bios.queryName(self.smb_name)
return ip[0]
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)
return None
def connect(self):
try:
self.error = None
self.my_name = gethostname() # iDevice name
self.smb_ip = self.getIP()
smb_structs.SUPPORT_SMB2 = True
self.conn = SMBConnection(self.username, self.password, self.my_name, self.smb_name, use_ntlm_v2 = True)
self.conn.connect(self.smb_ip, 139) #139=NetBIOS / 445=TCP
if self.conn:
shares = self.conn.listShares()
for share in shares:
if share.type == 0: # 0 = DISK_TREE
self.service_name = share.name
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 close(self):
try:
self.error = None
self.conn.close()
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 getRemoteDir(self, path, pattern):
try:
self.error = None
files = self.conn.listPath(self.service_name, path, pattern=pattern)
return files
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)
return None
def getRemoteTree(self,path=''):
try:
self.error = None
if path == '':
w = ''
else:
w = path+'/'
files = self.getRemoteDir(path, '*')
if files:
for file in files:
if file.filename[0] == '.':
continue
self.tree.append({'name':w+file.filename, 'isdir':file.isDirectory, 'size':file.file_size})
if file.isDirectory:
self.getRemoteTree(path=w+file.filename)
return self.tree
except Exception as e:
if self.print_errors:
#.........这里部分代码省略.........
示例12: SMB_Connect
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import listShares [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()
示例13: CommonCIFSShare
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import listShares [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
示例14: SMBConnection
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import listShares [as 别名]
# -*- coding: utf-8 -*-
from smb.SMBConnection import SMBConnection
from subprocess import *
import os
import sys
USER_NAME = 'NASのログインユーザ'
PASSWORD = 'NASのログインパス'
CLIENT_USER_NAME = 'クライアントのユーザ名'
SERVER_NAME = 'NASのホスト名'
SERVER_IP = 'NASのIP'
if __name__ == '__main__':
conn = SMBConnection(USER_NAME, PASSWORD, CLIENT_USER_NAME, SERVER_NAME)
conn.connect(SERVER_IP)
for path in conn.listShares():
if not os.path.exists('/Volumes/' + path.name):
os.mkdir('/Volumes/' + path.name)
try:
res = run(['mount_smbfs', '//'+USER_NAME +'@'+SERVER_NAME+ '/' + path.name, '/Volumes/' + path.name], stdout=PIPE)
sys.stdout.buffer.write(res.stdout)
except:
sys.stdout.buffer.write("ERROR")
示例15: SMBConnection
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import listShares [as 别名]
#!/usr/bin/python
import sys
from smb.SMBConnection import SMBConnection
host = sys.argv[1]
domain = ""
conn = SMBConnection("guest", "guest", "workgroup", host, domain, True, 2)
conn.connect(host, 139)
shares = conn.listShares()
for share in shares:
print("Share: %s" % share.name)
conn.close()