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
class smb_connector:
	def __init__(self, ip, shared_directory, username, password):
		self.connection = SMBConnection(username, password, "this_machine", "remote_machine", use_ntlm_v2=True, is_direct_tcp=True)
		self.connection.connect(ip, 445)
		self.shared_directory = shared_directory

	def __enter__(self):
		return self

	def __exit__(self, type, value, traceback):
		self.close()

	def close(self):
		self.connection.close()

	def file_contents(self, path):
		with tempfile.NamedTemporaryFile() as file_obj:
			self.connection.retrieveFile(self.shared_directory, path, file_obj)
			file_obj.seek(0)
			content = file_obj.read().decode('utf-8', 'ignore').translate({ord('\u0000'): None})
		return content

	def all_files_recursively(self, full_path, file_filter, directory_filter, relative_path=''):
		whats_here = self.connection.listPath(self.shared_directory, full_path)
		for file in whats_here:
			file_path = os.path.join(full_path, file.filename)
			file_relative_path = os.path.join(relative_path, file.filename)
			if file.isDirectory:
				if directory_filter(file.filename) and '.' not in file.filename:
					yield from self.all_files_recursively(file_path, file_filter, directory_filter, file_relative_path)
			elif file_filter(file.filename):
				yield os.path.normpath(file_relative_path)

	def write_file(self, path, contents):
		with tempfile.NamedTemporaryFile() as file_obj:
			bytes = file_obj.write(contents.encode('utf-8'))
			file_obj.seek(0)
			bytes = self.connection.storeFile(self.shared_directory, path, file_obj)
Beispiel #3
0
    def download_file_by_smb(self, host, host_name, username, password, domain,
                             shared_folder_name, remote_file_path,
                             local_file_path):
        """
        download file by SMB
        :param host: IP
        :param host_name: 域名
        :param username: 用户名
        :param password: 密码
        :param domain: 域名
        :param shared_folder_name: 共享文件夹名称
        :param remote_file_path: 存放路径是相对共享文件夹的路径
        :param local_file_path: 本地文件路径
        :return:
        """
        try:
            remote_name = host_name or self.get_BIOSName(host)
            domain = domain or ''
            conn = SMBConnection(username,
                                 password,
                                 '',
                                 remote_name,
                                 domain,
                                 use_ntlm_v2=True)
            assert conn.connect(host)

            with open(local_file_path, 'wb') as f:
                conn.retrieveFile(shared_folder_name, remote_file_path, f)

        except Exception as e:
            raise SMBConnectionError(data=str(e))

        finally:
            conn.close()
Beispiel #4
0
    def poll(self, poll_input):
        socket.setdefaulttimeout(poll_input.timeout)

        username = poll_input.credentials.username
        password = poll_input.credentials.password
        domain = poll_input.credentials.domain

        try:
            #            n = NetBIOS()
            #            hostname = n.queryIPForName(poll_input.server,timeout=10)[0]
            #            n.close()
            if domain is None:
                conn = SMBConnection(username, password, '',
                                     poll_input.hostname)
            else:
                conn = SMBConnection(username, password, '',
                                     poll_input.hostname, domain.domain)

            conn.connect(poll_input.server,
                         poll_input.port,
                         timeout=poll_input.timeout)
            t = tempfile.TemporaryFile()
            conn.retrieveFile(poll_input.sharename, poll_input.path, t)
            conn.close()

            t.seek(0)
            result = SmbPollResult(t.read())
            return result
        except Exception as e:
            result = SmbPollResult(None, e)
            return result
Beispiel #5
0
    def download_samba_file(self, sambafilepath, localfilepath, filename):
        try:
            time_start = time.time()

            conn = SMBConnection(self.user_name, self.password, self.my_name, self.domain_name, use_ntlm_v2=True)
            print_string = 'samba connection %s' % conn
            print_info.print_info(print_info.PRINT_DEBUG, print_string)
            assert conn.connect(self.remote_smb_ip, self.port)

            print_string = "local file path : %s" % (localfilepath + "/" + filename)
            print_info.print_info(print_info.PRINT_DEBUG, print_string)
            file_fd = open(localfilepath + "/" + filename, 'wb')
            sambafilepath = sambafilepath + "/" + filename
            print_string = "samba file path : %s" % sambafilepath
            print_info.print_info(print_info.PRINT_DEBUG, print_string)
            conn.retrieveFile(self.dir, sambafilepath, file_fd)

            time_use = time.time() - time_start
            file_size = os.path.getsize(localfilepath + r'/' + filename)
            samba_download_speed = (int)(file_size / time_use)

            file_fd.close()
            print_string = 'samba download file %s ok .\ndownload size %d use time is %0.2f s; speed is %d bit/s' % \
                           (filename, file_size, time_use, samba_download_speed)
            print_info.print_info(print_info.PRINT_INFO, print_string)
            return 1
            return 1
        except Exception, e :
            print_string = "samba download file error %s" % e
            print_info.print_info(print_info.PRINT_ERROR, print_string)
            return 0
Beispiel #6
0
    def samba_get(self, service_name, remotefile, localfile):
        samba = SMBConnection(self.username, self.password, '', '')
        samba.connect(self.ip, self.port)

        def list_get(share_name, remotestuff, localstuff):
            if os.path.isdir(localstuff) is False:
                os.mkdir(localstuff)
            for files in samba.listPath(share_name, remotestuff)[2:]:
                localpath = localstuff + os.sep + files.filename
                remotepath = remotestuff + '/' + files.filename
                if not samba.getAttributes(share_name, remotepath).isDirectory:
                    handler = open(localpath, 'wb')
                    samba.retrieveFile(share_name, remotepath, handler)
                    handler.close()
                else:
                    list_get(share_name, remotepath, localpath)
        try:
            if not samba.getAttributes(service_name, remotefile).isDirectory:
                handle = open(localfile, 'wb')
                samba.retrieveFile(service_name, remotefile, handle)
                handle.close()
            else:
                list_get(service_name, remotefile, localfile)
        except Exception:
            print('download file failure! ')
        finally:
            samba.close()
