Пример #1
0
def get_git_version():
    '''
    eg,
    {'commit': 'a5c7865efd188715a8436ef7be23e38448e2aa60', 'describe': 'v1.0'}
    '''
    from run_command import run_command
    version = {}
    rtn,out,err = run_command('git log --max-count=1 | head -n 1')
    assert(rtn == 0)
    lines = out.split('\n')
    lines = [l for l in lines if len(l)]
    for l in lines:
        words = l.split(' ', 1)
        words = [w.strip() for w in words]
        version[words[0]] = words[1]

    rtn,out,err = run_command('git describe')
    if rtn == 0:
        # this can fail if there has been no "git tag"
        lines = out.split('\n')
        lines = [l for l in lines if len(l)]
        assert(len(lines) == 1)
        version['describe'] = lines[0]

    return version
    def ensure_local_cask_repo_present(self):
        """
        Ensure that the repo contain the local cask definitions is present

        Returns:
            No return
            
            Will exit if an error occurs during repo cloning.

        """
        if not path.exists(LOCAL_CASK_REPO_DIR):
            # git clone [email protected]:tflynn/private_casks.git
            cmd = ['git', 'clone', LOCAL_CASK_REPO_URL]
            results = run_command(cmd=cmd, working_dir=STARTUP_DIR, logger=self.logger)
            if not results.success:
                self.logger.error(("BrewCaskLocalInstaller error cloning cask definitions repo"
                                    + " status {0} results {1} errors {2}").format(
                                    results.status_code, results.results, results.errors))
                sys.exit(1)

        else:
            # git pull
            cmd = ['git', 'pull']
            results = run_command(cmd=cmd, working_dir=LOCAL_CASK_REPO_DIR, logger=self.logger)
            if not results.success:
                self.logger.error(("BrewCaskLocalInstaller error updating cask definitions repo"
                                    + " status {0} results {1} errors {2}").format(
                                    results.status_code, results.results, results.errors))
                sys.exit(1)

        return
Пример #3
0
def get_git_version():
    '''
    eg,
    {'commit': 'a5c7865efd188715a8436ef7be23e38448e2aa60', 'describe': 'v1.0'}
    '''
    from run_command import run_command
    version = {}
    rtn, out, err = run_command('git log --max-count=1 | head -n 1')
    assert (rtn == 0)
    lines = out.split('\n')
    lines = [l for l in lines if len(l)]
    for l in lines:
        words = l.split(' ', 1)
        words = [w.strip() for w in words]
        version[words[0]] = words[1]

    rtn, out, err = run_command('git describe')
    if rtn == 0:
        # this can fail if there has been no "git tag"
        lines = out.split('\n')
        lines = [l for l in lines if len(l)]
        assert (len(lines) == 1)
        version['describe'] = lines[0]

    return version
Пример #4
0
def clone_web_app():
	import sys
	sys.path.append('..')
	from run_command import run_command
	from server_communication.post_resource_to_server import post_resource_to_server

	run_command('git clone https://github.com/elevati0n/batphoneWebApp.git')
	run_command('cd batphoneWebApp; sudo bundle install')
Пример #5
0
def install_batctl():
	'''Installs batctl a BATMAN-Advanced configuration tool.

	ARGS:
	None

	RETURN:
	None
	'''
	import sys
	sys.path.append('..')
	from run_command import run_command	
	run_command('sudo apt-get batctl')
Пример #6
0
def install_batctl():
    '''Installs batctl a BATMAN-Advanced configuration tool.

	ARGS:
	None

	RETURN:
	None
	'''
    import sys
    sys.path.append('..')
    from run_command import run_command
    run_command('sudo apt-get batctl')
def change_ip(interface, ip):
	'''Change an interfaces IP address.

	ARGS:
	@interface  		-- The interface to be changed.
	@ip 				-- The new IP address to use.

	RETURNS:
	None
	'''
	import sys
	sys.path.append(..)
	from run_command import run_command

	run_command('sudo ifconfig ' + interface + ' ' + ip)
def join_batman_network_as_master(ssid = 'squids_network',
								  ap = '02:12:34:56:78:9A',
								  channel = 1,
								  gateway = True):
	import sys
	import threading
	sys.path.append('..')
	from run_command import run_command

	if gateway:
		from join_batman_network_as_gateway import join_batman_network_as_gateway
		interface = 'br-lan'
		join_batman_network_as_gateway(ssid, ap, channel)
	else:
		from join_batman_network import join_batman_network
		interface = 'bat0'
		join_batman_network(ssid, ap, channel)

	with open('/etc/dhcp/dhcpd.conf', 'w') as dhcp_file:
		dhcp_file.write('ddns-update-style none;\n\n' +
						'default-lease-time 600;\n' +
						'max-lease-time 7200;\n\n' +
						'authoritative;\n\n' +
						'subnet 192.168.10.0 netmask 255.255.255.0 {\n' +
						'	range 192.168.10.10 192.168.10.250;\n' +
						'	option broadcast-address 192.168.10.255;\n' +
						'	option routers 192.168.10.1;\n' +
						'	default-lease-time 600;\n' +
						'	max-lease-time 7200;\n' +
						'	option domain-name "batlan";\n' +
						'	option domain-name-servers 8.8.8.8 8.8.4.4;\n' +
						'}')

	with open('/etc/default/isc-dhcp-server', 'w') as server_file:
		server_file.write('INTERFACES="' + interface + '"')

	run_command('sudo ifdown wlan0')
	with open('/etc/network/interfaces', 'w') as interfaces_file:
		interfaces_file.write('auto lo\n\n' +
							  'iface lo inet loopback\n' +
							  'iface eth0 inet dhcp\n\n' +
							  'allow-hotplug ' + interface + '\n\n' +
							  'iface ' + interface + ' inet static\n' +
							  ' address 192.168.10.1\n' +
							  ' netmask 255.255.255.0')

	command = 'sudo service isc-dhcp-server restart'
	thread = threading.Thread(target=run_command, args=(command, ))
