• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python SMBConnection.SMBConnection类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: SmbClient

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-,代码行数:30,代码来源:samba_client.py


示例2: transfer

    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
开发者ID:rz-comp,项目名称:compassion-switzerland,代码行数:25,代码来源:gp_connector.py


示例3: authenticate

    def authenticate(self):

        from smb.SMBConnection import SMBConnection

        # There will be some mechanism to capture userID, password, client_machine_name, server_name and server_ip
        # client_machine_name can be an arbitary ASCII string
        # server_name should match the remote machine name, or else the connection will be rejected

        #userID = 'xatportantier'
        userID = 'guest'
        #password = 'SecurFMP_23'
        password = ''
        client_machine_name = 'fmp'
        server_ip = '192.1.3.120'
        server_name = 'Server72'
        server_name = ''

        from nmb.NetBIOS import NetBIOS

        nb = NetBIOS(broadcast=True, listen_port=0)
        #print('ip', nb.queryName(server_name, port=445))
        #print('name', nb.queryIPForName(server_ip))


        conn = SMBConnection(userID, password, client_machine_name, server_name, use_ntlm_v2=True, is_direct_tcp=False)
        from pprint import pprint
        for a in [ 'capabilities', 'domain', 'host_type', 'log', 'my_name', 'remote_name', 'security_mode', 'uid', 'username' ]:
            print(a, getattr(conn, a))
        #print('cap', conn.capabilities)
        #print('domain', conn.domain)

        print('auth', conn.connect(server_ip, 139))
开发者ID:portantier,项目名称:habu,代码行数:32,代码来源:auth.py


示例4: enumerateShareName

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,代码行数:31,代码来源:smbDumper.py


示例5: getShares

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,代码行数:28,代码来源:smbDumper.py


示例6: get_connection

def get_connection(location):
    """
    Get a SMB connnection using the location and verify the remote
    location.

    Get the formatted location name, otherwise throw a
    RemoteNameException. Create the SMB connection, otherwise throw a
    SMBConnectionException.
    """
    location_name = smb_share_format.format(location.server_ip,
                                            location.share_name,
                                            location.path)
    netbios = NetBIOS()
    remote_name = netbios.queryIPForName(location.server_ip)
    if not remote_name:
        raise RemoteNameException("Unable to get remote name for {0}!".
                                  format(location.server_ip))
    if not location.username:
        location.username=""
    if not location.password:
        location.password=""
    connection = SMBConnection(location.username, location.password, 'ONYX',
        remote_name[0])
    if not connection.connect(location.server_ip):
        riemann.send({"host": config.HOST,
                      "service": "shareutil.get_connection",
                      "state": "start"})
        raise SMBConnectionException("Unable to connect to {0}".
                                     format(location_name))
    return connection
开发者ID:countrymarmot,项目名称:deca_tech,代码行数:30,代码来源:shareutil.py


示例7: setup_func_SMB2

def setup_func_SMB2():
    global conn
    smb_structs.SUPPORT_SMB2 = True
    smb_structs.SUPPORT_SMB2x = False
    info = getConnectionInfo()
    conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True)
    assert conn.connect(info['server_ip'], info['server_port'])
开发者ID:miketeo,项目名称:pysmb,代码行数:7,代码来源:test_rename.py


示例8: smb_scan

def smb_scan(ip, port, list_shares, timeout, verbose):
	# empty username and password for null session
	username = ""
	password = ""
	client_name = "client"
	server_name = ip
	if port == 445:
		is_direct_tcp = True
	else:
		is_direct_tcp = False
	try:
		# def __init__(self, username, password, my_name, remote_name, domain = '', use_ntlm_v2 = True, sign_options = SIGN_WHEN_REQUIRED, is_direct_tcp = False)
		conn = SMBConnection(username, password, client_name, server_name, use_ntlm_v2 = True, is_direct_tcp = is_direct_tcp)
		smb_authentication_successful = conn.connect(ip, port, timeout = timeout)
		if smb_authentication_successful:
			print "SMB active [null session enabled]: %s:%s" % (ip, port)
			if list_shares:
				list_smb_shares(conn, timeout)
		else:
			# on Windows 7 authentication fails due to disabled null sessions
			print "SMB active [null session disabled]: %s:%s" % (ip, port)
	except:
		if verbose:
			e = sys.exc_info()
			print "%s" % str(e)
	finally:
		if conn:
			conn.close()
开发者ID:0x27,项目名称:tools,代码行数:28,代码来源:smb-discovery.py


示例9: verify_user

    def verify_user(username, password):
        verified_username_and_password = False
        msg_to_web = None 

        conn = None
        
        try:
            if is_username_correct(username):
                conn = SMBConnection(
                    username, password, 'gsmbpasswd-server', SMB_SERVER, use_ntlm_v2 = True)
                verified_username_and_password = conn.connect(SMB_SERVER, 445)
            else:
                verified_username_and_password = False
                log_to_file(u"WARNING: Someone entered a non-existent username: %s" % username)
 
        except:
            # Re-raise the same exception that was thrown and let
            # the calling function handle the exception.
            raise
       
        finally:
            if not conn == None:
                conn.close # Always close the connection

        return verified_username_and_password, msg_to_web
开发者ID:Gsmbpasswd,项目名称:gsmbpasswd,代码行数:25,代码来源:gsmbpasswd-https.py