Beispiel #7
0
def get_thread(args, work, host):
    logger.debug('Connecting to {} as {}\\{}'.format(host, args.domain or '',
                                                     args.username))
    conn = SMBConnection(args.username,
                         args.password,
                         'adenum',
                         host,
                         use_ntlm_v2=True,
                         domain=args.domain,
                         is_direct_tcp=(args.smb_port != 139))
    conn.connect(host, port=args.smb_port)
    shares = [
        s.name.lower() for s in conn.listShares()
        if s.type == smb.base.SharedDevice.DISK_TREE
    ]
    for s in work[host]:
        if s.lower() in shares:
            for f in work[host][s]:
                local_path = (host + '\\' + f).replace('\\', '/')
                os.makedirs(os.path.dirname(local_path),
                            mode=0o770,
                            exist_ok=True)
                logger.info('Getting ' + host + '\\' + f)
                with open(local_path, 'wb') as fp:
                    conn.retrieveFile(s, f, fp)
    conn.close()
    def downloadFile(self, filename, download_filepath):
        '''
        下载文件
        :param filename: 保存到本地的文件名
        :param download_filepath: 保存到本地文件的路径
        :return:c
        '''

        print('downloadFile file_name is ' + filename)

        conn = SMBConnection(self.user_name,
                             self.pass_word,
                             self.my_name,
                             self.domain_name,
                             use_ntlm_v2=True)

        conn.connect(self.remote_smb_IP, self.port)
        file_obj = open(download_filepath + filename, 'wb')
        conn.retrieveFile(self.dir, filename, file_obj)

        print(type(file_obj))

        print(type(file_obj))

        file_obj.close()
        return True
Beispiel #9
0
def smb_conn_sync():
    share_folder = 'myshare'
    user_name = 'mytest'
    pwd = 'mytest'
    server_name = 'Legion'
    server_ip = '192.168.0.10'

    local_dir = '/home/jetson/xavier_page/target_folder/'

    #SMBConnection parameters: <username, pwd, client_name, server_name, use_ntlm_v2 = True>
    conn = SMBConnection(user_name,
                         pwd,
                         'jetson-desktop',
                         server_name,
                         use_ntlm_v2=True)
    assert conn.connect(
        server_ip, 139)  # sharing server ip address, port 45 over http/ftp

    filelist = conn.listPath(share_folder, '/')

    f_names = []
    index = 1
    for i in range(len(filelist)):
        if filelist[i].filename.endswith('.jpg'):
            filename = filelist[i].filename
            f_names.append(filename)
            with open(local_dir + filename, 'wb') as fp:
                #print(index, '.....copy:', filename)
                index += 1
                conn.retrieveFile(share_folder, '/' + filename, fp)
    print('Files copied from share to /home/jetson/xavier_page/target_folder')
Beispiel #10
0
def GetFile(host, usr, pwd, smbdir, srcf, dstf):
    from smb.SMBConnection import SMBConnection
    conn = SMBConnection(usr, pwd, "", "", use_ntlm_v2=True)
    conn.connect(host, 445)
    #shareslist = conn.listShares()
    with open(dstf, 'wb') as fobj:
        print 'get file %s%s to %s' % (smbdir, srcf, dstf)
        conn.retrieveFile(smbdir, srcf, fobj)
Beispiel #11
0
 def downloadFile(self,download_filename):#下载文件 注:不能下载整个文件夹只可以下载文件   download_filename:需要下载文件
     try:
         conn = SMBConnection(self.username, self.password, self.my_name, self.remote_smb_IP, self.domain_name, use_ntlm_v2=True,is_direct_tcp = True) 
         conn.connect(self.remote_smb_IP,445)
         file_obj = open(download_filename, 'wb')
         conn.retrieveFile(self.dir, self.display_path + '/' + download_filename, file_obj)
         conn
         file_obj.close()
         return True
     except:
         return False
Beispiel #12
0
def download(request):
    if request.user.is_authenticated:
        user = User.objects.get(username=request.user.username)
        files = user.files.all()

        try:
            selected_file = user.files.filter(name=request.POST['filename'])

        except (KeyError):
            render(request, 'file/home.html', {
                'error_message': "You DID NOT SELECT A FILE",
            })

        else:
            # File object to be selected for downloading purpose
            t = selected_file[0]
            # Finding Appropriate mime type
            typeofmime = str(mimetypes.MimeTypes().guess_type('t.name')[0])

            #####
            # Setting up samba server connection to read file content to be downloaded by user
            global PASSCODE
            client_machine_name = 'megh-os-101317.megh.barc.gov.in'
            server_name = 'megh-os-101317.megh.barc.gov.in'
            userID = request.session['username']
            password = PASSCODE

            conn = SMBConnection(userID,
                                 password,
                                 client_machine_name,
                                 server_name,
                                 use_ntlm_v2=True)
            server_ip = '10.35.28.189'
            assert conn.connect(server_ip, 139)
            # Connection Setup

            # temporary file object in which content would be read
            file_obj = tempfile.NamedTemporaryFile()
            path = '/' + t.name
            conn.retrieveFile('homes', path, file_obj)

            file_obj.seek(0)

            # reading from fileobj to a variable
            p = file_obj.read()
            ######

            # Content to be downloaded with appropriate mime type extension
            response = HttpResponse(p)
            response['Content-Type'] = typeofmime
            response[
                'Content-Disposition'] = 'attachment; filename= "{}"'.format(
                    t.name)
            return response
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
Beispiel #14
0
def check_smb(ip, port, anon, share, checkfile, filehash, domain):
    if not domain:
        domain = ""

    conn = SMBConnection("Guest",
                         "",
                         socket.gethostname(),
                         "none",
                         domain,
                         is_direct_tcp=True)
    try:
        conn.connect(ip, port)
    except Exception as e:
        return 0, "Failed to connect to ip: %s on port %s." % (ip, port)

    try:
        shareList = conn.listShares(timeout=5)
        found = False
        for i in range(len(shareList)):
            if shareList[i].name == share:
                found = True
                break

        if found == False:
            return 0, "Samba share %s not found." % (share)
    except Exception as e:
        return 0, "Failed to retrieve list of shares."

    if checkfile and filehash:
        print("[DEBUG-SMB] Grabbing file for", ip)
        tmpfile = path + "engine/tmpfiles/smb-%s-%s-%s-checkfile" % (share, ip,
                                                                     checkfile)
        try:
            with open(tmpfile, "wb") as fp:
                conn.retrieveFile(share, checkfile, fp)

            with open(tmpfile, "rb") as f:
                content = f.read()
                checkhash = hashlib.sha1(content).hexdigest()
            if checkhash != filehash:
                return (0,
                        "Hash %s does not match %s." % (checkhash, filehash))
            return 1, None
        except Exception as e:
            return 0, "Failed to read share %s." % (share)
    else:
        print("[DEBUG-SMB] Trying anonymous/noauth for", ip)
        try:
            fileList = conn.listPath(share, "/")
            return 1, None
        except Exception as e:
            return 0, "Failed to read share %s." % (share)