Пример #9
0
    def install(self):
        """
        Install a MAS package

        Returns:
            bool:

            True if installation occurred.

            False if package already installed or installation failed

        """

        if self.is_present():
            self.logger.info(
                "MASInstaller.install {0} is already installed".format(
                    self.package_info.name))
            return False
        else:
            self.logger.info("MASInstaller.installing {0}".format(
                self.package_info.name))
            cmd = ["mas", "install", self.package_info.mas_id]
            results = run_command(cmd=cmd, logger=self.logger)
            if results.success:
                self.logger.info("MASInstaller.install {0} succeeded".format(
                    self.package_info.name))
                return True
            else:
                self.logger.error(
                    "MASInstaller.install {0} failed status {1} results {2} errors {3}"
                    .format(self.package_info.name, results.status_code,
                            results.results, results.errors))
                return False
Пример #10
0
 def test_command_that_finishes(self):
     reason, code, output = run_command(
         ['echo', 'hello world']
     )
     self.assertEqual(reason, NORMAL)
     self.assertEqual(code, 0)
     self.assertEqual(output, 'hello world\n')
Пример #11
0
 def test_command_too_much_time(self):
     reason, code, output = run_command(
         ['sleep', '5'],
         timeout=1,
     )
     self.assertEqual(reason, KILLED_TIME)
     self.assertNotEqual(code, 0)
Пример #12
0
def warp(subDir, sub, movFile, targFile, roiDir, outDir):

    matFile
    preFile

    roiFiles = [f for f in listdir(roiDir) if isfile(join(roiDir, f))]




    T1=Template("3dAllineate -base $_base -source $_source -prefix $_preFile -master $_base -1Dmatrix_save $_matFile -overwrite")\
    T1=T1.substitute(_base=targFile, _source=movFile, _pre=preFile, _matFile=matFile)

    for f in roiFiles:
        T2="3dAllineate -base  -source -prefix -master -1Dmatrix_apply -overwrite".format()

        T3="fslmaths {} -thr 0.05  -bin  {}".format()

        T4="rm {}".format()



    out, error = run_command(T)


    t = Template('dwi2fod msmt_csd $_DWI $_RF_WM $_WM_FODs $_RF_GM $_GM $_RF_CSF $_CSF -mask $_nodif')
    c=t.substitute(_DWI=self._DWI, _RF_WM=self._RF_WM, _WM_FODs=self._WM_FODs, _RF_GM=self._RF_GM, _GM=self._GM, _RF_CSF=self._RF_CSF, _CSF=self._CSF, _nodif=self.nodif_brain_mask)
    output, error = self.run_command(c)
    def process_receipt_info(self, app_name):
        """
        Process a receipts zip if present in the installed App

        Args:
            app_name: Name of app to search for receipts zip

        Returns:
            bool:

            True: If no zip or no errors during unzip processing

            False: If any errors during unzip processing

        """
        tmp_dir = os.environ['MY_TEMP']

        # Extract receipts zip and unpack to /private/var/db/receipts
        possible_zips = glob.glob("/Applications/{0}/*-receipts.zip".format(app_name), recursive=False)
        if possible_zips:
            receipts_zip_file = possible_zips[0]
            full_target_dir = '/private/var/db/receipts'
            # "sudo unzip <zip file name> -d dir"
            cmd = ['sudo', 'unzip', receipts_zip_file, '-d', full_target_dir]
            results = run_command(cmd=cmd, logger=self.logger)
            if not results.success:
                if results.results:
                    self.logger.info("unzip receipts results {0}".format(results.results))
                if results.errors:
                    self.logger.info("unzip receipts errors {0}".format(results.errors))
                return False

        return True
    def remove(self):
        """
        Remove a Homebrew CaskLocal package

        Returns:
            bool:

            True if removal succeeded

            False if package not installed or removal failed.

        """
        self.ensure_local_cask_repo_present()

        if self.is_present():
            cmd = ["brew", "cask", "uninstall", self.package_info.name]
            results = run_command(cmd=cmd, logger=self.logger)
            if results.success:
                if not self.is_present():
                    self.logger.info("BrewCaskLocalInstaller.remove {0} removal succeeded".format(
                        self.package_info.name))
                    return True
                else:
                    self.logger.warning("BrewCaskLocalInstaller.remove {0} removal failed".format(
                        self.package_info.name))
                    return False
            else:
                self.logger.error("BrewCaskLocalInstaller.remove {0} failed status {1} results {2} errors {3}".format(
                    self.package_info.name, results.status_code, results.results, results.errors))
                return False
        else:
            self.logger.info("BrewCaskLocalInstaller.remove {0} is not installed".format(self.package_info.name))
            return False
def open_tcp_ports():
	'''Find all open TCP ports above port 1000 on this machine.

	ARGS:
	None

	RETURNS:
	@ports 		-- The LIST of open tcp port INTEGERS
	'''

	import re
	import sys
	import string
	sys.path.append('..')
	from run_command import run_command

	stdout, stderr = run_command('netstat -l')
	print stdout
	ports = string.split(stdout, '\n')[2 : ]
	open_ports = []
	for port in ports:
		attributes = string.split(port)
		if attributes[5] != 'LISTEN' and attribues[4] != '*:*':
			continue

		port_num = port[3][2 : ]
		if not port_num.isdigit():
			continue

		open_ports.append(port_num)

	return open_ports
