def read_alerts():
print('Retrieving info from', URL_MESSAGES, '...')
messages = get_response_json(URL_MESSAGES)
if messages is None:
return None
alerts = []
for message in messages:
messageFits = ((message['version'] == 'all') or (float(message['version']) >= version.version))
messageHigher = ((message['version'] == 'all') or (float(message['version']) > version.version))
categoryCheck = (message['category'] == 'alert') and messageFits
versionCheck = (message['category'] == 'release') and messageHigher
if not categoryCheck and not versionCheck:
continue
alerts.append(message)
print_table(alerts)
return alerts
python类version()的实例源码
def main():
logging.info('pyhttps {}'.format(version))
create_ssl_cert()
atexit.register(exit_handler)
if PY3:
import http.server
import socketserver
import ssl
logging.info('Server running... https://{}:{}'.format(server_host, server_port))
httpd = socketserver.TCPServer((server_host, server_port), http.server.SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket(httpd.socket, certfile=ssl_cert_path, server_side=True)
else:
import BaseHTTPServer
import SimpleHTTPServer
import ssl
logging.info('Server running... https://{}:{}'.format(server_host, server_port))
httpd = BaseHTTPServer.HTTPServer((server_host, server_port), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket(httpd.socket, certfile=ssl_cert_path, server_side=True)
httpd.serve_forever()
def get_release_component():
"""Split the argument passed on the command line into a component name and expected version
"""
global comp_names
if len(sys.argv) < 2:
raise EnvironmentError("Usage: python release.py <component_name>-<version>")
name = 'iotile_cloud_api'
vers = sys.argv[-1]
#Allow versions to be vX.Y.Z
if vers[0] == 'v':
vers = vers[1:]
if name not in comp_names:
raise EnvironmentError("Invalid unknown release component name", name=name, known_names=comp_names.keys())
return name, vers
def main():
if len(sys.argv) < 2:
print("Usage: release.py [--check] <component_name>-<version>")
sys.exit(1)
dry_run = False
if sys.argv[-2] == '--check':
dry_run = True
component, version = get_release_component()
check_version(component, version)
build_component(component)
#release_notes = get_release_notes(component, version)
if dry_run:
print("Check Release\nName: {}\nVersion: {}".format(component, version))
#print("Release Notes:\n" + release_notes)
else:
upload_component(component)
#send_slack_message('*Released {} version {} to PYPI*\n\nRelease Notes for version {}:\n```\n{}```'.format(component, version, version, release_notes))
def get_release_component():
"""Split the argument passed on the command line into a component name and expected version
"""
global comp_names
if len(sys.argv) < 2:
raise EnvironmentError("Usage: python release.py <component_name>-<version>")
comp = sys.argv[-1]
name, vers = comp.split("-")
if name not in comp_names:
raise EnvironmentError("Invalid unknown release component name", name=name, known_names=comp_names.keys())
return name, vers
def main():
if len(sys.argv) < 2:
print("Usage: release.py [--check] <component_name>-<version>")
sys.exit(1)
dry_run = False
if sys.argv[-2] == '--check':
dry_run = True
component, version = get_release_component()
check_version(component, version)
build_component(component)
release_notes = get_release_notes(component, version)
if dry_run:
print("Check Release\nName: {}\nVersion: {}".format(component, version))
print("Release Notes:\n" + release_notes)
else:
upload_component(component)
send_slack_message('*Released {} version {} to PYPI*\n\nRelease Notes for version {}:\n```\n{}```'.format(component, version, version, release_notes))
def baselevels(self, s, maxlevel=1, brackets="()"):
"""strip parts of a string above a given bracket level
- return a modified (some parts might be removed) version of the string s
where all parts inside brackets with level higher than maxlevel are
removed
- if brackets do not match (number of left and right brackets is wrong
or at some points there were more right brackets than left brackets)
just return the unmodified string"""
level = 0
highestlevel = 0
res = ""
for c in s:
if c == brackets[0]:
level += 1
if level > highestlevel:
highestlevel = level
if level <= maxlevel:
res += c
if c == brackets[1]:
level -= 1
if level == 0 and highestlevel > 0:
return res
def get_info(dynamic=True):
## Date information
date_info = datetime.datetime.now()
date = time.asctime(date_info.timetuple())
revision, version, version_info, vcs_info = None, None, None, None
import_failed = False
dynamic_failed = False
if dynamic:
revision, vcs_info = get_revision()
if revision is None:
dynamic_failed = True
if dynamic_failed or not dynamic:
# This is where most final releases of NetworkX will be.
# All info should come from version.py. If it does not exist, then
# no vcs information will be provided.
sys.path.insert(0, basedir)
try:
from version import date, date_info, version, version_info, vcs_info
except ImportError:
import_failed = True
vcs_info = (None, (None, None))
else:
revision = vcs_info[1][0]
del sys.path[0]
if import_failed or (dynamic and not dynamic_failed):
# We are here if:
# we failed to determine static versioning info, or
# we successfully obtained dynamic revision info
version = ''.join([str(major), '.', str(minor)])
if dev:
version += '.dev_' + date_info.strftime("%Y%m%d%H%M%S")
version_info = (name, major, minor, revision)
return date, date_info, version, version_info, vcs_info
## Version information
def inject_version():
return dict(
version=version.version,
repo_url=libforget.version.url_for_version(version.version),
)
def test_version_looks_like_a_version():
assert re.match(
'v?[0-9]+.[0-9]+.[0-9]+(-[A-Za-z0-9\-.]+)?',
version.version)
def test_libversion_url():
import libforget.version
assert libforget.version.url_for_version(version.version)
def inject_revision():
return dict(revision=version.revision())
def src():
version_string = version.version()
source_name="torscraper-%s.tar.gz" % version_string
source_link="/static/%s" % source_name
return render_template('src.html', source_name=source_name, source_link=source_link)
def whatweb_list(name):
version = request.args.get("version")
account = request.args.get("account")
string = request.args.get("string")
domains = WebComponent.find_domains(name, version=version, account=account, string=string)
return render_template('whatweb_list.html', domains=domains, name=name, version=version, account=account, string=string)
def whatweb_list_json(name):
version = request.args.get("version")
account = request.args.get("account")
string = request.args.get("string")
domains = WebComponent.find_domains(name, version=version, account=account, string=string)
return jsonify(Domain.to_dict_list(domains))
def ParseOptions(self):
'''Read command line options
'''
parser = OptionParser(version=version.description + " version " + version.version + " (" + version.url + ").")
parser.add_option("-d", "--debug", action="store_true", dest="debug", help="debug mode (print extra debug output) [default: %default]")
parser.add_option("-t", "--disttype", action="store", dest="disttype", help="type of distribution to build ('standard', 'nonag', 'stealth', or 'all'). [default: %default]")
parser.add_option("-u", "--uploadonly", action="store_true", dest="uploadonly", help="only upload the release, don't do the build. [default: %default]")
parser.set_defaults(debug=False,
disttype="all",
uploadonly=False)
(self.cmdoptions, args) = parser.parse_args()
def version_check(self):
if raw_input("Current version is " + version.version + ". Is that correct? [Y/N] ") in ["y", "Y", "yes", "YES", "Yes"]:
pass
else:
sys.exit()
def toggle_stealth(self, new_name, new_description, icon_flag):
''' change name, description, in version.py,
rename the icon files and the ini and val files
'''
f = open('version.py','r')
try:
contents=f.readlines()
finally:
f.close()
f = open('version.py','w')
try:
for line in contents:
line = re.sub('^( *name = ).*', '\\1' + '"' + new_name + '"', line)
line = re.sub('^( *description = ).*', '\\1' + '"' + new_description + '"', line)
#line = re.sub('^( *window_title = ).*', '\\1' + '"' + new_window_title + '"', line)
f.write(line)
#if re.search('^( +NagMe = )', line):
#print line
finally:
f.close()
if icon_flag == 1:
shutil.copy(version.name + '.ini', new_name + '.ini')
shutil.copy(version.name + '.val', new_name + '.val')
shutil.copy(version.name + 'icon.ico', new_name + 'icon.ico')
shutil.copy(version.name + 'icon.svg', new_name + 'icon.svg')
shutil.copy(version.name + 'icon_big.gif', new_name + 'icon_big.gif')
else:
os.remove(icon_flag + '.ini')
os.remove(icon_flag + '.val')
os.remove(icon_flag + 'icon.ico')
os.remove(icon_flag + 'icon.svg')
os.remove(icon_flag + 'icon_big.gif')
def update_nsis_script_version(self):
f = open('pykeylogger_install_script.nsi','r')
try:
contents=f.readlines()
finally:
f.close()
f = open('pykeylogger_install_script.nsi','w')
try:
for line in contents:
line = re.sub('^( *!define PYKEYLOGGER_VERSION ).*', '\\1' + '"' + version.version + '"', line)
f.write(line)
finally:
f.close()
def initialize_main_panel(self):
#create the main panel window
#root = Tk()
#root.title("PyKeylogger Control Panel")
# create a menu
self.root.title("PyKeylogger Control Panel")
self.root.config(height=200, width=200)
self.root.protocol("WM_DELETE_WINDOW", self.close)
# Display the version in main window
g = Pmw.Group(self.root, tag_pyclass = None)
g.pack(fill = 'both', expand = 1, padx = 6, pady = 6)
textlabel = Label(g.interior(),
text="PyKeylogger " + str(version.version),
font=("Helvetica", 18))
textlabel.pack(padx = 2, pady = 2, expand='yes', fill='both')
# Pretty logo display
photo = PhotoImage(file=os.path.join(myutils.get_main_dir(),
version.name + "icon_big.gif"))
imagelabel = Label(self.root, image=photo, height=160, width=200)
imagelabel.photo = photo
imagelabel.pack()
# Create and pack the MessageBar.
self.message_bar = Pmw.MessageBar(self.root,
entry_width = 50,
entry_relief='groove',
labelpos = 'w',
label_text = 'Status:')
self.message_bar.pack(fill = 'x', padx = 10, pady = 10)
self.message_bar.message('state',
'Please explore the menus.')
# Create main menu
menu = MainMenu(self.root, self.panelsettings, self)
def __init__(self):
self.configfile=version.name + ".ini"
self.configval=version.name + ".val"
def check_version(component, expected_version):
"""Make sure the package version in setuptools matches what we expect it to be
"""
_, relative_compath = comp_names[component]
compath = os.path.realpath(os.path.abspath(relative_compath))
sys.path.insert(0, compath)
import version
if version.version != expected_version:
raise EnvironmentError("Version mismatch during release, expected={}, found={}".format(expected_version, version.version))
def get_release_notes(component, version):
_, relative_compath = comp_names[component]
notes_path = os.path.join(relative_compath, 'RELEASE.md')
try:
with open(notes_path, "r") as f:
lines = f.readlines()
except IOError:
print("ERROR: Could not find release notes file RELEASE.md")
sys.exit(1)
release_lines = {y[2:].strip(): x for x, y in enumerate(lines) if y.startswith('##')}
if version not in release_lines:
print("ERROR: Could not find release notes for current release version")
sys.exit(1)
start_line = release_lines[version]
past_releases = [x for x in release_lines.itervalues() if x > start_line]
if len(past_releases) == 0:
release_string = "".join(lines[start_line+1:])
else:
release_string = "".join(lines[start_line:min(past_releases)])
if len(release_string) == 0:
print("ERROR: Empty release notes for current release version")
sys.exit(1)
return release_string
def _get_boost_version(boost_path):
# Assuming the path exists here
# Return (major, minor, patch)
with open(os.path.join(boost_path,"boost","version.hpp"),"r") as f:
data = f.read()
version = int(re.findall("#define +BOOST_VERSION +([0-9]+)",data)[0])
return version / 100000, version / 100 % 1000, version % 100
def _is_boost_new_enough(boost_path):
# Caveat, it has to be a high enough version...
major, minor, patch = _get_boost_version(boost_path)
if major > 1:
return True
if major == 1 and minor >= 55:
return True
return False
def _install_boost():
"""Determine if we need to install liboost, and do so."""
# If it's already installed, don't install it.
if _get_boost_path() != None:
# Caveat, it has to be a high enough version...
major, minor, patch = _get_boost_version(_get_boost_path())
if major > 1:
return
if major == 1 and minor >= 55:
return
print("Installing boost.")
# Looks like we need to build it
try:
#out = subprocess.check_output("pip install -vvv larissa_boost",shell=True)
# No idea why setup.py correctly installs larissa_boost in this case where pip does not.
os.system("pip download larissa_boost")
os.system("tar xf larissa_boost*")
_, names, _ = next(os.walk("."))
os.chdir([name for name in names if "larissa_boost" in name][0])
out = subprocess.check_output("python setup.py install",shell=True)
except Exception as e:
raise Exception(e.output)
print(out)
print(os.system("ls -la $VIRTUAL_ENV/"))
print(os.system("ls -la $VIRTUAL_ENV/include/"))
print(os.system("ls -la $VIRTUAL_ENV/boost/"))
print(os.system("ls -la $VIRTUAL_ENV/boost/include"))
def _install_triton():
# Locate the needed libraries
capstone_include = re.match("(.*)/capstone$", find_file("capstone.h")).group(1)
capstone_lib = os.path.join(find_file("libcapstone.so"),"libcapstone.so")
cpath = [find_file("z3++.h")]
cpath.append(find_file("z3.h"))
cpath.append(find_file("z3_ast_containers.h"))
# Using triton version included in larissa due to triton not being in pypi
os.chdir(os.path.join(here,"lib","triton"))
os.mkdir("build")
os.chdir("build")
cmake_options = [
'-DCMAKE_INSTALL_PREFIX={0}'.format(sys.prefix),
'-DCAPSTONE_INCLUDE_DIR={0}'.format(capstone_include),
'-DCAPSTONE_LIBRARY={0}'.format(capstone_lib)
]
# Custom boost install dir
if _get_boost_path() != "/usr/include":
cmake_options.append("-DBoost_INCLUDE_DIR={0}".format(os.path.join(_get_boost_path(),"include")))
cmake_options.append("-DBoost_LIBRARY_DIR={0}".format(os.path.join(_get_boost_path(),"lib")))
cpath = ["/usr/include"] + cpath
cpath.append(os.path.join(_get_boost_path(),"include"))
try:
print("cmake {0} ..".format(' '.join(cmake_options)))
subprocess.check_output("cmake {0} ..".format(' '.join(cmake_options)),shell=True)
except Exception as e:
raise Exception(e.output)
try:
print("CPATH={1} make -j{0} install".format(multiprocessing.cpu_count(), ':'.join(cpath)))
subprocess.check_output("CPATH={1} make -j{0} install".format(multiprocessing.cpu_count(), ':'.join(cpath)),shell=True)
except Exception as e:
raise Exception(e.output)
os.chdir(here)
def print_help():
print
script = os.path.basename(sys.argv[0])
print "usage:"
print " %s [options] input_file [input_file ...]" % script
print " or "
print " %s --help" % script
print " or "
print " %s --version" % script
dump_config_info(CONFIG.config, CONFIG.info)
def print_version():
import version
print "%d.%d.%d" % version.version
def parse_cmdline(args):
options = dict()
pathes = []
if "--help" in args:
print_help()
sys.exit(0)
if "--version" in args:
print_version()
sys.exit(0)
for arg in args:
if arg.startswith("--"):
if "=" in arg:
pre, __, post = arg.partition("=")
options[pre[2:]] = post
else:
options[arg[2:]] = True
else:
pathes.append(arg)
if not pathes:
print_help()
raise Exception("no input file given")
CONFIG.update(options)
dump_config(CONFIG.config)
return pathes