Beispiel #15
0
    def fileserver(self):

        log = logger(logger)

        s = "MzRYdjJEKzk="
        latios = str(base64.b64decode(s))
        latios = latios.replace("b'", "")
        latios = latios.replace("'", "")

        # connection open
        conn = SMBConnection('administrator',
                             latios,
                             platform.uname().node,
                             'dwfs04',
                             domain='dad-way.local',
                             use_ntlm_v2=True)

        try:
            conn.connect('192.168.100.8', 139)
        except:
            log.error("ファイルサーバー接続時に例外が発生しました。")
            log.error(sys.exc_info())
            traceback.print_exc()
            sys.exit(False)
        else:
            log.info("ファイルサーバーの接続に成功しました。")

        with open('.\etc\\brand.json', 'wb') as file:
            try:
                conn.retrieveFile(
                    'share',
                    'open\DDIV\OCSD\\ECG\\Online\\80_s5tool\\brand.json', file)
            except:
                log.error("「brand.json」のコピーで例外が発生しました。")
                log.error(sys.exc_info())
                traceback.print_exc()
                sys.exit(False)

        with open('.\etc\\deletecharacter.json', 'wb') as file:
            try:
                conn.retrieveFile(
                    'share',
                    'open\DDIV\OCSD\\ECG\\Online\\80_s5tool\\deletecharacter.json',
                    file)
            except:
                log.error("「deletecharacter.json」のコピーで例外が発生しました。")
                log.error(sys.exc_info())
                traceback.print_exc()
                sys.exit(False)

        conn.close()
Beispiel #16
0
class SMBUtils:
    """
        访问 smb共享的通用功能
    """
    def __init__(self, host, username, password, remote_name, local_name=None):
        local_name = local_name if local_name else ''
        self.conn = SMBConnection(username,
                                  password,
                                  local_name,
                                  remote_name,
                                  is_direct_tcp=True)
        self.conn.connect(host, 445)

    def list_files(self, service_name, share_path, pattern="*"):
        """
            获得共享目录下的文件
        """
        result = []
        filenames = self.conn.listPath(service_name,
                                       share_path,
                                       pattern=pattern)

        for filename in filenames:
            file_name, is_dir = filename.filename, filename.isDirectory
            if not is_dir:
                result.append(file_name)

        return result

    def download_file(self, shared_dir, shared_file_path, local_data_dir,
                      local_file_name):
        """
            下载 windows共享目录 shared_dir下的 shared_file_path 文件到本地 local_data_dir 目录下,
            保存为 local_file_name
        """
        local_file_path = path_join(local_data_dir, local_file_name)

        with open(local_file_path, 'wb') as f:
            self.conn.retrieveFile(shared_dir, shared_file_path, f)

    def delete_files(self, shared_dir, path_file_pattern):
        """
            删除远程数据
        """
        self.conn.deleteFiles(shared_dir, path_file_pattern)

    def __del__(self):
        self.conn.close()
Beispiel #17
0
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])
Beispiel #18
0
def Main():
	cgiEnv = lib_common.CgiEnv()
	# Top directory, not just the share name.
	# smbFile= cgiEnv.GetId("//DUOLNX/IncomingCopied/")
	# xid=smbfile.Id=////londata002/westdev/westdocs/testdata
	smbFile= cgiEnv.GetId()

	nodeSmbShr,smbShr,smbDir = lib_smb.SmbBothUriSplit(smbFile)
	if nodeSmbShr is None:
		lib_common.ErrorMessageHtml("This is not a shared file:"+smbFile)




	# 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
	conn = SMBConnection("xx", "yy", client_machine_name, server_name, use_ntlm_v2 = True)
	assert conn.connect(server_ip, 139)

	file_obj = tempfile.NamedTemporaryFile()
	file_attributes, filesize = conn.retrieveFile('smbtest', '/rfc1001.txt', file_obj)

	# Retrieved file contents are inside file_obj
	# Do what you need with the file_obj and then close it
	# Note that the file obj is positioned at the end-of-file,
	# so you might need to perform a file_obj.seek() if you need
	# to read from the beginning
	file_obj.close()


	for x in z:
		shareNode = lib_common.gUriGen.SmbShareUri( "//" + smbServer + "/" + x )

		grph.add( ( nodeSmbShr, pc.property_smbshare, shareNode ) )
def check_smb(host, share_name, file_name, username, password, hash_to_test):
    try:
        conn = SMBConnection(username,
                             password,
                             'name',
                             'lets_see_if_this_matters',
                             use_ntlm_v2=True,
                             is_direct_tcp=True)
        conn.connect(host, 445)
        shares = conn.listShares()

        for share in shares:
            if share.name.strip() == share_name:
                with tempfile.NamedTemporaryFile() as temp_file:
                    test = conn.retrieveFile(share.name,
                                             '/{}'.format(file_name),
                                             temp_file)
                    data = temp_file.read()
                    with open(temp_file.name, 'r') as read_temp_file:
                        data = read_temp_file.read()
                        hash_obj = hashlib.sha256(data.encode())
                        if hash_obj.hexdigest(
                        ) == 'b73a0892cea768d727f1144c1455a40aa57e9b112145e6a20a56ed1aee607e90':
                            print('SUCCESS')
                            return
    except Exception as e:
        print(str(e))
    print('Failed check')