Пример #16
0
 def test_command_too_much_length(self):
     reason, code, output = run_command(
         ['yes'],
         max_length=100
     )
     self.assertEqual(reason, KILLED_LENGTH)
     self.assertNotEqual(code, 0)
     assert len(output) <= 100
Пример #17
0
    def remove(self):
        """
        Remove a MAS package


        Returns:
            bool:

            True if removal succeeded

            False if package not installed or removal failed.

        """

        self.logger.warning(
            "MASInstaller.remove ia experimental. Use at your own risk")
        if self.is_present():
            app_name = "/Applications/{0}.app".format(self.package_info.name)
            cmd = ["sudo", "rm", "-rf", app_name]
            results = run_command(cmd=cmd, logger=self.logger)
            if results.success:
                if self.is_present():
                    self.logger.warning(
                        "MASInstaller.remove {0} removal failed".format(
                            self.package_info.name))
                    return False
                else:
                    self.logger.info(
                        "MASInstaller.remove {0} removal succeeded".format(
                            self.package_info.name))
                    trash_dir = "{0}/.Trash/*".format(os.environ['HOME'])
                    cmd = ["sudo", "rm", "-rf", trash_dir]
                    run_command(cmd=cmd, logger=self.logger)
                    # Ignore errors
                    return True
            else:
                self.logger.error(
                    "MASInstaller.remove {0} failed status {1} results {2} errors {3}"
                    .format(self.package_info.name, results.status_code,
                            results.results, results.errors))
                return False
        else:
            self.logger.info("MASInstaller.remove {0} is not installed".format(
                self.package_info.name))
            return False
Пример #18
0
def fix_file_expecting_no_change(file):
    command, infile, outfile, status, stdout = fix_file_helper(file)
    if status != 0:
        return 1
    status, stdout, stderr = run_command('diff ' + outfile + ' ' + infile)
    if status != 0:
        logging.error(file + ': expected file to remain unchanged')
        return 1
    return 0
    def interpret_args(self, args, client, address):
        """Interpret the arguments received from another device and do what they ask.

		ARGS:
		@args 			-- The list of arguments to execute.
		@client 		-- The client the data came from.
		@address		-- The client's return address.

		RETURNS:
		None
		"""
        if args[0] == "ping":
            (stdout, stderr) = run_command("sudo batctl ping -c 1" + args[1])
            xml_ping = xml_parser.parse_ping_to_xml(stdout)
            client_send_message(address, "ping_response " + open(xml_ping, "r").read())
        elif args[0] == "traceroute":
            (stdout, stderrr) = run_command("sudo batctl traceroute " + args[1])
            xml_traceroute = xml_parser.parse_traceroute_to_xml(stdout)
            client_send_message(address, "traceroute_response " + open(xml_traceroute, "r").read())
Пример #20
0
	def retrieve(self, filetype, run, camcol, field, band=None, skipExisting=True):
		outfn = self.getPath(filetype, run, camcol, field, band)
		if outfn is None:
			return None
		if skipExisting and os.path.exists(outfn):
			return outfn
		rerun = self.get_rerun(run, field)
		path = self.daspaths[filetype]
		url = self.dasurl + path % dict(run=run, camcol=camcol, field=field, rerun=rerun,
										band=band)
		#print 'URL:', url
		if self.curl:
			cmd = "curl -o '%(outfn)s' '%(url)s"
		else:
			cmd = "wget --continue -nv -O %(outfn)s '%(url)s'"

		# suffix to add to the downloaded filename
		suff = self.dassuffix.get(filetype, '')
		
		cmd = cmd % dict(outfn=outfn + suff, url=url)
		#print 'cmd:', cmd
		(rtn,out,err) = run_command(cmd)
		if rtn:
			print 'Command failed: command', cmd
			print 'Output:', out
			print 'Error:', err
			print 'Return val:', rtn
			return None

		if filetype in self.processcmds:
			cmd = self.processcmds[filetype]
			cmd = cmd % dict(input = outfn + suff, output = outfn)
			print 'cmd:', cmd
			(rtn,out,err) = run_command(cmd)
			if rtn:
				print 'Command failed: command', cmd
				print 'Output:', out
				print 'Error:', err
				print 'Return val:', rtn
				return None

		return outfn
def parse_iwconfig():
	'''Parser the iwconfig commands output into a list of
	dictionaries containing information about each wireless
	interface.

	ARGS:
	None

	RETURNS:
	@interfaces -- Interfaces as a LIST of DICTIONARIES 
				   Keys:
					  interface Ex. wlan0 				STRING
					  essid 	Ex. NUwave 				STRING
					  ap 		Ex. 02:12:34:56:78:9A   STRING
					  mode 		Ex. Managed, Ad-Hoc 	STRING
	'''

	import sys
	import shlex
	sys.path.append('..')
	from run_command import run_command

	# Run iwconfig and split stdout into interface chunks
	(stdout, stderr) = run_command('iwconfig')
	interfaces = stdout.split('\n\n')

	library = []
	for intrfc in interfaces:
		# Create a dictionary for each interface
		dictionary = {'interface' : None, 'essid' : None, 'ap' : None, 'mode' : None}
		essid_index = intrfc.find('ESSID:')
		mode_index = intrfc.find('Mode:')
		ap_index = intrfc.find('Access Point:')

		# If the interface isn't blank record it's info
		if len(shlex.split(intrfc)) > 0:
			# Grab the name of the interface and store it
			dictionary['interface'] = shlex.split(intrfc)[0]

			# Check that all other attributes exist and grab the ones
			# that do to be recorded
			if essid_index != -1:
				net = shlex.split(intrfc[essid_index + 6 :])[0]
				dictionary['essid'] = net
			if mode_index != -1:
				dongle_mode = shlex.split(intrfc[mode_index + 5 : ])[0]
				dictionary['mode'] = dongle_mode
			if ap_index != -1:
				mac = shlex.split(intrfc[ap_index + 13 : ])[0]
				dictionary['ap'] = mac

			# Append the interfaces dictionary to the list of them
			library.append(dictionary)
	return library
