当前位置: 首页>>代码示例>>Python>>正文


Python SMBConnection.connect方法代码示例

本文整理汇总了Python中smb.SMBConnection.SMBConnection.connect方法的典型用法代码示例。如果您正苦于以下问题:Python SMBConnection.connect方法的具体用法?Python SMBConnection.connect怎么用?Python SMBConnection.connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在smb.SMBConnection.SMBConnection的用法示例。


在下文中一共展示了SMBConnection.connect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: SmbClient

# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import connect [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
开发者ID:rahulinux,项目名称:PythonPractice-,代码行数:32,代码来源:samba_client.py

示例2: getShares

# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import connect [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)
开发者ID:jorik041,项目名称:smbDumper,代码行数:30,代码来源:smbDumper.py

示例3: SambaHelper

# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import connect [as 别名]
class SambaHelper():
    def __init__(self, user, password, serverName):
        self.__username = user
        self.__password = password
        self.__connect(serverName)

    def __connect(self, serverName):
        self.conn = SMBConnection(self.__username, self.__password, '','',use_ntlm_v2 = True)
        self.conn.connect(serverName, 139)
        print "Connected."

    def CopyFileToSambaShare(self, fileName, shareName):
        file_obj=file(fileName, 'r')
        print file_obj.name
        self.conn.storeFile(shareName, '/{0}'.format(fileName), file_obj)
    
    def CopyFilesToSambaShare(self, inputDir, shareName):
        files = os.listdir(inputDir)
        for file in files:
            if file.endswith('.jpg'):
                print file
                self.CopyFileTo("{0}/{1}".format(inputDir,file), shareName)

    def CloseConnection():
        self.conn.close()
开发者ID:oaicstef,项目名称:RaspPhotoBooth,代码行数:27,代码来源:connectToSambaShare.py

示例4: connect

# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import connect [as 别名]
def connect(server_name, user, password, domain='', use_ntlm_v2=True):
    logger.info("[lib.samba.py] connect")

    from smb.SMBConnection import SMBConnection
    import socket

    from smb import smb_structs
    smb_structs.SUPPORT_SMB2 = False

    if user == 'quest' or user == 'anonnimo' or user == 'invitado' or user == 'anonimo' or user == '' or user is None:
        user = 'quest'
        password = ''

    logger.info("[lib.samba.py] Averigua IP...")
    server_ip = socket.gethostbyname(server_name)
    logger.info("[lib.samba.py] server_ip=" + server_ip)

    logger.info("[lib.samba.py] Crea smb...")
    try:
        remote = SMBConnection(user, password, domain, server_name, use_ntlm_v2=use_ntlm_v2)
        conn = remote.connect(server_ip, 139)
    except:
        remote = SMBConnection(user, password, domain, server_ip, use_ntlm_v2=use_ntlm_v2)
        conn = remote.connect(server_ip, 139)

    logger.info("[lib.samba.py] Conexión realizada con éxito")

    return remote
开发者ID:jurrKodi,项目名称:pelisalacarta,代码行数:30,代码来源:libsmb.py

示例5: enumerateShareName

# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import connect [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)
开发者ID:jorik041,项目名称:smbDumper,代码行数:33,代码来源:smbDumper.py

示例6: return_sampleIDs

# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import connect [as 别名]
def return_sampleIDs():
	sampleIDs = []
	query = request.form['query']
	mainLibraryFolder = request.form['mainLibraryFolder']
	try:
		conn = SMBConnection(username, password, myRequestIdentifier, serverName, domain=domain, use_ntlm_v2 = True)
		conn.connect(host, port)

		sampleSheetCSV = tempfile.NamedTemporaryFile()
		pathTo = 'MiSeqOutput/'+mainLibraryFolder+'/SampleSheet.csv'
		sampleSheetCSV_attributes, sampleSheetCSV_size = conn.retrieveFile(sharedFolder, pathTo, sampleSheetCSV)

		sampleSheetCSV.seek(0)

		fileContents = sampleSheetCSV.read()
		uniqueLines = fileContents.replace("\r\n", '\n').replace("\r", '\n').split("\n")

		counter = 0
		for line in uniqueLines:
			#sampleIDs.append(idtext(line, line))
			if (line.startswith("[Data]") or counter==1):
				counter+=1
				continue
			#Two lines after [Data] line, first sampleIDs is encountered
			if (counter==2):
				sampleID = line[:line.find(",")]
				if (query.lower() in sampleID.lower()) and not sampleID=="": #Not blank line
					sampleIDs.append(idtext(sampleID, sampleID))
	except Exception as ex:
		exc_type, exc_obj, exc_tb = sys.exc_info()
		fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
		return jsonify(result=(exc_type, fname, exc_tb.tb_lineno))
	return jsonify(result=[e.serialize() for e in sampleIDs])