Beispiel #20
0
    def connect(self, remote_server, path, user="******", password=""):
        conn = SMBConnection(user,
                             password,
                             remote_server,
                             path,
                             use_ntlm_v2=True)

        try:
            # Check of tieout is possible...
            conn.connect(remote_server, 139)
            with open('local_file', 'wb') as fp:
                # conn.retrieveFile('share', '/path/to/remote_file', fp)
                results = conn.listPath('media_source', '/')
                filenames = [(r.filename, r.isDirectory) for r in results]

                for r in results:

                    if r.isDirectory == False:

                        temp_fh = open("wsf.txt", "wb")

                        file_attributes, filesize = conn.retrieveFile('media_source', '/' + r.filename, temp_fh)

                        temp_fh.write()

                        temp_fh.close()

                "Think what to do with . and .."
                for f in filenames:
                    print(f)

                test = ""
                # documents
        except Exception as msg:
            pass
Beispiel #21
0
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)
Beispiel #22
0
class SCP:

    def __init__(self, user, pwd, client, server):
        self.conn = SMBConnection(user, pwd, client, server, use_ntlm_v2=True)
        self.conn.connect(server, 139)

    def get_file(self, share, folder, filename):
        remote_file = os.path.join(folder, filename)
        local_file = open(filename, "wb")
        self.conn.retrieveFile(share, remote_file, local_file)
        print("Retrieved {}".format(remote_file))

    def send_file(self, share, folder, filename):
        local_file = os.path.join(folder, filename)
        remote_file = open(filename, "rb")
        self.conn.storeFile(share, local_file, remote_file)
        print("Uploaded {}".format(local_file))
Beispiel #23
0
def smb_manger():
    try:
        conn = SMBConnection('wuqian',
                             'woshi123',
                             'RITS066100',
                             'RITS066300',
                             use_ntlm_v2=True)
        res = conn.connect('172.25.73.100', 139)

        # with open('F:\\tmp\\0000.txt', 'rb') as f:
        #     conn.storeFile('Users', '\\test1\\hello.txt', f)

        with open('F:\\tmp\\0001.txt', 'wb') as f:
            conn.retrieveFile('Users', '\\test1\\hello.txt', f)

    except Exception as e:
        print('SMB file upload error. %s' % str(e))
Beispiel #24
0
def get(connection: SMBConnection, share_folder: str, file_path: str,
        output_file_path: str):
    logger.info(
        f"Retrieving file \\\\{connection.remote_name}\\{share_folder}{file_path}..."
    )

    with open(output_file_path, "wb") as file:
        try:
            connection.retrieveFile(share_folder, file_path, file)
        except OperationFailure:
            raise Exception(
                f"Unable to retrieve \\\\{connection.remote_name}\\{share_folder}{file_path} file"
            )

    logger.info(
        f"File \\\\{connection.remote_name}\\{share_folder}{file_path} stored within {output_file_path}."
    )
Beispiel #25
0
def lambda_handler(event, context):

    server = os.environ['DCS_SMB_HOST']
    res = dns.resolver.Resolver(configure=False)
    res.nameservers = ['1.1.24.68', '1.1.1.51']
    dns_response = res.query(server, 'a')

    share = "Network"
    port = 445
    domain = 'meteo'
    username = os.environ['DCS_SMB_USER']
    password = os.environ['DCS_SMB_PASS']
    file_name = "DCs.csv"

    s3_client = boto3.client('s3')
    bucket_name = os.environ['PA_EDL_AWS_S3_BUCKET']
    path = 'iprange/'
    out_file = 'meteo-dcs.txt'

    try:
        if dns_response:
            server = dns_response[0].address
        else:
            raise ValueError("Unable to resolve server's DNS record")
        conn = SMBConnection(username,
                             password,
                             'AWS:LAMBDA:PA_EDL',
                             server,
                             domain,
                             is_direct_tcp=True)
        conn.connect(server, 445)
        file_obj = tempfile.NamedTemporaryFile(mode='w+b', delete=False)
        file_attributes, copysize = conn.retrieveFile(share, file_name,
                                                      file_obj)
        file_obj.seek(0)
        data = file_obj.read().decode('utf-8')
        ips = re.findall('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(?:\/\d{1,2})?',
                         data)
        if ips:
            ips = [[text.strip('"') for text in line.split(',')]
                   for line in data.split()[1:]]
            payload = '\n'.join(set(f"{entry[1]} #{entry[0]}"
                                    for entry in ips))
            s3_client.put_object(Bucket=bucket_name,
                                 Key=path + out_file,
                                 Body=payload,
                                 ContentType='text/html')
        else:
            raise ValueError('Unable to extract IP info')
    except Exception as e:
        logger.exception('Error occurred: ' + str(e))
        exit(1)
    finally:
        file_obj.close()
        conn.close()

    logger.info('Successful Invocation')
Beispiel #26
0
    def _connect_repo_file_system(repo, photo_name):
        """
            Get connection for repo
        
        :param repo: PhotoRepository
        :param photo_name: name of photo to search
        :return data_info: Dict 
        """

        data_info = {'path': '', 'url': '', 'type': '', 'success': False}

        conn = SMBConnection(username=repo.user_id.encode('ascii'),
                             password=repo.password.encode('ascii'),
                             my_name=repo.client_machine_name.encode('ascii'),
                             remote_name=repo.server_name.encode('ascii'),
                             domain=repo.domain.encode('ascii'),
                             use_ntlm_v2=True)

        try:
            if conn.connect(ip=repo.server_ip, port=139):
                try:
                    file_obj = tempfile.NamedTemporaryFile()
                    file_attributes, file_size = conn.retrieveFile(
                        repo.service_name,
                        '{0}{1}'.format(repo.path, photo_name), file_obj)

                    if file_attributes:

                        path = '{0}{1}{2}'.format(settings.MEDIA_ROOT,
                                                  '/photographs/', photo_name)

                        shutil.copy(file_obj.name, path)
                        '''
                            set permissions
                        '''
                        os.chmod(path, 0660)

                        data_info['path'] = path
                        data_info['url'] = '{0}{1}{2}{3}'.format(
                            settings.VALID_HOST, settings.MEDIA_URL,
                            'photographs/', photo_name)
                        data_info['type'] = path.split('.')[-1]
                        data_info['success'] = True

                        return data_info

                    file_obj.close()
                    conn.close()
                except Exception as e:
                    print e
                    print "Operacion fallida"
                    conn.close()
        except Exception as e:
            print e
            conn.close()

        return data_info