Пример #22
0
def get_svn_version():
    from run_command import run_command
    version = {}
    rtn, out, err = run_command('svn info')
    assert (rtn == 0)
    lines = out.split('\n')
    lines = [l for l in lines if len(l)]
    for l in lines:
        words = l.split(':', 1)
        words = [w.strip() for w in words]
        version[words[0]] = words[1]
    return version
Пример #23
0
def get_include_dirs(pkg):
	(rtn,out,err) = run_command('pkg-config --cflags-only-I ' + pkg)
	if rtn:
		raise Exception('Failed to find include paths for package ' + pkg)
	if err and len(err):
		print 'pkg-config complained:', err
	dirs = out.split()
	dirs = [l for l in dirs if len(l)]
	# Strip off the leading "-I"
	dirs = [l[2:] for l in dirs]
	#print 'returning include dirs:', dirs
	return dirs
Пример #24
0
def load_batman(password):
    '''Load BATMAN-Advanced.

	ARGS:
	None

	RETURN:
	Boolean	-- True if successful; otherwise False
	'''
    import sys
    sys.path.append('..')
    from run_command import run_command

    # Run the load and store stdout
    run_command('sudo modprobe batman-adv', password)
    out, err = run_command('dmesg', password)

    # Check if load was successful
    if 'BATMAN-Advanced was loaded successfully' in out:
        return True
    return False
Пример #25
0
def load_batman(password):
	'''Load BATMAN-Advanced.

	ARGS:
	None

	RETURN:
	Boolean	-- True if successful; otherwise False
	'''
	import sys
	sys.path.append('..')
	from run_command import run_command

	# Run the load and store stdout
	run_command('sudo modprobe batman-adv', password)
	out, err = run_command('dmesg', password)

	# Check if load was successful
	if 'BATMAN-Advanced was loaded successfully' in out:
		return True
	return False
Пример #26
0
def get_svn_version():
    from run_command import run_command
    version = {}
    rtn,out,err = run_command('svn info')
    assert(rtn == 0)
    lines = out.split('\n')
    lines = [l for l in lines if len(l)]
    for l in lines:
        words = l.split(':', 1)
        words = [w.strip() for w in words]
        version[words[0]] = words[1]
    return version
Пример #27
0
def get_include_dirs(pkg):
    (rtn, out, err) = run_command('pkg-config --cflags-only-I ' + pkg)
    if rtn:
        raise Exception('Failed to find include paths for package ' + pkg)
    if err and len(err):
        print 'pkg-config complained:', err
    dirs = out.split()
    dirs = [l for l in dirs if len(l)]
    # Strip off the leading "-I"
    dirs = [l[2:] for l in dirs]
    #print 'returning include dirs:', dirs
    return dirs
def join_wifi(ssid = None, password = None):
	'''Joins a wifi network via editing wpa config files and cycling wlan0.

	ARGS:
	@ssid		-- The name of the network intended to be joined.
	@password    -- The password to the network with the corresponding ssid.

	RETURN:
	None
	'''
	import sys
	import time
	sys.path.append('..')
	from run_command import run_command

	# If ssid is none then no network can be joined, therefore return None
	if ssid == None:
		return None

	# Appends network configuration lines to the end of 
	# /etc/wpa_supplicant/wpa_supplicant.conf
	# Ex.
	# network={
	#     ssid="example"
	#     psk="example_password"
	# }
	with open('/etc/wpa_supplicant/wpa_supplicant.conf', 'a') as myfile:
		myfile.write('\n')
		myfile.write('network={\n')
		myfile.write('    ssid="' + ssid + '"\n')
		if password:
			myfile.write('	  psk="' + password + '"\n')
		myfile.write('}\n')
		myfile.flush()
		myfile.close()

	# Cycle the wlan0 interface so that the device joins the network																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																				q
	run_command('sudo ifdown wlan0')
	time.sleep(1)
	run_command('sudo ifup wlan0')
Пример #29
0
def join_wifi(ssid = None, password = None):
	'''Joins a wifi network via editing wpa config files and cycling wlan0.

	ARGS:
	@ssid		-- The name of the network intended to be joined.
	@password    -- The password to the network with the corresponding ssid.

	RETURN:
	None
	'''
	import sys
	import time
	sys.path.append('..')
	from run_command import run_command

	# If ssid is none then no network can be joined, therefore return None
	if ssid == None:
		return None

	# Appends network configuration lines to the end of 
	# /etc/wpa_supplicant/wpa_supplicant.conf
	# Ex.
	# network={
	#     ssid="example"
	#     psk="example_password"
	# }
	with open('/etc/wpa_supplicant/wpa_supplicant.conf', 'a') as myfile:
		myfile.write('\n')
		myfile.write('network={\n')
		myfile.write('    ssid="' + ssid + '"\n')
		if password:
			myfile.write('	  psk="' + password + '"\n')
		myfile.write('}\n')


	# Cycle the wlan0 interface so that the device joins the network																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																				q
	run_command('sudo ifdown wlan0')
	time.sleep(1)
	run_command('sudo ifup wlan0')
