本文整理汇总了Python中smb.SMBConnection.SMBConnection.listPath方法的典型用法代码示例。如果您正苦于以下问题:Python SMBConnection.listPath方法的具体用法?Python SMBConnection.listPath怎么用?Python SMBConnection.listPath使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类smb.SMBConnection.SMBConnection
的用法示例。
在下文中一共展示了SMBConnection.listPath方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: SmbClient
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import listPath [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: transfer
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import listPath [as 别名]
def transfer(self, uid, old_code, new_code):
""" Sync a child transfer with GP: rename pictures and log a note. """
# Retrieve configuration
smb_user = config.get('smb_user')
smb_pass = config.get('smb_pwd')
smb_ip = config.get('smb_ip')
smb_port = int(config.get('smb_port', 0))
if not (smb_user and smb_pass and smb_ip and smb_port):
return False
# Rename files in shared folder
smb_conn = SMBConnection(smb_user, smb_pass, 'openerp', 'nas')
if smb_conn.connect(smb_ip, smb_port):
gp_old_pic_path = "{0}{1}/".format(config.get('gp_pictures'),
old_code[:2])
gp_new_pic_path = "{0}{1}/".format(config.get('gp_pictures'),
new_code[:2])
pic_files = smb_conn.listPath('GP', gp_old_pic_path)
for file in pic_files:
filename = file.filename
if filename.startswith(old_code):
new_name = filename.replace(old_code, new_code)
smb_conn.rename('GP', gp_old_pic_path + filename,
gp_new_pic_path + new_name)
# Rename child code in GP tables
self.query("UPDATE ENFANTS SET CODE = %s WHERE CODE = %s",
[new_code, old_code])
self.query("UPDATE Poles SET CODESPE = %s WHERE CODESPE = %s",
[new_code, old_code])
self.query("UPDATE Affectat SET CODESPE = %s WHERE CODESPE = %s",
[new_code, old_code])
return True
示例3: transfer
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import listPath [as 别名]
def transfer(self, uid, old_code, new_code):
""" Sync a child transfer with GP: rename pictures and log a note. """
# Retrieve configuration
smb_user = config.get("smb_user")
smb_pass = config.get("smb_pwd")
smb_ip = config.get("smb_ip")
smb_port = int(config.get("smb_port", 0))
if not (smb_user and smb_pass and smb_ip and smb_port):
return False
# Rename files in shared folder
smb_conn = SMBConnection(smb_user, smb_pass, "openerp", "nas")
if smb_conn.connect(smb_ip, smb_port):
gp_old_pic_path = "{0}{1}/".format(config.get("gp_pictures"), old_code[:2])
gp_new_pic_path = "{0}{1}/".format(config.get("gp_pictures"), new_code[:2])
pic_files = smb_conn.listPath("GP", gp_old_pic_path)
for file in pic_files:
filename = file.filename
if filename.startswith(old_code):
new_name = filename.replace(old_code, new_code)
smb_conn.rename("GP", gp_old_pic_path + filename, gp_new_pic_path + new_name)
# Rename child code in Poles table
self.query("UPDATE Poles SET CODESPE = %s WHERE CODESPE = %s", [old_code, new_code])
return True
示例4: enumerateShareName
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import listPath [as 别名]
def enumerateShareName(ip,shareName):
print "Attempting to access: //"+ip+"/"+shareName
try:
conn = SMBConnection('guest', '', client_machine_name, remote_machine_name, use_ntlm_v2 = True)
conn.connect(ip, 445)
except:
print "Failed to Connect"
pass
filelist = conn.listPath(shareName, "")
for y in filelist:
if y.isDirectory:
if y.filename!="." and y.filename!="..":
found=False
for z in ignoreList:
if z in str(y.filename).lower():
found=True
if found==False:
addDirList.append([ip,shareName,"\\"+y.filename])
getShares(ip,shareName,"\\"+y.filename)
else:
shareName1=shareName.replace("//","/")
fullPath = ip+"/"+shareName1+"/"+y.filename
fullPath = fullPath.replace("///","/")
fullPath = fullPath.replace("//","/")
fullPath = "//"+fullPath
print fullPath
allFilesList.append([ip,shareName1,fullPath])
for format in formatList:
if format in str(y.filename).lower():
docList.append(["docs",ip,fullPath])
fileMatch(ip,fullPath)
示例5: getShares
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import listPath [as 别名]
def getShares(ip,shareName,folderPath):
conn = SMBConnection('guest', '', client_machine_name, remote_machine_name, use_ntlm_v2 = True)
conn.connect(ip, 445)
filelist = conn.listPath(shareName, folderPath)
for y in filelist:
if y.isDirectory:
if y.filename!="." and y.filename!="..":
found=False
for z in ignoreList:
if z in str(y.filename).lower():
found=True
if found==False:
getShares(ip,shareName,"\\"+folderPath+"\\"+y.filename)
else:
folderPath1=folderPath.replace("\\","/")
folderPath1=folderPath1.replace("//","/")
shareName1=shareName.replace("//","/")
fullPath = ip+"/"+shareName1+folderPath1+"/"+y.filename
fullPath = fullPath.replace("///","/")
fullPath = fullPath.replace("//","/")
fullPath = "//"+fullPath
print fullPath
allFilesList.append([ip,shareName1,fullPath])
for format in formatList:
if format in str(y.filename).lower():
docList.append(["docs",ip,fullPath])
fileMatch(ip,fullPath)
示例6: show_dir
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import listPath [as 别名]
def show_dir(path):
conn = SMBConnection(USERNAME, PASSWORD, MY_NAME, REMOTE_NAME, use_ntlm_v2=False)
conn.connect(SERVER_IP, PORT)
re = conn.listPath('Share', os.path.join('/ESAP/Hand-Out/', path))
conn.close()
for i in re:
i.link = os.path.join(path, i.filename)
return render_template('hello.html', files=re)
示例7: run
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import listPath [as 别名]
def run(self):
try:
conn = SMBConnection(MiSeqServerData.username, MiSeqServerData.password, MiSeqServerData.myRequestIdentifier, MiSeqServerData.serverName, domain=MiSeqServerData.domain, use_ntlm_v2 = True)
conn.connect(MiSeqServerData.host, MiSeqServerData.port)
#Get files names of fastq.gz files that correspond to subLibraryID (e.g. one if single, two if paired-end read)
print("Reading fastq.gz file for "+self.subLibraryID)
fastqFiles = []
try:
sharedFileObjs = conn.listPath(MiSeqServerData.sharedFolder, '/MiSeqOutput/'+self.mainLibraryFolder+'/Data/Intensities/BaseCalls')
for a in sharedFileObjs:
#If fastq.gz file...
if (a.filename.endswith("fastq.gz")):
#And correct sample ID
if (a.filename.startswith(self.subLibraryID) or a.filename.startswith(self.subLibraryID.replace("_", "-"))): #For some reason, MiSeq sampleSheet.csv will escape hyphens
fastqFiles.append(a.filename)
#Now fetch and write fastq.gz files to local machine
director = urllib.request.build_opener(SMBHandler)
fh = director.open('smb://'+MiSeqServerData.username+':'+MiSeqServerData.password+'@secret.jbei.org/miseq/MiSeqOutput/'+self.mainLibraryFolder+'/Data/Intensities/BaseCalls/'+a.filename).read()
f = open(self.outputFolder+"/"+a.filename, 'wb')
f.write(fh)
f.close()
except SMBTimeout:
print("SMB server timed out")
return
except NotReadyError:
print("Authentication with SMB server failed")
return
except NotConnectedError:
print("Disconnected from SMB server")
return
except Exception as ex:
print("Error retrieving fastq.gz files "+str(ex))
return
print("Writing metadata for "+self.subLibraryID)
for filename in fastqFiles:
#Get metadata for project's pre.libraries.info file
proposalID = self.subLibraryID
libraryName = "libName"
genus = "genus"
species = "species"
strain = "strain"
metaData = [proposalID, libraryName, self.outputFolder+"/"+filename, genus, species, strain]
#Save metadata to be later printed to libraries.info file
self.metadata += ("\t").join(metaData)+"\n";
except SMBTimeout:
print("SMB server timed out")
return
except NotReadyError:
print("Authentication with SMB server failed")
return
except NotConnectedError:
print("Disconnected from SMB server")
return
except Exception as ex:
print("Error retrieving libraries from SMB server "+str(ex))
return
示例8: getFileList
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import listPath [as 别名]
def getFileList():
filename_list = []
conn = SMBConnection(smb_credential['user'], smb_credential['password'], "", smb_credential['hostname'], use_ntlm_v2 = True)
conn.connect(smb_credential['host'], 139)
file_list = conn.listPath(short_group_name, u'/Audit/每周会议记录/%s-%s年%s学期会议记录' % (short_group_name, cur_year, cur_semester))
for f in file_list:
if f.filename != '.' and f.filename != '..':
filename_list.append(f.filename)
conn.close()
return filename_list
示例9: dotransform
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import listPath [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")
if not server:
server = mt.getVar("machinename")
workgroup = mt.getVar("workgroup")
path = mt.getVar("path")
domaindns = mt.getVar("domain_dns")
sharename = mt.getVar("sharename")
if not workgroup:
workgroup = "WORKGROUP"
# conn = SMBConnection('', '', "localhost", server, domain=workgroup, use_ntlm_v2=True,is_direct_tcp=True)
conn = SMBConnection('', '', "localhost", server, domain=workgroup, use_ntlm_v2=True)
conn.connect(ip, int(port))
regex = re.compile("^\.{1,2}$")
try:
files = conn.listPath(sharename, path)
except NotReadyError:
accessdenied = mt.addEntity("msploitego.AccessDenied",sharename)
accessdenied.setValue(sharename)
else:
for file in files:
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
else:
entityname = "msploitego.SambaFile"
newpath = "{}/{}".format(path, filename)
sambaentity = mt.addEntity(entityname,"{}/{}{}".format(ip,sharename,newpath))
sambaentity.setValue("{}/{}{}".format(ip,sharename,newpath))
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)
if domaindns:
sambaentity.addAdditionalFields("domain_dns", "Domain DNS", False, domaindns)
sambaentity.addAdditionalFields("sharename", "Share Name", False, sharename)
conn.close()
mt.returnOutput()
mt.addUIMessage("completed!")
示例10: main
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import listPath [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')
示例11: dotransform
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import listPath [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!")
示例12: run
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import listPath [as 别名]
def run(self):
print "Starting thread for " + self.ip
net = NetBIOS()
net_name = str(net.queryIPForName(self.ip)).strip("['").strip("']")
net.close()
conn = SMBConnection(self.user, self.pwd, 'cobwebs', net_name, domain=self.domain, use_ntlm_v2 = False)
if conn.connect(self.ip, port=139, timeout=10):
print ("Connecting to %s was successful! How about a nice game of spidering %s%s?" % (self.ip, self.share, self.subfolder))
else:
print ("Connection error: %s" % (self.ip))
if self.recursive > 0:
recurse(conn,self.ip,self.share,self.subfolder,self.pattern,int(self.recursive))
else:
filelist = conn.listPath(self.share, self.subfolder)
dir_list(filelist,self.ip,self.subfolder,self.pattern)
conn.close()
print "Exiting thread for " + self.ip
示例13: return_mainlibraries
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import listPath [as 别名]
def return_mainlibraries():
mainLibraryNames = []
query = request.form['query']
try:
conn = SMBConnection(username, password, myRequestIdentifier, serverName, domain=domain, use_ntlm_v2 = True)
conn.connect(host, port)
mainLibraryFolders = conn.listPath(sharedFolder, '/MiSeqOutput')
for f in mainLibraryFolders:
#Ignore .DS_Store
folderName = f.filename
if folderName.startswith("."):
continue
if query.lower() in folderName.lower():
mainLibraryNames.append(idtext(folderName, folderName))
except Exception as ex:
return jsonify(result=str(ex))
return jsonify(result=[e.serialize() for e in mainLibraryNames])
示例14: main
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import listPath [as 别名]
def main():
parser = argparse.ArgumentParser('check_smbproxy')
parser.add_argument('server_ip', metavar='server-ip')
parser.add_argument('server_port', metavar='server-port', type=int)
parser.add_argument('server_name', metavar='server-name')
parser.add_argument('share_name', metavar='share-name')
parser.add_argument('--path', default='/')
parser.add_argument('--user', default='cluster_user')
parser.add_argument('--password', default='cluster_user_password')
parsed_args = parser.parse_args()
userID = parsed_args.user
password = parsed_args.password
client_machine_name = 'test_client'
server_ip = parsed_args.server_ip
server_port = parsed_args.server_port
server_name = parsed_args.server_name
share_name = parsed_args.share_name
path = parsed_args.path
try:
start_time = datetime.datetime.utcnow()
conn = SMBConnection(userID, password, client_machine_name, server_name, use_ntlm_v2=False, is_direct_tcp=True)
assert conn.connect(server_ip, server_port)
ls = conn.listPath(share_name, path)
num_files = len(ls)
# for f in ls:
# print f.filename
conn.close()
end_time = datetime.datetime.utcnow()
time_spent = (end_time-start_time).total_seconds()*1000
print "OK: %d files found in %s | connection_time=%dms" % (num_files, path, time_spent)
except Exception:
print "CRITICAL: Exception while trying to connect:"
print traceback.print_exc()
sys.exit(2)
sys.exit(0)
示例15: searchTarget
# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import listPath [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