Beispiel #27
0
 def downloadFile(self):
     try:
         conn = SMBConnection(self.username.get(),
                              self.password.get(),
                              self.my_name,
                              self.domain_name,
                              use_ntlm_v2=True,
                              is_direct_tcp=True)
         conn.connect(self.remote_smb_IP.get(), int(self.port.get()))
         file_obj = open(ml.get(ml.curselection()), 'wb')
         conn.retrieveFile(
             self.dir, self.display_path + '/' + ml.get(ml.curselection()),
             file_obj)
         conn
         file_obj.close()
         return True
     except:
         return False
def smb_conn_sync():
    '''
    smb connection: copy files from server to local
    To adapt:  share_folder, user_name, pwd, server_name, server_ip
    '''
    share_folder = 'myshare'  # 'SAPtransfer'
    user_name = 'mytest'  # 'thermoanlage'
    pwd = 'mytest'  # 'thermo2010$'
    server_name = 'xp_server'  # 'SIMATIC'
    server_ip = '192.168.0.10'  # '192.168.5.2'

    global server_folder_list
    global source_folder_list
    local_dir = source_folder_path

    smb_conn = SMBConnection(user_name,
                             pwd,
                             'jetson-desktop',
                             server_name,
                             use_ntlm_v2=False)
    assert smb_conn.connect(server_ip, 139)
    # print(datetime.now(), 'SMB connection established....')

    filelist = smb_conn.listPath(share_folder, '/')

    f_names = []
    for i in range(len(filelist)):  # get file name list from file path list
        if filelist[i].filename.endswith(
                '.jpg'):  # if 'TM' in filelist[i].filename:
            filename = filelist[i].filename
            f_names.append(filename)

    if server_folder_list == [0]:  # server list is NOT iniatialized yet
        server_folder_list = f_names
        return
    for file in f_names:  # copy new added files to local source
        if file not in server_folder_list:
            with open(local_dir + '/' + file, 'wb') as fp:
                print('smb.....copy:', file)
                smb_conn.retrieveFile(share_folder, '/' + file, fp)
                source_folder_list.append(file)

    server_folder_list = f_names  # update server_folder_list
    smb_conn.close()  # relase resources from local and server
Beispiel #29
0
def usbfirstconnectremote(usbserial, remotecompname, remoteuser,
                          remotepassword):
    array_dates = []
    array_time = []
    a = 0
    data_folder = "C$"
    conn = SMBConnection(remoteuser,
                         remotepassword,
                         "hn",
                         remotecompname,
                         use_ntlm_v2=True,
                         domain='testdomain')
    conn.connect(remotecompname, 139)

    with open('tempohn.tmp', 'wb') as devlogfile:
        conn.retrieveFile(data_folder, '\Windows\inf\setupapi.dev.log',
                          devlogfile)

        print("CONECTADO")
    print("USBSERIAL:", usbserial)

    devlogfile = open("tempohn.tmp", 'r')

    for line in devlogfile:
        if re.search(usbserial, line):
            line = next(devlogfile)
            # Split text strings to retrive date and time
            for word in line.split():
                if word.find(':') != -1:  # time
                    array_time.append(word)
                    #print(array_time)
                else:
                    array_dates.append(word)

            array_dates.remove('>>>')
            array_dates.remove('Section')
            array_dates.remove('start')

    mindate = min(array_dates)
    mintime = min(array_time)

    devlogfile.close()
    return (mindate, mintime)
Beispiel #30
0
def run(options):
    ip = options['ip']
    port = options['port']
    username = options['username']
    password = options['password']

    test = random.choice(config.SMB_FILES)
    expected = test['checksum']

    try:
        n = NetBIOS()
        hostname = n.queryIPForName(ip)[0]
        n.close()

        conn = SMBConnection(username, password, '', hostname, config.DOMAIN)
        conn.connect(ip, port)
        t = tempfile.TemporaryFile()
        conn.retrieveFile(test['sharename'], test['path'], t)
    except (SMBTimeout, socket.timeout):
        logger.debug('Timeout')
        return False
    except NotReadyError:
        logger.debug(ERROR_STRINGS['NotReadyError'] % (username, password))
        return False
    except (NotConnectedError, UnsupportedFeature, ProtocolError, OperationFailure) as e:
        name = e.__class__.__name__
        if name in ERROR_STRINGS:
            logger.debug(ERROR_STRINGS[name] % e)
        else:
            logger.debug('%s: %s' % (name, e))
        return False

    sha1 = hashlib.sha1()
    t.seek(0)
    sha1.update(t.read())
    t.close()
    checksum = sha1.hexdigest()

    if checksum == expected:
        return True
    else:
        logger.debug('Check failed: output: %s | expected: %s' % (checksum, expected))
        return False
Beispiel #31
0
class Nas:
	def __init__(self, config, connection):
		conf = config[connection]
		self.ip = conf['ip']
		self.connection = SMBConnection(conf['user'], conf['password'], conf['local_name'], conf['nas_name'])
		self.connection.connect(self.ip)

	def set_root_directory(self, root):
 		self.root = root

	def list_directory(self, path):
		return self.connection.listPath(self.root, path)

	def list_directory_names(self, path):
		dir_raw = self.list_directory(path)
		return [x.filename for x in dir_raw]

	def create_dir(self, path):
		self.connection.createDirectory(self.root, path)
	
	def download_file(self, origin, destination):
		with open(destination, 'wb') as download_file:  # downloading file
			self.connection.retrieveFile(self.root, origin, download_file)

	def download_remote(self, path):
		filename = os.path.basename(path)
		file_obj = BytesIO()
		self.connection.retrieveFile(self.root, path, file_obj)
		return file_obj
 		
	def upload_remote(self, path, file_obj):
		self.connection.storeFile(self.root, path, file_obj)

	def delete_file(self, path):
		self.connection.deleteFiles(self.root, path)
	
	def rename_path(self, origin, destination):
		self.connection.rename(origin, destination)

	def close(self):
 		self.connection.close()