def load_batman():
    """Load BATMAN-Advanced.

	ARGS:
	None

	RETURN:
	Boolean	-- True if successful; otherwise False
	"""
    import sys

    sys.path.append("..")
    from run_command import run_command

    # Run the load and store stdout
    run_command("modprobe batman-adv")
    out, err = run_command("dmesg")

    # Check if load was successful
    if "BATMAN-Advanced was loaded successfully" in out:
        return True
    return False
Пример #31
0
def fix_file_expecting_success(file, extra_input_files=None):
    command, infile, outfile, status, stdout = fix_file_helper(
        file, extra_input_files=extra_input_files)
    if status != 0:
        print("FAILED: " + infile)
        emit_stdout_as_error(stdout)
        return 1
    status, stdout, stderr = run_command('diff ' + outfile + ' ' + infile + '.gold')
    if status != 0:
        print("FAILED: " + infile)
        emit_stdout_as_error(stdout + stderr)
        return 1
    return 0
def play_recording(name, interface = 'headset'):
	'''Playback a recording.

	ARGS:
	@name 		-- The file name of the recording.
	@interface 	-- The interface to play it over.

	RETURNS:
	None
	'''
	import os
	import sys
	sys.path.append('..')
	from run_command import run_command

	path = os.path.join(os.path.abspath(__file__), 
		                '../../resources/recordings', filename)

	if interface == 'headset':
		run_command('./Playback_to_Headset.sh')

	command = 'aplay ' + path
	run_command(command)
Пример #33
0
def start_host(url):
    if is_ip(url):
        return (url)
    command = 'host ' + url
    #host scanme.nmap.org | head -1 | cut -d' ' -f4 (in bash)
    print(command)
    results = run_command(command).decode(
        'utf-8')  #utf-8 changes bytes to string
    start_location = results.index(
        'has address'
    ) + 12  #represents where the string starts so its not static
    stop_location = results.index('\n')
    ip = results[start_location:stop_location]
    return (ip)
def start_recording(filename, el_format = '.wav'):
	'''Start a recording and leave it recording.

	ARGS:
	@filename 		-- The name of the recording to create.
	@el_format 		-- The format of the recording to create.

	RETURNS:
	@process 		-- The running process.
	'''
	import sys
	import shlex
	sys.path.append('..')
	from run_command import run_command
	from subprocess import Popen, PIPE

	run_command('./Record_from_DMIC.sh')

	command = ('arecord -Dhw:sndrpiwsp -r 44100 -c 2 -f S16_LE ' + filename 
	          + '.' + el_format)
	args = shlex.split(command)

	return Popen(args, stdout = PIPE, stderr = PIPE, shell = True)
Пример #35
0
def do_test_runstring(runstring):
    import inspect
    callerframerecord = inspect.stack()[1]  # 0 represents this line
    # 1 represents line at caller
    frame = callerframerecord[0]
    info = inspect.getframeinfo(frame)
    # print info.filename                       # __FILE__     -> Test.py
    # print info.function                       # __FUNCTION__ -> Main
    # print info.lineno                         # __LINE__     -> 13
    output_file_basename = info.filename + '_' + info.function
    output_file_expected = output_file_basename + '.expected'
    output_file_actual = output_file_basename + '.actual'

    if not re.search('^cd ', runstring):
        if product_dir_path == 'not_set':
            assert False, "File %s, line %d: product_dir_path is not set." % (
                info.filename, info.lineno)
        runstring = "cd " + product_dir_path + "; " + runstring
    rc, output, error = run_command(runstring)
    assert rc == 0, "File %s, line %d: run_command rc != 0.  output: %s.  error: %s" % (
        info.filename, info.lineno, output, error)
    fd = open(output_file_actual, 'w')
    for line in output.split('\n'):
        fd.write(line + '\n')
    fd.close()
    rc, diff_results, error = run_command("diff " + output_file_expected +
                                          " " + output_file_actual)
    msg1 = "File %s, line %d: " % (info.filename, info.lineno)
    msg2 = "diff rc != 0.\n----- output:\n%s\n----- error:\n%s" % (
        diff_results, error)
    assert rc == 0, msg1 + msg2
    msg2 = "diff error != ''.\n----- output:\n%s\n----- error:\n%s" % (
        diff_results, error)
    assert error == '', msg1 + msg2
    msg2 = "diff output != expected.  len(diff_results_list): %d\n----- diff_results:\n%s\n" % (
        len(diff_results.split('\n')), str(diff_results))
    assert diff_results == '', msg1 + msg2
Пример #36
0
def join():
	import requests
	import webbrowser
	from sockets import TCPSocket
	from run_command import run_command
	from read_mac_address import read_mac_address
	from join_batman_network import join_batman_network

	error = None
	try:
		from 
		from run_command import run_command
		from sockets import TCPSocket
		from join_batman_network import join_batman_network
		ssid = request.form['ssid']
		publickey = request.form['publickey']
		mac = request.form['mac']
		password = request.form['admin_password']
		interface = request.form['interfaces']

		join_batman_network(password = password,
				    interface = interface,
				    network_name = ssid,
				    ap_mac = mac)

		if_mac = read_mac_address(interface)
		sock = TCPSocket()
		sock.connect('192.168.2.15', 5005)
		sock.write('DHCP ' + if_mac + '/n')

		response = socket.read()
		run_command('sudo ifconfig bat0 ' + response, password)		
		
		print 'Successfully Joined Network'
	except StormpathError, err:
		error = err.message