开发者ID:JBEI,项目名称:MiSeqValPipeline,代码行数:35,代码来源:seqval.py

示例7: show_dir

# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import connect [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)
开发者ID:ceclinux,项目名称:mpidrive,代码行数:10,代码来源:connecto.py

示例8: run

# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import connect [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
开发者ID:Miking98,项目名称:MiSeqValPipeline,代码行数:60,代码来源:MiSeqServerData.py

示例9: connect

# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import connect [as 别名]
def connect(url):
    #logger.info("Url: %s" % url)
    global remote
    server_name, server_ip, share_name, path, user, password, domain = parse_url(url)
    if not remote or not remote.sock or not server_name == remote.remote_name:
      remote = SMBConnection(user, password, domain, server_name)
      remote.connect(server_ip, 139)
  
    return remote, share_name, path
开发者ID:FusionwareIT,项目名称:Repository-FusionBox,代码行数:11,代码来源:libsmb.py

示例10: file_connection

# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import connect [as 别名]
def file_connection():
    IP = sys.argv[1]
    shareName = sys.argv[2]
    inputFile = sys.argv[3]
    port = 139
    conn = SMBConnection("","","","")
    conn.connect(IP,port)
    fileObj = tempfile.NamedTemporaryFile()

    conn.retrieveFile(shareName,inputFile,fileObj)
    return fileObj
开发者ID:dengwc,项目名称:GaoKao-Select_term-system,代码行数:13,代码来源:selectTermSystem.py

示例11: getFileList

# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import connect [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
开发者ID:hsluoyz,项目名称:TeamHelper,代码行数:14,代码来源:samba.py

示例12: test_NTLMv2_auth_SMB2

# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import connect [as 别名]
def test_NTLMv2_auth_SMB2():
    global conn
    smb_structs.SUPPORT_SMB2 = smb_structs.SUPPORT_SMB2x = True
    info = getConnectionInfo()
    conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], domain = info['domain'], use_ntlm_v2 = True)
    assert conn.connect(info['server_ip'], info['server_port'])

    conn2 = SMBConnection(info['user'], 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = True)
    assert not conn2.connect(info['server_ip'], info['server_port'])

    conn3 = SMBConnection('INVALIDUSER', 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = True)
    assert not conn3.connect(info['server_ip'], info['server_port'])
开发者ID:miketeo,项目名称:pysmb,代码行数:14,代码来源:test_auth.py

示例13: dotransform

# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import connect [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!")
开发者ID:mmclaughlin1,项目名称:msploitego,代码行数:55,代码来源:smblsshare.py

示例14: Connect

# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import connect [as 别名]
    def Connect(self):
        client_machine_name = socket.gethostname()
        # watch out:
        # self.computer is unicode (must be converted to str)!
        conn = SMBConnection(self.username, self.password, client_machine_name, str(self.computer))

        computerIp = socket.gethostbyname(self.computer)
        # print computerIp

        conn.connect(computerIp, 139)

        self.conn = conn
开发者ID:undergraver,项目名称:QuickIndexer,代码行数:14,代码来源:smbScan.py

示例15: __connect

# 需要导入模块: from smb.SMBConnection import SMBConnection [as 别名]
# 或者: from smb.SMBConnection.SMBConnection import connect [as 别名]
 def __connect(self):
     conn_cnt = 0
     logger.info("trying to connect smb server on %s:%s" % (self.ip, self.port))
     while conn_cnt < ss.get("reconnect_times", 3):
         try:
             smb_conn = SMBConnection(
                 self.username, self.password, self.client_name, self.server_name, use_ntlm_v2=self.use_ntlm_v2
             )
             smb_conn.connect(self.ip, self.port)
             logger.info("connected to smb server")
             return smb_conn
         except Exception, e:
             conn_cnt += 1
             logger.info("connecting failed, times to reconnect: %d" % conn_cnt)
开发者ID:muma378,项目名称:datatang,代码行数:16,代码来源:smb_proxy.py


注:本文中的smb.SMBConnection.SMBConnection.connect方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。