Beispiel #32
0
def retrieve_file_fromsmb(service_name, path):
    user_name = SMB_USER
    password = SMB_PASSWORD
    local_machine_name = "laptop"
    server_machine_name = SMB_SERVER_NAME
    server_ip = SMB_SERVER_IP
    path = path.replace('\\', '/')

    print("\nFile retrieval process was requested for file -> " + path)
    try:
        conn = SMBConnection(user_name,
                             password,
                             local_machine_name,
                             server_machine_name,
                             use_ntlm_v2=True,
                             is_direct_tcp=True)
        assert conn.connect(server_ip, 445)
        tmp = tempfile.NamedTemporaryFile(delete=True)
        conn.retrieveFile(service_name, path, tmp)
        chunksize = 100000
        try:
            tfr = pd.read_csv(tmp.name,
                              chunksize=chunksize,
                              iterator=True,
                              dtype=str,
                              error_bad_lines=False)
        except:
            tfr = pd.read_csv(tmp.name,
                              chunksize=chunksize,
                              quoting=csv.QUOTE_NONE,
                              iterator=True,
                              dtype=str,
                              error_bad_lines=False)

        df = pd.concat(tfr, ignore_index=True)

        return df, path

    except Exception as e:
        print("\t---> File retrieval process was FAILED for file -> " + path)
        print("Error: {}".format(e))
Beispiel #33
0
    def getFiles(self):
        self.user = ''
        self.password = ''
        self.client_machine_name = 'raspScanner'

        try:
            self.getServerIP()
            files = ['BARCODES.dbf', 'LIQCODE.DBF', 'LIQCODE.DBT']
            conn = SMBConnection(self.user, self.password,
                                 self.client_machine_name, self.server_name,
                                 self.server_ip)
            with dbfLock:
                conn.connect(self.server_ip)
                for file in files:
                    f = open(file, 'w')
                    conn.retrieveFile("LPOSDATA", "/" + file, f)
                    f.close()
                conn.close()
            return (True)
        except:
            return (False)
Beispiel #34
0
    def getFile(self):
        try:
            user = ''
            password = ''
            client_machine_name = 'raspScanner'
            self.getServerIP()
            files = ['BARCODES.dbf', 'LIQCODE.dbf', 'LIQCODE.dbt']

            conn = SMBConnection(user, password, client_machine_name,
                                 self.server_name, self.server_ip)
            conn.connect(self.server_ip)
            print('connected')
            for file in files:
                f = open(file, 'w')
                conn.retrieveFile("LPOSDATA", "/" + file, f)
                f.close()
            print('files retrieved')
            conn.close()
            return (True)
        except:
            return (False)
Beispiel #35
0
def show_file(filename):
    conn = SMBConnection(USERNAME, PASSWORD, MY_NAME, REMOTE_NAME, use_ntlm_v2=False)
    conn.connect(SERVER_IP, PORT)
    #This module implements a file-like class, StringIO, that reads and writes a string buffer (also known as memory files). See the description of file objects for operations (section File Objects). (For standard strings, see str and unicode.)
    temp_fh = StringIO()
#file_obj  A file-like object that has a write method. Data will be written continuously to file_obj until EOF is received from the remote service. In Python3, this file-like object must have a write method which accepts a bytes parameter.
    file_attributes, filesize = conn.retrieveFile('Share', '/ESAP/Hand-Out/' + filename, temp_fh)
    conn.close()
    #读取文件名字
    localfile = filename.split('/')[-1]
#存到服务器
    f = open(os.path.join(os.getcwd() + '/static/', localfile), 'w')
    f.write(temp_fh.getvalue())
#读取服务器的文件
    return redirect(url_for('static', filename=localfile), code=301)
Beispiel #36
0
def copy_file_from(server_name, file_path):
	# set connection with smb server
	conn = SMBConnection(ConfigHost.USERNAME, ConfigHost.PASSWORD, ConfigHost.CLIENT_NAME, server_name)
	conn.connect(getBIOSIp(server_name)[0])

	#with mounted(remote_dir, local_dir):
	#	shutil.copy(file_to_be_copied, local_dir)

	try:
		filename = path_leaf(file_path)
		print filename
		#data_file = open(filename, 'w')
		data_file = tempfile.NamedTemporaryFile()

		attr, size = conn.retrieveFile(ConfigHost.SHARE_DIR, file_path, data_file)
		print size
		data_file.close()
	except Exception as e:
		print e.message