Пример #37
0
 def on_push_button_run_clicked(self):
     command = str(self.line_edit_command.text())
     output = None
     command_config = {}
     try:
         output, command_config = run_command(
             command, self.commands, self.setting("defaultCommandSettings"))
     except Exception as e:
         print e
         return self.show_error(str(e))
     finally:
         if command_config["closeOnSuccess"]:
             self.close()
         else:
             self.show_output(str(output))
Пример #38
0
def get_lib_dirs(pkg, required=True):
    (rtn, out, err) = run_command('pkg-config --libs-only-L ' + pkg)
    if rtn:
        if required:
            raise Exception('Failed to find libraries for package ' + pkg)
        else:
            print 'Failed to find libraries for (optional) package', pkg
            return []
    if err and len(err):
        print 'pkg-config said:', err
    libs = out.split()
    libs = [l for l in libs if len(l)]
    # Strip off the leading "-L"
    libs = [l[2:] for l in libs]
    return libs
Пример #39
0
def get_svn_version():
    from run_command import run_command
    version = {}
    rtn,out,err = run_command('svn info')
    if rtn != 0:
        import sys
        print >>sys.stderr, 'Error getting SVN version: rtn', rtn, '\nOut:', out, '\nErr:', err
    assert(rtn == 0)
    lines = out.split('\n')
    lines = [l for l in lines if len(l)]
    for l in lines:
        words = l.split(':', 1)
        words = [w.strip() for w in words]
        version[words[0]] = words[1]
    return version
Пример #40
0
def diff(result_file, golden_file):
    """Execute diff command with unified form

    Args:
        result_file: result proto file
        golden_file: golden proto file

    Returns:
        output and status code
    """
    command = 'diff -u '
    command += result_file + ' '
    command += golden_file
    status, stdout, stderr = run_command(command)
    return [status, stdout, stderr]
Пример #41
0
def get_lib_dirs(pkg, required=True):
	(rtn,out,err) = run_command('pkg-config --libs-only-L ' + pkg)
	if rtn:
		if required:
			raise Exception('Failed to find libraries for package ' + pkg)
		else:
			print 'Failed to find libraries for (optional) package', pkg
			return []
	if err and len(err):
		print 'pkg-config said:', err
	libs = out.split()
	libs = [l for l in libs if len(l)]
	# Strip off the leading "-L"
	libs = [l[2:] for l in libs]
	return libs
Пример #42
0
def get_svn_version():
    from run_command import run_command
    version = {}
    rtn, out, err = run_command('svn info')
    if rtn != 0:
        import sys
        print >> sys.stderr, 'Error getting SVN version: rtn', rtn, '\nOut:', out, '\nErr:', err
    assert (rtn == 0)
    lines = out.split('\n')
    lines = [l for l in lines if len(l)]
    for l in lines:
        words = l.split(':', 1)
        words = [w.strip() for w in words]
        version[words[0]] = words[1]
    return version
Пример #43
0
def get_libs(pkg, required=True):
	(rtn,out,err) = run_command('pkg-config --libs-only-l ' + pkg)
	if rtn:
		if required:
			raise Exception('Failed to find libraries for package ' + pkg)
		else:
			print 'Failed to find libraries for (optional) package', pkg
			return []
	if err and len(err):
		print 'pkg-config complained:', err
	#print 'pkg-config said:', out
	#libs = out.replace('\n', ' ').split(' ')
	libs = out.split()
	libs = [l for l in libs if len(l)]
	# Strip off the leading "-l"
	libs = [l[2:] for l in libs]
	#print 'returning libs:', libs
	return libs
Пример #44
0
def compile_kernel(ctx,
                   *,
                   boot_device: Path,
                   no_configure_kernel: bool,
                   force: bool,
                   verbose: int,
                   verbose_inf: bool,
                   ):

    if not root_user():
        ic('You must be root.')
        sys.exit(1)

    configure_kernel = not no_configure_kernel

    mount_path_boot = Path('/boot')
    ic(mount_path_boot)
    assert not path_is_mounted(mount_path_boot, verbose=verbose,)

    mount_path_boot_efi = mount_path_boot / Path('efi')
    ic(mount_path_boot_efi)
    assert not path_is_mounted(mount_path_boot_efi, verbose=verbose,)

    assert device_is_not_a_partition(device=boot_device, verbose=verbose,)

    assert path_is_block_special(boot_device)
    assert not block_special_path_is_mounted(boot_device, verbose=verbose,)
    warn((boot_device,), msg="about to update the kernel on device:", verbose=verbose,)

    os.makedirs(mount_path_boot, exist_ok=True)
    boot_partition_path = add_partition_number_to_device(device=boot_device, partition_number="3", verbose=verbose,)
    boot_mount_command = "mount " + boot_partition_path + " " + str(mount_path_boot)
    assert not path_is_mounted(mount_path_boot, verbose=verbose,)
    run_command(boot_mount_command, verbose=True, popen=True)
    assert path_is_mounted(mount_path_boot, verbose=verbose,)

    os.makedirs(mount_path_boot_efi, exist_ok=True)

    efi_partition_path = add_partition_number_to_device(device=boot_device, partition_number="2", verbose=verbose,)
    efi_mount_command = "mount " + efi_partition_path + " " + str(mount_path_boot_efi)
    assert not path_is_mounted(mount_path_boot_efi, verbose=verbose,)
    run_command(efi_mount_command, verbose=True, popen=True)
    assert path_is_mounted(mount_path_boot_efi, verbose=verbose,)

    kcompile(configure=configure_kernel,
             force=force,
             no_check_boot=True,
             verbose=verbose,
            )

    grub_config_command = "grub-mkconfig -o /boot/grub/grub.cfg"
    run_command(grub_config_command, verbose=True, popen=True)
Пример #45
0
def get_libs(pkg, required=True):
    (rtn, out, err) = run_command('pkg-config --libs-only-l ' + pkg)
    if rtn:
        if required:
            raise Exception('Failed to find libraries for package ' + pkg)
        else:
            print 'Failed to find libraries for (optional) package', pkg
            return []
    if err and len(err):
        print 'pkg-config complained:', err
    #print 'pkg-config said:', out
    #libs = out.replace('\n', ' ').split(' ')
    libs = out.split()
    libs = [l for l in libs if len(l)]
    # Strip off the leading "-l"
    libs = [l[2:] for l in libs]
    #print 'returning libs:', libs
    return libs
Пример #46
0
    def is_present(self):
        """
        Is package present

        Returns:
            bool:
            True if installed
            False Otherwise
        """
        cmd = ["brew", "cask", "list"]
        results = run_command(cmd=cmd, logger=self.logger)
        if results.success:
            results = results.results.split("\n")
            if self.package_info.name in results:
                return True
            else:
                return False
        else:
            return False
    def install(self):
        """
        Install a Homebrew CaskLocal package

        Returns:
            bool:

            True if installation occurred.

            False if package already installed or installation failed

        """
        self.ensure_local_cask_repo_present()

        if self.is_present() and self.package_info.force == "false":
            self.logger.info("BrewCaskLocalInstaller.install {0} is already installed".format(self.package_info.name))
            return False
        else:
            local_cask_name, local_cask_dir, local_cask_qname_file, app_name = self.get_cask_info()

            self.logger.info("BrewCaskLocalInstaller.installing {0}".format(self.package_info.name))

            start_dir = os.getcwd()
            os.chdir(local_cask_dir)
            brew_command = "install" if self.package_info.force == "false" else "reinstall"
            cmd = ["brew", "cask", brew_command, local_cask_name]
            results = run_command(cmd=cmd, logger=self.logger)
            os.chdir(start_dir)

            if results.success:
                if self.is_present():
                    status = self.process_receipt_info(app_name)
                    if status:
                        self.logger.info("BrewCaskLocalInstaller.install {0} succeeded".format(self.package_info.name))
                        return True
                    else:
                        self.logger.error("BrewCaskLocalInstaller.install {0} failed".format(self.package_info.name))
                        return False
            else:
                self.logger.error("BrewCaskLocalInstaller.install {0} failed status {1} results {2} errors {3}".format(
                    self.package_info.name, results.status_code, results.results, results.errors))
                return False
Пример #48
0
    def is_present(self):
        """
        Is package present

        Returns:
            bool:

            True if installed

            False Otherwise
            
        """
        cmd = ["mas", "list"]
        results = run_command(cmd=cmd, logger=self.logger)
        if results.success:
            results = results.results.split("\n")
            results = [result.split(" ")[0] for result in results]
            if self.package_info.mas_id in results:
                return True
            else:
                return False
        else:
            return False
Пример #49
0
def get_url_for_overlay(overlay: str,
                        verbose: int,
                        ) -> str:
    command = ["eselect", "repository", "list"]
    command_output = run_command(command, str_output=True, verbose=verbose,)
    command_output = command_output.split('\n')
    if verbose:
        ic(type(command_output))
        ic(command_output)

    for line in command_output[1:]:
        if verbose:
            ic(line)
        try:
            index, repo_name, repo_url = [item for item in line.split() if item]
        except ValueError:
            pass

        repo_url = repo_url.split("(")[-1].split(")")[0]
        if repo_name == overlay:
            return repo_url

    raise ValueError(f'unknown repo {overlay}')
Пример #50
0
def init_git():
    run_command(GIT_INIT)
Пример #51
0
    msg = sys.exc_info()[1]
    print("problem with link : ", msg)
    sys.exit()

#write the command file

o = open('orbit_input', 'w')
o.write(input_file_name + '\n')
o.write('y\n')
o.close()

# run the code
command = pf.get_value('run_command')
input = open('orbit_input')

ret = rc.run_command(command, 'orbit_output', 'orbit_error', stdin=input)

errors = open('orbit_error').readlines()

for l in errors:
    if l.find('Fortran runtime error:') >= 0:
        print(l)
        sys.exit(-1)
    if l.find('No such file or directory') > 0:
        print(l)
        sys.exit(-1)

if ret != 0:
    print('An error occurred while running orbit, check error file!')
    sys.exit(-1)
def join_batman_network(network_name = 'squids_network', 
						ap_mac = '02:12:34:56:78:9A', 
						channel = '1'):
	'''Create a BATMAN network using Raspbian.

	ARGS:
	@network_name		-- The name of the network you would like to create
	@ap_mac				-- The MAC address to assign the Access Point
	@channel			-- The channel number to join (STRING or INT)

	RETURN:
	None
	'''
	import sys
	import time
	sys.path.append('..')
	from batman_setup import load_batman
	from run_command import run_command

	load_batman.load_batman()

	# Configure wlan0 to have a Maximum Transmission Unit to 1532 frames
	# This is standard for BATMAN-Advanced. Most protocols only require
	# 1500 frames, but BATMAN-Advanced uses the spare 32 frames to append
	# its header.
	run_command('sudo ip link set up dev eth0')
	run_command('sudo ip link set mtu 1532 dev wlan0')

	# Configure wlan0 with the specifications given.
	run_command('sudo ifconfig wlan0 down && sudo iwconfig wlan0 mode ad-hoc ' +
				'essid ' + network_name + ' ap ' + ap_mac + ' channel ' + str(channel))

	# Add wlan0 to the list of BATMAN-Advanced available interfaces, then
	# start wlan0 and the corresponding BATMAN-Advanced interface.
	run_command('sudo batctl if add wlan0')
	run_command('sudo ip link set up dev wlan0')
	run_command('sudo ip link set up dev bat0')
	run_command('sudo batctl gw_mode client')
def join_batman_network(password = '******',
			interface = 'wlan2',
			network_name = 'batmesh', 
			ap_mac = '02:12:34:56:78:9A',
			gw_ip = '192.168.2.4', 
			channel = '1'):
	'''Create a BATMAN network using Raspbian.

	ARGS:
	@network_name		-- The name of the network you would like to create
	@ap_mac				-- The MAC address to assign the Access Point
	@channel			-- The channel number to join (STRING or INT)

	RETURN:
	None
	'''
	import time
	from batman_setup import load_batman
	from run_command import run_command

	load_batman.load_batman(password)

	run_command('sudo /etc/init.d/network-manager stop', password)

	# Configure wlan0 to have a Maximum Transmission Unit to 1532 frames
	# This is standard for BATMAN-Advanced. Most protocols only require
	# 1500 frames, but BATMAN-Advanced uses the spare 32 frames to append
	# its header.
	run_command('sudo ifconfig ' + interface + ' mtu 1532', password)

	# Configure wlan0 with the specifications given.
	run_command('sudo ifconfig ' + interface + ' down && ' +
		    'sudo iwconfig ' + interface + ' mode ad-hoc essid ' 
		    + network_name + ' ap ' + ap_mac + ' channel ' + 
 		    str(channel), password)

	# Add wlan0 to the list of BATMAN-Advanced available interfaces, then
	# start wlan0 and the corresponding BATMAN-Advanced interface.
	run_command('sudo batctl if add ' + interface, password)
	run_command('sudo ifconfig ' + interface + ' up', password)
	run_command('sudo ifconfig bat0 up', password)
	run_command('sudo ifconfig bat0 192.168.2.15', password)
	run_command('sudo route add default gw ' + gw_ip, password)
	run_command('sudo batctl gw_mode client', password)

	with open('/etc/resolv.conf', 'rt') as f:
		text = f.read()
		if text.find('nameserver 8.8.8.8') == -1:
			text = text + '\nnameserver 8.8.8.8\n'
		if text.find('nameserver 8.8.4.4') == -1:
			text = text + 'nameserver 8.8.4.4\n'
		with open('/tmp/etc_resolv.tmp', 'wt') as temp:
			temp.write(text)

	run_command('sudo mv /tmp/etc_resolv.tmp /etc/resolv.conf')
def join_batman_network_as_gateway(ssid, ap, channel):
	'''Join the Batman network as a gateway node.

	ARGS:
	@ssid		-- The name of the network to be joined.
	@ap 		-- The MAC address of the access point of the network.
	@ip_range 	-- The IP address range of the network being joined.

	RETURNS:
	None		
	'''
	import sys
	sys.append.path('..')
	from run_command import run_command

	run_command('sudo ip link set mtu 1532 wlan0')
	run_command('sudo ifconfig wlan0 down ' +
	 			'&& sudo iwconfig wlan0 mode ad-hoc essid ' + 
	 			ssid + 
	 			' ap ' +
	 			ap  +
	 			' channel ' + 
	 			str(channel))
	run_command('sudo batctl if add wlan0')
	run_command('sudo ip link set up dev wlan0')
	run_command('sudo ip link add name br-lan type bridge')
	run_command('sudo ip link set dev eth0 master br-lan')
	run_command('sudo ip link set dev bat0 master br-lan')
	run_command('sudo ip link set up dev eth0')
	run_command('sudo ip link set up dev bat0')
	run_command('sudo ip link set up dev br-lan')
	run_command('sudo batctl gw_mode server')
def run_check_format(operation, filename):
    command = check_spelling + " --test-ignore-exts " + operation + " " + filename
    status, stdout, stderr = run_command(command)
    return (command, status, stdout + stderr)
def install_batman_raspbian(path = '/squids_tmp'):
	'''Download BATMAN-Advanced package, unpack it, install it, and load it.

	ARGS:
	@path -- The absolute path of where the BATMAN-Advanced module will be built.
			If the path specified does not exist it will be created.
			Default path is /squids_tmp

	RETURN:
	None
	'''
	import os
	import sys
	sys.path.append('..')
	from download_batman import download_batman
	from load_batman import load_batman
	from run_command import run_command

	# Check if @path does not exist create it then download BATMAN to it
	if not os.path.exists(path):
		os.mkdir(path)
	download_batman(path)

	# Run a chain of linux operations to install BATMAN and its dependencies
	run_command('sudo apt-get update')
	run_command("sudo apt-get install linux-headers-'*'")
	run_command('sudo apt-get install g++ gcc')
	run_command('cd ' + batpath[: -7] + '/; make')
	out, err = run_command('cd ' + batpath[: -7] + '/; uname -r')
	run_command('sudo apt-get install aptitude')
	run_command('sudo aptitude qt4-dev-tools')
	run_command('sudo apt-get install libncurses5-dev libncursesw5-dev')
	run_command('cd /usr/src/linux-headers-' + out + '/; sudo make xconfig; sudo make menuconfig; sudo make oldconfig;')
	
	# Attempt to load BATMAN and print success
	if load_batman():
		print '\033[1;43m' + 'BATMAN-Advanced' + '\033[1;m' + ' was successfully loaded\n'
	else:
		print 'Could not load BATMAN-Advanced\n'
Пример #57
0
 def test_command_that_doesnt_exist(self):
     reason, code, output = run_command(['./herp'])
     self.assertEqual(reason, ERROR)
     self.assertNotEqual(code, 0)