Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_config_from_file(self, key, attr, value, tmpdir):
config_file = tmpdir.join("config.yaml")
with config_file.open("w") as fobj:
pyaml.dump({key: value}, fobj, safe=True, default_style='"')
config = Configuration(["--config-file", config_file.strpath])
assert getattr(config, attr) == value
testdir = os.path.join(testdir, testcase)
if not os.path.exists(testdir):
os.makedirs(testdir)
test_log = os.path.join(testdir, 'test.log')
inventory_file = os.path.join(testdir, 'inventory.txt')
play_yml = os.path.join(testdir, 'play.yml')
# Remove stale logs
if os.path.exists(test_log):
os.remove(test_log)
# Write dict to proper yaml playbook
with open(play_yml, 'w') as fh:
fh.write(pyaml.dumps(play_dict))
# Write the inventory
with open(inventory_file, 'w') as fh:
fh.write(inventory)
actual_command = 'ANSIBLE_LOG_PATH="%s" ansible-playbook -i %s -M %s %s -vvv' % (test_log, inventory_file, ansible_module_path, play_yml)
print(actual_command)
retval = subprocess.call(actual_command, shell=True)
# Parse json return object from verbose log output
with open(test_log, 'r') as fh:
json_lines = []
in_json = False
for line in fh:
if not in_json:
log.addHandler(handler)
log.setLevel(logging.DEBUG if args.verbose else logging.INFO)
log.info("MISP<->STIX Converter")
# Set the config file
if args.config:
configfile = args.config
else:
configfile = os.path.expanduser("~/.misptostix/misp.login")
log.debug("Using config file at %s", configfile)
try:
with open(configfile, "r") as f:
CONFIG = pyaml.yaml.load(f)
except FileNotFoundError:
print("Could not find config file {}".format(configfile))
sys.exit(1)
if args.tag and not ("{}" in args.outfile):
args.outfile += ".{}"
if args.format:
args.format = args.format.lower()
if args.format not in ["json", "xml"]:
print("Only possible output formats are JSON and XML.")
print("{} is not valid".format(args.format))
sys.exit()
else:
args.format = "json"
log.setLevel(logging.DEBUG if args.verbose else logging.INFO)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.DEBUG if args.verbose else logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
log.addHandler(ch)
# Set the config file
if args.config:
configfile = args.config
else:
configfile = os.path.expanduser("~/.misptostix/misp.login")
try:
with open(configfile, "r") as f:
CONFIG = pyaml.yaml.load(f)
except FileNotFoundError:
log.fatal("Could not find config file %s", configfile)
sys.exit(1)
# Backwards compatability, if users haven't updated config
if "SSL" not in CONFIG["MISP"]:
log.warning("Please update your config file using the misp.login.example to include SSL")
time.sleep(1)
CONFIG["MISP"]["SSL"] = False
# This is just a file conversion
# Relatively quick and easy
MISP = misp.MISP(CONFIG["MISP"]["URL"], CONFIG["MISP"]["KEY"], CONFIG["MISP"].get("SSL", True))
# Load the package
log.info("Opening STIX file %s", args.file)
d['requirements']['build'] = ["PLACEHOLDER"]
d['test']['commands'] = ['''LD_LIBRARY_PATH="${BUILD_PREFIX}/x86_64-conda_cos6-linux-gnu/sysroot/usr/lib64" $R -e "library('{{ name }}')"''']
if self.extra:
d['extra'] = self.extra
if self._cb3_build_reqs:
d['requirements']['build'] = []
else:
d['build']['noarch'] = 'generic'
for k, v in self._cb3_build_reqs.items():
d['requirements']['build'].append(k + '_' + "PLACEHOLDER")
rendered = pyaml.dumps(d, width=1e6).decode('utf-8')
# Add Suggests: and SystemRequirements:
renderedsplit = rendered.split('\n')
idx = renderedsplit.index('requirements:')
if self.packages[self.package].get('SystemRequirements', None):
renderedsplit.insert(idx, '# SystemRequirements: {}'.format(self.packages[self.package]['SystemRequirements']))
if self.packages[self.package].get('Suggests', None):
renderedsplit.insert(idx, '# Suggests: {}'.format(self.packages[self.package]['Suggests']))
# Fix the core dependencies if this needsX
if self.needsX:
idx = renderedsplit.index(' build:') + 1
renderedsplit.insert(idx, " - xorg-libxfixes # [linux]")
renderedsplit.insert(idx, " - {{ cdt('libxxf86vm') }} # [linux]")
renderedsplit.insert(idx, " - {{ cdt('libxdamage') }} # [linux]")
renderedsplit.insert(idx, " - {{ cdt('libselinux') }} # [linux]")
renderedsplit.insert(idx, " - {{ cdt('mesa-dri-drivers') }} # [linux]")
from misp_stix_converter.converters import lint_roller
import logging
# Set up logger
log = logging.getLogger(__name__)
formatter = logging.Formatter(
"%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch = logging.FileHandler("push.log")
ch.setFormatter(formatter)
log.addHandler(ch)
log.setLevel(logging.DEBUG)
log.info("Starting...")
# Try to load in config
if "OPENTAXII_CONFIG" in os.environ:
config = yaml.load(open(os.environ["OPENTAXII_CONFIG"], "r"))
else:
print("OPENTAXII CONFIG NOT EXPORTED")
sys.exit()
# Set up our ZMQ socket to recieve MISP JSON on publish
context = zmq.Context()
socket = context.socket(zmq.SUB)
log.info("Subscribing to tcp://{}:{}".format(
config["zmq"]["host"],
config["zmq"]["port"]
))
# Connect to the socket
socket.connect("tcp://{}:{}".format(
config["zmq"]["host"],
def auth(self):
status = True
manager = Manager.objects.get(name=self.metadata['cloud_endpoint'])
if not os.path.isdir(self.metadata['template_path']):
status = False
try:
config_file, filename = tempfile.mkstemp()
config_content = {
'clouds': {self.name: manager.metadata}
}
os.write(config_file, pyaml.dump(config_content).encode())
os.close(config_file)
self.cloud = os_client_config.config \
.OpenStackConfig(config_files=[filename]) \
.get_one_cloud(cloud=self.name)
os.remove(filename)
self.api = self._get_client('orchestration')
except ConnectFailure as exception:
logger.error(exception)
status = False
return status
'contexts': [{
'context': {
'cluster': self.name,
'user': self.name,
},
'name': self.name,
}],
'current-context': self.name,
'kind': 'Config',
'preferences': {},
'users': [{
'name': self.name,
'user': self.metadata['user']
}]
}
os.write(config_file, pyaml.dump(config_content).encode())
os.close(config_file)
self.config_wrapper = pykube.KubeConfig.from_file(filename)
os.remove(filename)
self.api = pykube.HTTPClient(self.config_wrapper)
pods = pykube.Pod.objects(self.api).filter(namespace="kube-system")
for pod in pods:
pass
except URLError as exception:
logger.error(exception)
status = False
except ConnectionError as exception:
logger.error(exception)
status = False
return status
# in messages
msg = msg.replace('Explanation:', '\n Explanation:')
# The settings will tell us if we should show all details or not
# The message is part of the details, so if it's already being shown
# do not show it again
details = None
if self.suite.config.pr_comment_report.get('show_details', False):
result_details = dict(result.details)
if show_message:
del result_details['message']
if not result_details:
details = None
else:
details = PRCommentReport._increase_readability(
pyaml.dump(result_details)
)
msg = '\n {}'.format(msg) if msg else ''
details = '\n {}'.format(details) if details else ''
return '- **{check_type}**{msg}{details}'.format(
check_type=result.config.check_type, msg=msg, details=details
)
def _dump_yaml():
yaml_str = ""
if len(_secrets) > 0:
yaml_str = pyaml.dump(_secrets, string_val_style="plain")
yaml_str = "%s\n---\n" % yaml_str
yaml_str = yaml_str + pyaml.dump(yaml(), string_val_style="plain")
print(yaml_str)