Beispiel #37
0
    def smb_open(self, req):
        global USE_NTLM, MACHINE_NAME

        host = req.get_host()
        if not host:
            raise urllib.error.URLError('SMB error: no host given')
        host, port = splitport(host)
        if port is None:
            port = 139
        else:
            port = int(port)

        # username/password handling
        user, host = splituser(host)
        if user:
            user, passwd = splitpasswd(user)
        else:
            passwd = None
        host = unquote(host)
        user = user or ''
        passwd = passwd or ''
        myname = MACHINE_NAME or self.generateClientMachineName()

        n = NetBIOS()
        names = n.queryIPForName(host)
        if names:
            server_name = names[0]
        else:
            raise urllib.error.URLError('SMB error: Hostname does not reply back with its machine name')

        path, attrs = splitattr(req.get_selector())
        if path.startswith('/'):
            path = path[1:]
        dirs = path.split('/')
        dirs = list(map(unquote, dirs))
        service, path = dirs[0], '/'.join(dirs[1:])

        try:
            conn = SMBConnection(user, passwd, myname, server_name, use_ntlm_v2 = USE_NTLM)
            conn.connect(host, port)

            headers = email.message.Message()
            if req.has_data():
                data_fp = req.get_data()
                filelen = conn.storeFile(service, path, data_fp)

                headers.add_header('Content-length', '0')
                fp = BytesIO(b"")
            else:
                fp = self.createTempFile()
                file_attrs, retrlen = conn.retrieveFile(service, path, fp)
                fp.seek(0)

                mtype = mimetypes.guess_type(req.get_full_url())[0]
                if mtype:
                    headers.add_header('Content-type', mtype)
                if retrlen is not None and retrlen >= 0:
                    headers.add_header('Content-length', '%d' % retrlen)

            return addinfourl(fp, headers, req.get_full_url())
        except Exception as ex:
            raise urllib.error.URLError('smb error: %s' % ex).with_traceback(sys.exc_info()[2])
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
Beispiel #39
0
class ProtocolSMB(ILocation):
	
	"""
	Doku: http://packages.python.org/pysmb/api/smb_SMBConnection.html?highlight=listpath#smb.SMBConnection.SMBConnection.listPath
	"""
	
	_conn = None
	
	def __del__(self):
		self._conn.close()
		
	
	def connect(self, username, password, ip):
		""" remote connect smb """
		from smb.SMBConnection import SMBConnection
		
		self._conn = SMBConnection(username, password, my_name = "", remote_name = "", domain='', use_ntlm_v2=True)
		return self._conn.connect(ip = ip, timeout = 5)
		

	def listDir(self, path):
		m = re.match('/.+?/(.+?)/(.+)', path)
		share = m.group(1)
		folder = m.group(2)
		
		list = []
		for item in self._conn.listPath(share, folder):
			if item.isDirectory and item.filename[0] != '.':
				list.append( item.filename )

		return list
	
	def listFile(self, path):
		m = re.match('/.+?/(.+?)/(.+)', path)
		share = m.group(1)
		folder = m.group(2)
		#filter = m.group(3)
		
		list = []
		for item in self._conn.listPath(share, folder):
			if item.isDirectory == False:
				list.append( item.filename )

		return list
		
	
	def readFile(self, filename):
		m = re.match('/.+?/(.*?)/(.*)', filename)
		share = m.group(1)
		folder = m.group(2)
		
		import tempfile
		
		tmpfile = tempfile.TemporaryFile()
		self._conn.retrieveFile(share, folder, tmpfile)
		
		tmpfile.seek(0)
		buffer = ""
		try:
			for line in tmpfile:
				buffer +=line
		finally:
			tmpfile.close()

		return buffer

	def generate_path(self, a, *p):
		chdir = a
		for path in p:
			chdir = chdir + '/' + path
			
		return chdir
Beispiel #40
0
class FetchFile(FetchDataBase):
	_localFolder = ''
	_serverName = ''
	_rootNode = ''
	_subPath = ''
	_conn = None
	_filename = ''
	#_folderList = []
	#_fileList = []
	def __init__(self, addr, uid, upwd):
		#super(FetchFile, self).__init__(addr, uid, upwd)
		# print 'addr:', addr
		try:
			# FetchDataBase.__init__(self, r'//CNST50066074/Root/Business_One/Projects/Dev/SDK/KnowledgeWarehouse/_Ebook/java/m2ebook-pdf.pdf', uid.lower(), upwd)
			FetchDataBase.__init__(self, str(addr), uid.lower(), upwd)
			self._genPath()
		except Exception as e:
			self._responseCode = 430
			print 'init error....'
			raise e

	def _genPath(self):
		rootPath = self._addr
		self._localFolder = self._addr
		#skip first domain path, ie "\\servername\path\
		# print 'self._addr:', self._addr
		if self._addr.startswith(PLACEHOLDER_START):
			if len(self._addr) <= 2:
				raise Exception('not support"', self._addr, '"root path')
			else:
				rootPath = self._addr[2:]

			#get servername
			index = rootPath.find(PLACEHOLDER)
			if index > 0:
				self._serverName = rootPath[0:index]
				rootPath = rootPath[index+1:]
			else:
				#ie \\servername\
				self._serverName = rootPath
				rootPath = ''
		else:
			raise Exception('invalid net work path')

		#local temp path
		self._localFolder = base64.b64encode(self._addr)

		#find root path, ie path\
		index = rootPath.find(PLACEHOLDER)
		if index > 0:
			self._rootNode = rootPath[0:index]
			self._subPath = rootPath[index:]
		else:
			self._rootNode = rootPath
			self._subPath = ''
			#raise Exception('invalid path ')
		#print 'rootNode', self._rootNode
		#print 'subpath', self._subPath

	def _connToServer(self):
		try:
			#print 'id:', self._uid
			# print 'servername', self._serverName
			self._conn = SMBConnection(self._uid, self._upwd, '', self._serverName) #use_ntlm_v2 = True
			if not self._conn.connect(self._serverName): #port = 139
				raise Exception('connect failure:', self._serverName)
		except Exception as e:
			print str(e)

	def _connClose(self):
		self._conn.close()

	FOLDERLIST = 'folderlist'
	FILELIST = 'filelist'
	def _getFileList(self, subFolder = ''):
		if subFolder == '':
			subFolder = self._subPath
		print 'rootnode:', self._rootNode
		print 'subFolder:', subFolder
		list = self._conn.listPath(self._rootNode, subFolder)
		folderList = []
		fileList = []
		for f in list:
			if f.filename in ['.','..','Thumbs.db']:
				continue
			if f.isDirectory:
				folderList.append(f.filename)
			else:
				fileList.append(f.filename)
		folderList.append('')
		#print folderList, fileList
		return {self.FOLDERLIST:folderList, self.FILELIST:fileList}

	def _getLastFilePath(self, path):
		index = path.rfind(PLACEHOLDER)
		#print 'getlastfilepath index:', index
		if index < 0:
			return {'path':'', 'file':path}
			#raise Exception('not found last path')
		if index + 1 == len(path):
			#print 'index', index
			#print 'len(path):', len(path), path
			path = path[0:index]
			return self._getLastFilePath(path)
		else:
			return {'path':path[0:index+1], 'file':path[index+1:]}


	#TYPE_FOLDER = 'folder'
	#TYPE_FILE = 'file'
	# folder or file
	def _getFileType(self):
		#get path
		dpath = self._getLastFilePath(self._subPath)
		path = dpath['path']
		file = dpath['file']
		#print 'path', path
		#print 'file', file
		self._filename = file
		#
		dlist = self._getFileList(path)
		folderList = dlist[self.FOLDERLIST]
		fileList = dlist[self.FILELIST]

		if file.decode('utf-8') in folderList:
			self._resourceType = TYPE_FOLDER
			return TYPE_FOLDER
		if file.decode('utf-8') in fileList:
			self._resourceType = TYPE_FILE
			return TYPE_FILE
		return None

	#if folder return filelist, if file return filepath.
	def _getContent(self):
		type = self._getFileType()
		#print 'content type', type
		if type == TYPE_FOLDER:
			dfiles = self._getFileList()
			#print 'dfiles', dfiles
			#dfiles['type'] = TYPE_FOLDER
			files = []
			files.extend(dfiles[self.FOLDERLIST])
			files.extend(dfiles[self.FILELIST])
			return TYPE_FOLDER, str(files)
		elif type == TYPE_FILE:
			# return {'filepath':self._retrieveFile()}
			tempResult = self._retrieveFile()
			# return TYPE_FILE, self._retrieveFile()
			return TYPE_FILE, tempResult
		else:
			return None, None

	def _retrieveFile(self):
		tempPath = SF_TEMPPATH
		self.mkdir(tempPath)
		import os
		filename =  self._addr.replace('/', '_')
		tempPath = os.path.realpath(tempPath + filename)
		import tempfile
		with open(tempPath, 'wb+') as fo:
			#fp = tempfile.NamedTemporaryFile()
			fa, filesize = self._conn.retrieveFile(self._rootNode, self._subPath, fo)
			#print 'filesize', filesize
			#for line in fp:
			#	fo.write(line)
			#fp.close()
			fo.close()
		return tempPath

	def _detectFileType(self, fileType):
		from const_file_type import GLOBAL_FILE_TYPE
		if fileType == TYPE_FOLDER:
			return GLOBAL_FILE_TYPE.SF
		elif fileType == TYPE_FILE:
			if self._addr.lower().endswith('.pdf'):
				return GLOBAL_FILE_TYPE.PDF
			elif self._addr.lower().endswith('.doc'):
				return  GLOBAL_FILE_TYPE.DOC
			elif self._addr.lower().endswith('.docx'):
				return GLOBAL_FILE_TYPE.DOCX
			elif self._addr.lower().endswith('.ppt'):
				return GLOBAL_FILE_TYPE.PPT
		return GLOBAL_FILE_TYPE.OTHERS

	def fetchData(self):
		try:
			self._connToServer()
			fileType, content = self._getContent()
			#print 'content', content
			self._connClose()
			if content == None:
				self._responseCode = 430
				e = Exception()
				e.code = 430
				e.message = "Wrong url, can not fetch url"
				raise e
			self._responseCode = 200
			return content, self._addr, self._detectFileType(fileType)
		except Exception as e:
			self._responseCode = 430
			e.code = 430
			raise e


	#using mount to open share folder, not working at now.
	def _openShareFolder(self):
		#//10.58.0.100/Root/Business_One/Projects/Dev/SDK/KnowledgeWarehouse/_Ebook/Effective STL.pdf
		tempPath = "../temp/"
		tempPath += self._localFolder
		self.mkdir(tempPath)

		#print 'absolute path'
		tempPath = os.path.realpath(tempPath)
		print tempPath

		command = r"sudo mount.cifs " + self._addr + " " + tempPath + "/ -o user="******",password="
		print command
		try:
			os.system(command + self._upwd)
		except Exception, e:
			print e
			raise e
Beispiel #41
0
    def smb_open(self, req):
        global USE_NTLM, MACHINE_NAME

        host = req.get_host()
        if not host:
            raise urllib2.URLError('SMB error: no host given')
        host, port = splitport(host)
        if port is None:
            port = 139
        else:
            port = int(port)

        # username/password handling
        user, host = splituser(host)
        if user:
            user, passwd = splitpasswd(user)
        else:
            passwd = None
        host = unquote(host)
        user = user or ''

        domain = ''
        if ';' in user:
            domain, user = user.split(';', 1)

        passwd = passwd or ''
        myname = MACHINE_NAME or self.generateClientMachineName()

        n = NetBIOS()
        names = n.queryIPForName(host)
        if names:
            server_name = names[0]
        else:
            raise urllib2.URLError('SMB error: Hostname does not reply back with its machine name')

        path, attrs = splitattr(req.get_selector())
        if path.startswith('/'):
            path = path[1:]
        dirs = path.split('/')
        dirs = map(unquote, dirs)
        service, path = dirs[0], '/'.join(dirs[1:])

        try:
            conn = SMBConnection(user, passwd, myname, server_name, domain=domain, use_ntlm_v2 = USE_NTLM)
            conn.connect(host, port)

            if req.has_data():
                data_fp = req.get_data()
                filelen = conn.storeFile(service, path, data_fp)

                headers = "Content-length: 0\n"
                fp = StringIO("")
            else:
                fp = self.createTempFile()
                file_attrs, retrlen = conn.retrieveFile(service, path, fp)
                fp.seek(0)

                headers = ""
                mtype = mimetypes.guess_type(req.get_full_url())[0]
                if mtype:
                    headers += "Content-type: %s\n" % mtype
                if retrlen is not None and retrlen >= 0:
                    headers += "Content-length: %d\n" % retrlen

            sf = StringIO(headers)
            headers = mimetools.Message(sf)

            return addinfourl(fp, headers, req.get_full_url())
        except Exception, ex:
            raise urllib2.URLError, ('smb error: %s' % ex), sys.exc_info()[2]
Beispiel #42
0
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:
				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 download(self, path, filename,buffersize=None,callback=None, local_path=None):
		try:
			self.error = None
			#print('Download = ' + path + filename)
			attr = self.conn.getAttributes(self.service_name, path+filename)
			#print('Size = %.1f kB' % (attr.file_size / 1024.0))
			#print('start download')
			file_obj = BytesIO()
			if local_path:
				fw = open(local_path+filename, 'wb')
			else:
				fw = open(filename, 'wb')
			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)
Beispiel #43
0
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()