示例10: return_sampleIDs

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,代码行数:33,代码来源:seqval.py


示例11: setup_func_SMB2

def setup_func_SMB2():
    global conn
    smb_structs.SUPPORT_SMB2 = True

    info = getConnectionInfo()
    conn = SMBConnection(info["user"], info["password"], info["client_name"], info["server_name"], use_ntlm_v2=True)
    assert conn.connect(info["server_ip"], info["server_port"])
开发者ID:devehe,项目名称:pysmb,代码行数:7,代码来源:test_storefile.py


示例12: run_brute_force

def run_brute_force(username, password, args):
	ip = args.ip
	port = args.port
	domain = args.domain
	list_shares = args.list_shares
	timeout = args.timeout
	verbose = args.verbose

	client_name = "client"
	server_name = ip
	if port == 445:
		is_direct_tcp = True
	else:
		is_direct_tcp = False

	try:
		# def __init__(self, username, password, my_name, remote_name, domain = '', use_ntlm_v2 = True, sign_options = SIGN_WHEN_REQUIRED, is_direct_tcp = False)
		conn = SMBConnection(username, password, client_name, server_name, domain = domain, use_ntlm_v2 = True, is_direct_tcp = is_direct_tcp)
		smb_authentication_successful = conn.connect(ip, port, timeout = timeout)
		if smb_authentication_successful:
			print "success: [%s:%s]" % (username, password)
			if list_shares:
				list_smb_shares(conn, timeout)
		else:
			if verbose:
				print "failed: [%s:%s]" % (username, password)
	except:
		if verbose:
			e = sys.exc_info()
			print "%s" % str(e)
	finally:
		if conn:
			conn.close()
开发者ID:0x27,项目名称:tools,代码行数:33,代码来源:smb-brute-force.py


示例13: transfer

    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
开发者ID:MickSandoz,项目名称:compassion-switzerland,代码行数:33,代码来源:gp_connector.py


示例14: _transfer_file_on_nas

    def _transfer_file_on_nas(self, file_name):
        """
        Puts the letter file on the NAS folder for the translation platform.
        :return: None
        """
        self.ensure_one()
        # 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):
            raise Exception('No config SMB in file .conf')

        # Copy file in the imported letter folder
        smb_conn = SMBConnection(smb_user, smb_pass, 'openerp', 'nas')
        if smb_conn.connect(smb_ip, smb_port):
            file_ = BytesIO(base64.b64decode(
                self.letter_image.with_context(
                    bin_size=False).datas))
            nas_share_name = self.env.ref(
                'sbc_translation.nas_share_name').value

            nas_letters_store_path = self.env.ref(
                'sbc_translation.nas_letters_store_path').value + file_name
            smb_conn.storeFile(nas_share_name,
                               nas_letters_store_path, file_)

            logger.info('File {} store on NAS with success'
                        .format(self.letter_image.name))
        else:
            raise Warning(_('Connection to NAS failed'))
开发者ID:MickSandoz,项目名称:compassion-switzerland,代码行数:32,代码来源:correspondence.py


示例15: smb_connect

def smb_connect(args):
	ip = args.ip
	port = args.port
	username = args.username
	password = args.password
	domain = args.domain
	timeout = args.timeout
	verbose = args.verbose

	client_name = "client"
	server_name = ip
	if port == 445:
		is_direct_tcp = True
	else:
		is_direct_tcp = False

	# def __init__(self, username, password, my_name, remote_name, domain = '', use_ntlm_v2 = True, sign_options = SIGN_WHEN_REQUIRED, is_direct_tcp = False)
	conn = SMBConnection(username, password, client_name, server_name, domain = domain, use_ntlm_v2 = True, is_direct_tcp = is_direct_tcp)
	smb_authentication_successful = conn.connect(ip, port, timeout = timeout)
	if smb_authentication_successful:
		print "authentication successful"
		return conn
	else:
		print "authentication failed"
		return None
开发者ID:0x27,项目名称:tools,代码行数:25,代码来源:smb-file-sharing.py


示例16: connect

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,代码行数:28,代码来源:libsmb.py


示例17: run

	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,代码行数:58,代码来源:MiSeqServerData.py


示例18: connect

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,代码行数:9,代码来源:libsmb.py


示例19: notify_smb

def notify_smb(isn, timestamp, msg):
	server_name = ""
	client_machine_name = "Onegin"
	server_ip = "172.18.212.211"
	userID = "szsfis"
	password = "szsfis"
	conn = SMBConnection(userID, password, client_machine_name, server_name, use_ntlm_v2 = True)
	assert conn.connect(server_ip, 139)
	filename = "%s_%s.csv" % (isn, timestamp)
	conn.storeFile("sz_sfis_event_log", filename, StringIO.StringIO(msg))
开发者ID:fragileness,项目名称:importer,代码行数:10,代码来源:mla_processmining_consumer.py


示例20: _get_connection

 def _get_connection(self):
     localname = socket.gethostname()
     remotename = 'agustin'
     conn = SMBConnection(self.username, self.password,
                          localname, remotename)
     self.debug('get connection {}'.format(self.host))
     if conn.connect(self.host):
         return conn
     else:
         print('failed to connect')
开发者ID:NMGRL,项目名称:pychron,代码行数:10,代码来源:smb_storage.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python smbus.SMBus类代码示例发布时间:2022-05-27
下一篇:
Python i18n._LI函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap