def generate_keys(self): # LOL WTF AM I DOING. THAT -p SWITCH IS COMPLETELY USELESS HERE (exit_code, _, _) = execute("mkdir -p %s" % glob.config.get("paths", "user_ssh_config_dir")) if exit_code != 0: return errors.throw(errors.SERVER_MKDIR_ERROR) # remove any existing Panenthe keys try: os.unlink(glob.config.get("paths", "master_private_key")) except OSError: pass try: os.unlink(glob.config.get("paths", "master_public_key")) except OSError: pass # generate the trusted SSH key (exit_code, _, _) = execute('ssh-keygen -f %s -P ""' % glob.config.get("paths", "master_private_key")) # fail if exit_code != 0: return errors.throw(errors.SERVER_SSH_KEYGEN) # get trusted SSH key file = open(glob.config.get("paths", "master_public_key"), "r") public_key = file.read() file.close() # overwrite SSH key with identifier we can use to delete the key with file = open(glob.config.get("paths", "master_public_key"), "w") file.write(public_key[:-1] + "_panenthe\n") file.close() return errors.throw(errors.ERR_SUCCESS)
def file_sync(self, sync_file): # see if file exists (exit_code,_,_) = self.do_execute("test -e %s" % sync_file) # copy flag copy = True # OST exists, check MD5 if exit_code == 0: # local md5 (exit_code,stdout,_) = execute("md5sum %s" % sync_file) # no file found locally if stdout == []: return errors.throw(errors.SERVER_FILE_NOT_FOUND) local_md5 = stdout[0].strip().split(" ")[0] if exit_code == 0: # remote MD5 (exit_code,stdout,_) = self.do_execute( "md5sum %s" % sync_file ) if exit_code == 0: try: remote_md5 = stdout[0].strip().split(" ")[0] remote_success = True except IndexError: remote_success = False else: remote_success = False # compare if remote_success and local_md5 == remote_md5: copy = False # remove existing template else: self.do_execute("rm -f %s" % sync_file) # copy over OST if copy: self.do_execute("mkdir -p \"%s\"" % os.path.dirname(sync_file)) execute( "scp -i %s -P %d %s root@%s:%s" % ( glob.config.get("paths", "master_private_key"), self.remote_server['port'], sync_file, executer.escape(self.remote_server['ip']), sync_file ) ) return errors.throw(errors.ERR_SUCCESS)
def main() -> None: # dump dump = "/Volumes/homes/Elisa/Drive/Moments" staging_home = "" server_home = "/Volumes" ignore = [] replace = False mode = 'move' staging = {} server = { "HOME": server_home, "image": f"{server_home}/photo", "video": f"{server_home}/video", "audio": f"{server_home}/photo", "archive": f"{server_home}/documents" } arguments = Arguments(dump, staging, server, ignore, replace, mode) # EXPENSIVE OPERATION: List files files = ls_recursive(src_dir=arguments.dump, ignore=arguments.ignore) # Select only video files keep = [ '.3gp', '.mp4', '.MP4', '.mov', '.MOV', '.MPG', '.AVI', '.WAV', '.wav' ] files_to_move = list( pd.Series([f for f in files if os.path.splitext(f)[1] in keep])) # Find extensions of files to keep leave = pd.Series([ os.path.splitext(f)[1] for f in files if os.path.splitext(f)[1] not in keep ]).unique() # describe files (string ops, fast) shallow = filedesc_shallow(files=files_to_move) # grub stats for each file (slower) deep = filedesc_deep(files=files_to_move) # Combine description = pd.merge(shallow, deep, how="outer", on="abspath_src") # Build a migration table table = migration_table(df=description, dirs=arguments.server) print("Plan ready.") # Execute plan execute(df=table, mode=arguments.mode, replace=arguments.replace)
def parse_cmd(provider): cmd = input('> ').strip() state = state_map.get(cmd, None) if state: try: if cmd == 'info': exec_info(provider) else: execute(state, provider) except Ice.Exception as e: print('ICE ERROR: ', e) else: print(f'Incorrect command: {cmd}')
def install(self, changeMgr): for server in self.servers: print "checking if we need to install %s on %s" % (self.name, server) # check if package is installed cmd = "ssh root@%s dpkg -s %s" % (server, self.name) (returnCode, output) = execute(cmd, printOutput=False) # dpkg returns zero if package is installed. non-zero otherwise if returnCode == 0: print "%s is already installed on %s" % (self.name, server) else: changeMgr.registerStateChange("package", self.name, server) print "%s is not installed. installing" % self.name cmd = "ssh root@%s apt-get install -y %s" % (server, self.name) (returnCode, output) = execute(cmd)
def copyArtifact(self, changeMgr): for server in self.servers: if self.isOutOfDate(server): changeMgr.registerStateChange("artifact", self.destination, server) cmd = "scp %s root@%s:%s" % (self.source, server, self.destination) execute(cmd) if self.mode: self.changeMode(server) if self.owner: self.changeOwner(server) else: print "%s is up to date. Skipping copy." % self.destination
def demo(): command = "" while command != "exit": command = input("Klam " + os.getcwd() + ">") try: result = execute(command) print(result) except Exception as e: print(e)
def pipeline(): while (1): fetch() if (debug == "ON"): print("fetch done") if (fetch_file.IR == 0): print("Program Execution Complete") gui.exitProgram() # Function imported from GUI break else: instruction_type = opcode_decoder(fetch_file.IR) if (debug == "ON"): print("decode done") execute(instruction_type) if (debug == "ON"): print("Execute Done") gui.display_update() if (gui.selected.get() == "yes" or gui.mbreak.get() == read_reg(7)): break
def isOutOfDate(self, server): print "checking if %s is out of date on %s" % (self.destination, server) (returnCode, output) = execute("ssh root@%s [ -f %s ]" % (server, self.destination)) if returnCode: # non-zero means file does not exist print "%s does not exist" % self.destination return True localSha = hashlib.sha1(file(self.source, 'r').read()).hexdigest() (returnCode, output) = execute("ssh root@%s sha1sum %s | awk '{ print $1 }'" % (server, self.destination)) remoteSha = output.strip() print "File exists. Comparing shas" print "Local sha: %s" % localSha print "Remote sha: %s" % remoteSha if localSha != remoteSha: return True else: return False
def set_hostname(self): if not self.require("new_hostname"): return errors.throw(errors.BACKEND_INVALID_INPUT) # CentOS specific # change kernel hostname execute('hostname "%s"' % executer.escape(self.new_hostname)) # filter any existing copies of the new hostname in /etc/hosts execute('sed "/[ \t]%s$/d" -i /etc/hosts' % executer.escape(self.new_hostname)) # filter any existing copies of the current hostname in /etc/hosts execute('sed "/[ \t]%s$/d" -i /etc/hosts' % executer.escape(self.hostname)) # add hostname to /etc/hosts execute('echo "127.0.0.1 %s" >> /etc/hosts' % executer.escape(self.new_hostname)) # change /etc/sysconfig/network file execute( 'sed "s/^HOSTNAME=.*$/HOSTNAME=\\"%s\\"/g" ' % executer.escape(self.new_hostname) + "-i /etc/sysconfig/network" ) return errors.throw(errors.ERR_SUCCESS)
def main(): # noinspection PyGlobalUndefined global num, is_interactive if len(sys.argv) is not 2: print('Usage: "tayphoon <filename>" or "tayphoon -i to open interactive mode') exit(1) if sys.argv[1] is '-i': is_interactive = True main() else: f = open_file() line = f.readline() while line is not '': cmd, args = get(line) num += 1 check_args(cmd, args) execute(cmd, args) line = f.readline() pass
def remove_key(self): ret = self.require_remote() if ret: return ret # strip keys from remote server (exit_code, _, _) = execute( "ssh -i %s " % glob.config.get("paths", "master_private_key") + "-p " + str(self.remote_server["port"]) + " root@" + self.remote_server["ip"] + " " + '"sed -r \\"/^.*_panenthe$/d\\" -i %s"' % glob.config.get("paths", "user_ssh_authorized_keys") ) # fail if exit_code != 0: return errors.throw(errors.SERVER_REMOTE_REMOVE) # return return errors.throw(errors.ERR_SUCCESS)
def execute(self): if not os.path.isfile(self.call_path): return errors.throw(errors.API_UNKNOWN_FUNCTION) (self.exit_code, self.stdout_list, self.stderr_list) = \ execute("%s %s -n%s" % ( glob.config.get("paths", "php"), self.call_path, self.cmd_params ) ) # handle errors if self.exit_code != 0: return errors.throw(errors.API_ERR_UNKNOWN) # create plain text variables self.stdout = "\n".join(self.stdout_list) self.stderr = "\n".join(self.stderr_list) # success return errors.throw(errors.ERR_SUCCESS)
import sys from validator import * from execute import * from termcolor import colored if __name__ == "__main__": while 1: query = raw_input(colored("mysql> ", 'green')) if query.upper() == 'Q' or query.upper() == 'QUIT': sys.exit() result, parsed_list = ValidateQuery(query) if result != True and result != 'T': print colored(result, 'red') continue elif result == 'T': #If empty string continue continue #Execute commands, which are syntatically parsed result = execute(parsed_list) if result != True: print colored(result, 'red')
traj_len = 32 n_epochs = 1 #200 batch_size = 1024 #256 n_critic = 10 n_gen = 1 do_train_flag = False if do_train_flag: execute(model_name, state_dim, param_dim, traj_len, labels, colors, noise_dim=noise_dim, n_epochs=n_epochs, batch_size=batch_size, n_critic=n_critic, n_gen=n_gen) else: trained_model = "/final_generator_200_epochs.h5" model_id = "TACAS" evaluate_trained_model(trained_model, model_id, model_name, state_dim, param_dim, traj_len, labels,
This circuit, which we have called `qc_output`, is created by Qiskit using `QuantumCircuit`. The number `n_q` defines the number of qubits in the circuit. With `n_b` we define the number of output bits we will extract from the circuit at the end. The extraction of outputs in a quantum circuit is done using an operation called `measure`. Each measurement tells a specific qubit to give an output to a specific output bit. The following code adds a `measure` operation to each of our eight qubits. The qubits and bits are both labelled by the numbers from 0 to 7 (because that’s how programmers like to do things). The command `qc.measure(j,j)` adds a measurement to our circuit `qc` that tells qubit `j` to write an output to bit `j`. qc_output.draw() for j in range(n): qc_output.measure(j,j) Now that our circuit has something in it, let's take a look at it. qc_output.draw() Qubits are always initialized to give the output ```0```. Since we don't do anything to our qubits in the circuit above, this is exactly the result we'll get when we measure them. We can see this by running the circuit many times and plotting the results in a histogram. We will find that the result is always ```00000000```: a ```0``` from each qubit. counts = execute(qc_output,Aer.get_backend('qasm_simulator')).result().get_counts() plot_histogram(counts) The reason for running many times and showing the result as a histogram is because quantum computers may have some randomness in their results. In this case, since we aren’t doing anything quantum, we get just the ```00000000``` result with certainty. Note that this result comes from a quantum simulator, which is a standard computer calculating what an ideal quantum computer would do. Simulations are only possible for small numbers of qubits (~30 qubits), but they are nevertheless a very useful tool when designing your first quantum circuits. To run on a real device you simply need to replace ```Aer.get_backend('qasm_simulator')``` with the backend object of the device you want to use. ## 4. Example: Creating an Adder Circuit <a id="adder"></a> ### 4.1 Encoding an input <a id="encoding"></a> Now let's look at how to encode a different binary string as an input. For this, we need what is known as a NOT gate. This is the most basic operation that you can do in a computer. It simply flips the bit value: ```0``` becomes ```1``` and ```1``` becomes ```0```. For qubits, it is an operation called ```x``` that does the job of the NOT. Below we create a new circuit dedicated to the job of encoding and call it `qc_encode`. For now, we only specify the number of qubits. qc_encode = QuantumCircuit(n) qc_encode.x(7)
def ost_create(self): ret = super(ovz_core, self).ost_create() if ret: return ret # stop VM (exit_code,_,_) = self.do_execute( "%s stop %d" % ( glob.config.get("paths", "vzctl"), self.real_id ) ) # also must account for not running ret = ovz_exit_codes.translate(exit_code) if exit_code != 0 and ret != errors.OVZ_NOT_RUNNING: return ret # sanitize OST path self.do_execute("mkdir -p \"%s\"" % glob.config.get("paths", "ost_ovz")) # get OST path and private directories ost_path = os.path.join( glob.config.get("paths", "ost_ovz"), executer.escape(self.ost_file) ) ost_private = os.path.join( glob.config.get("paths", "ovz_private"), str(self.real_id) ) # sanity checks self.do_execute( "rm -f \"%s\" \"%s\"" % (ost_path + ".tar", ost_path + ".tar.gz") ) # get list of directories, then tar it (exit_code,_,_) = self.do_execute( "ls -x \"%s\" | /usr/bin/env xargs " % ost_private + "/usr/bin/env tar cf \"%s\" -C \"%s\"" % ( ost_path + ".tar", ost_private ) ) if exit_code != 0: return errors.throw(ERR_TAR_FAILED) # gzip tarred VM (exit_code,_,_) = self.do_execute( "/usr/bin/env gzip \"%s\"" % (ost_path + ".tar") ) if exit_code != 0: return errors.throw(ERR_GZIP_FAILED) # transfer OST over to master node (exit_code,_,_) = execute( "scp -i \"%s\" -P %d \"root@%s:%s\" \"%s\"" % ( glob.config.get("paths", "master_private_key"), self.server['port'], executer.escape(self.server['ip']), ost_path + ".tar.gz", ost_path + ".tar.gz" ) ) if exit_code != 0: return errors.throw(ERR_SCP_FAILED) # update DB (php_exit_code,_,_) = php.db_update( "ost", "insert", self.ost_name, ost_path + ".tar.gz", self.ost_driver_id, self.ost_arch ) if php_exit_code != 0: return php_exit_codes.translate(php_exit_code) # start VM (exit_code,_,_) = self.do_execute( "%s start %d" % ( glob.config.get("paths", "vzctl"), self.real_id ) ) return ovz_exit_codes.translate(exit_code)
def create(self): ret = super(ovz_core, self).create() if ret: return ret # copy OS template if necessary if self.server_is_slave(): # sanitize OST path self.do_execute("mkdir -p %s" % glob.config.get("paths", "ost_ovz") ) # get OST path ost_path = os.path.join( glob.config.get("paths", "ost_ovz"), executer.escape(self.ost) ) # sync OST file server = self.get_server() server.file_sync(ost_path) # OST directory exists (exit_code,_,_) = self.do_execute( "test -e /vz/template/cache" ) # exists, get rid of it if exit_code == 0: # check for OST directory symlink (exit_code,_,_) = self.do_execute( "test -L /vz/template/cache" ) # is a symlink, remove it if exit_code == 0: self.do_execute("rm -f /vz/template/cache") # not a symlink? fix it else: # check if destination exists (exit_code,_,_) = self.do_execute( "test -e /vz/template/__cache" ) # if it does, remove it if exit_code == 0: self.do_execute("rm -rf /vz/template/__cache") # move to new directory self.do_execute( "mv /vz/template/cache /vz/template/__cache" ) # make symlink self.do_execute( "ln -s %s /vz/template/cache" % glob.config.get("paths", "ost_ovz") ) # get ost name ost_name = self.get_ost_name() # delete default config self.do_execute( "rm -f %s" % glob.config.get("paths", "vzconf_default") ) # copy default config over execute( "scp -i %s -P %d %s root@%s:%s" % ( glob.config.get("paths", "master_private_key"), self.server['port'], glob.getfile("shared/etc/ovz_vm_default.conf"), executer.escape(self.server['ip']), glob.config.get("paths", "vzconf_default") ) ) """ # check if disk quotas are enabled (exit_code,stdout,_) = self.do_execute( "/usr/bin/env grep DISK_QUOTA %s" % glob.config.get("paths", "vzconf") ) # disk quotas not set if exit_code != 0: disk_quotas = None else: # disk quotas not set stdout_str = "\n".join(stdout).strip() if stdout_str == "": disk_quotas = None # disk quotas set to yes elif stdout_str.lower().find("yes"): disk_quotas = True # disk quotas set to no else: disk_quotas = False # disable disk quotas for create if enabled if disk_quotas == True: self.do_execute( "/usr/bin/env sed -r " + "\"s/^[ ]*DISK_QUOTA[ ]*=.*$/DISK_QUOTA=no/g\" -i %s" % glob.config.get("paths", "vzconf") ) # make sure disk quotas are disabled if set as default elif disk_quotas == None: self.do_execute("echo \"DISK_QUOTA=no\" >> %s" % glob.config.get("paths", "vzconf") ) # else: it's already disabled... """ # remove directory if it's empty; goes with get_new_real_id() (exit_code,_,_) = self.do_execute("rmdir /vz/private/%d" % self.real_id) # create (exit_code,_,_) = self.do_execute( # prolog anyone? "%s create %d --ostemplate %s --hostname %s" % ( glob.config.get("paths", "vzctl"), self.real_id, executer.escape(ost_name), executer.escape(self.hostname) ) ) """ # re-enable disk quotas if necessary if disk_quotas == True: self.do_execute( "/usr/bin/env sed -r " + "\"s/^[ ]*DISK_QUOTA[ ]*=.*$/DISK_QUOTA=yes/g\" -i %s" % glob.config.get("paths", "vzconf") ) # delete line if it wasn't there before elif disk_quotas == None: self.do_execute("/usr/bin/env sed \"/DISK_QUOTA/d\" -i %s" % glob.config.get("paths", "vzconf") ) """ # fail if exit_code != 0: return ovz_exit_codes.translate(exit_code) # continue setting stuff (exit_code,_,_) = self.do_execute( "%s set %d --save --setmod restart --quotaugidlimit 3000 " % ( glob.config.get("paths", "vzctl"), self.real_id ) + \ "--cpulimit %d --cpus %d " % ( self.cpu_pct, self.cpu_num ) + \ # http://www.linux.com/archive/feature/114214 "--vmguarpages %d --privvmpages %d --diskspace %dK" % ( (self.g_mem*256/1024), (self.b_mem*256/1024), self.disk_space ) ) return ovz_exit_codes.translate(exit_code)
def ost_create(self): ret = super(xen_core, self).ost_create() if ret: return ret # stop VM error_code = self.stop() if error_code != errors.ERR_SUCCESS: return error_code # disk path disk_img_path = self.__get_disk_img_path() # mount loopback file loop_dir = self.__mount_loopback(disk_img_path) if not loop_dir: self.__quit_clean() return errors.throw(errors.XEN_MOUNT_LOOP) # sanitize OST path self.do_execute('mkdir -p "%s"' % glob.config.get("paths", "ost_xen")) # get OST path and private directories ost_path = self.__get_ost_path(self.ost_file) # sanity checks self.do_execute('rm -f "%s" "%s"' % (ost_path + ".tar", ost_path + ".tar.gz")) # get list of directories, then tar it (exit_code, _, _) = self.do_execute( 'ls -1 "%s" | xargs tar cf "%s" -C "%s"' % (loop_dir, ost_path + ".tar", loop_dir) ) if exit_code != 0: self.__quit_clean(loop_dir) return errors.throw(errors.ERR_TAR_FAILED) # gzip tarred VM (exit_code, _, _) = self.do_execute('/usr/bin/env gzip "%s"' % (ost_path + ".tar")) if exit_code != 0: self.__quit_clean(loop_dir) return errors.throw(errors.ERR_GZIP_FAILED) # transfer OST over to master node (exit_code, _, _) = execute( 'scp -i "%s" -P %d "root@%s:%s" "%s"' % ( glob.config.get("paths", "master_private_key"), self.server["port"], executer.escape(self.server["ip"]), ost_path + ".tar.gz", ost_path + ".tar.gz", ) ) if exit_code != 0: self.__quit_clean(loop_dir) return errors.throw(errors.ERR_SCP_FAILED) # update DB (php_exit_code, _, _) = php.db_update( "ost", "insert", self.ost_name, ost_path + ".tar.gz", self.ost_driver_id, self.ost_arch ) if php_exit_code != 0: self.__quit_clean(loop_dir) return php_exit_codes.translate(php_exit_code) # clean up self.__quit_clean(loop_dir) # start it back up exit_status = self.start() # ignore start errors return errors.throw(errors.ERR_SUCCESS)
def uninstall(self, changeMgr): for server in self.servers: changeMgr.registerStateChange("package", self.name, server) print "uninstalling %s on %s" % (self.name, server) cmd = "ssh root@%s apt-get remove -y --purge %s" % (server, self.name) execute(cmd)
def create(self): ret = super(xen_core, self).create() if ret: return ret # required to know what kernel to boot to if not self.require("kernel"): return errors.throw(errors.BACKEND_INVALID_INPUT) # get relevant paths config_path = self.__get_config_path() disk_img_path = self.__get_disk_img_path() ost_path = self.__get_ost_path() swap_img_path = self.__get_swap_img_path() vm_directory = self.__get_vm_directory() # make sure path exists self.do_execute('mkdir -p "%s"' % vm_directory) # config {{{ # kernel setup {{{ config_data = "# Kernel Setup\n" if self.os_type == "WINDOWS" or self.os_type == "OTHER": config_data += ( 'kernel = "/usr/lib/xen/boot/hvmloader"\n' + 'builder = "hvm"\n' + 'device_model = "/usr/lib/xen/bin/qemu-dm"\n' ) else: config_data += 'kernel = "/boot/%s"\n' % executer.escape(self.kernel) config_data += "\n" # }}} # memory {{{ # same for both memory = self.g_mem / 1024 config_data += "# Memory\n" + 'memory = "%s"\n' % memory + "\n" # }}} # disk {{{ config_data += "# Disk\n" if self.os_type == "WINDOWS" or self.os_type == "OTHER": config_data += ( "disk = [\n" + '"file:%s,ieomu:hda,w",\n' % disk_img_path + '"file:%s,hdc:cdrom,r",\n' % ost_path + "]\n\n" ) # "\"file:windows,ioemu,hdc:cdrom,r\"\n" + \ else: config_data += "disk = [\n" + '"file:%s,sda1,w",\n' % disk_img_path # add swap if necessary if self.swap_space != 0: config_data += '"file:%s,sda2,w"\n' % swap_img_path config_data += "]\n\n" # }}} # name and hostname {{{ config_data += ( "# container name\n" + 'name = "%d"\n' % self.real_id + 'hostname = "%s"\n' % self.hostname + "\n" ) # }}} # networking {{{ config_data += "# Networking\n" + 'vif = ["type=ieomu, bridge=xenbr0"]\n' + "\n" # }}} # VNC {{{ config_data += "# VNC\n" if self.os_type == "WINDOWS" or self.os_type == "OTHER": config_data += ( "vnc = 1\n" + "vncdisplay=1\n" + 'vnclisten="0.0.0.0"\n' + 'vncpasswd="%d"\n' % self.real_id + "\n" ) else: config_data += ( 'vfb = ["type=vnc,' + "vncdisplay=18," + "vnclisten=0.0.0.0," + "vncpasswd=%d" % self.real_id + '"]\n\n' ) # TODO: self.vncpasswd not self.real_id # TODO: vncdisplay not 1 # "vncdisplay = 1\n" % self.real_id + \ # TODO # }}} # behavior settings {{{ config_data += "# Behavior Settings\n" if self.os_type == "WINDOWS" or self.os_type == "OTHER": config_data += 'boot = "d"\n' + "sdl = 0\n" else: config_data += 'root = "/dev/sda1"\n' + 'extra = "fastboot"\n' config_data += "\n" # }}} # event settings {{{ config_data += ( "# Event Settings\n" + "on_poweroff = 'destroy'\n" + "on_reboot = 'restart'\n" + "on_crash = 'restart'\n" + "\n" ) # write config to temp file config_fd = tempfile.mkstemp(prefix="panenthe") config_fp = open(config_fd[1], "w") config_fp.write(config_data) config_fp.close() # copy config over execute( "scp -i %s -P %d %s root@%s:%s" % ( glob.config.get("paths", "master_private_key"), self.server["port"], config_fd[1], executer.escape(self.server["ip"]), config_path, ) ) # remove temp file os.unlink(config_fd[1]) # }}} # create null disk image (exit_code, _, _) = self.do_execute( 'dd if=/dev/zero of="%s" bs=%d count=0 seek=1024' % (disk_img_path, self.disk_space) ) if exit_code != 0: return errors.throw(errors.XEN_DISK_CREATION) # sync server OST file server = self.get_server() server.file_sync(ost_path) # linux only disk finalization if self.os_type == "LINUX": # make disk filesystem (exit_code, _, _) = self.do_execute('mkfs.ext3 -F "%s"' % disk_img_path) if exit_code != 0: return errors.throw(errors.XEN_DISK_CREATION) # only make swap if not zero if self.swap_space != 0: # create null swap image (exit_code, _, _) = self.do_execute( 'dd if=/dev/zero of="%s" bs=%d count=0 seek=1024' % (swap_img_path, self.swap_space) ) if exit_code != 0: return errors.throw(errors.XEN_SWAP_CREATION) # make swap (exit_code, _, _) = self.do_execute('mkswap "%s"' % swap_img_path) if exit_code != 0: return errors.throw(errors.XEN_SWAP_CREATION) # mount loopback device loop_dir = self.__mount_loopback(disk_img_path) if not loop_dir: self.__quit_clean() return errors.throw(errors.XEN_MOUNT_LOOP) # extract OST (exit_code, _, _) = self.do_execute('tar xzf "%s" -C "%s"' % (ost_path, loop_dir)) if exit_code != 0: self.__quit_clean(loop_dir) return errors.throw(errors.XEN_DISK_FINALIZATION) # enter swap into the fstab (exit_code, _, _) = self.do_execute( 'echo "/dev/sda2 none swap defaults 0 0" >> %s' % os.path.join(loop_dir, "etc", "fstab") ) if exit_code != 0: self.__quit_clean(loop_dir) return errors.throw(errors.XEN_DISK_FINALIZATION) # get distro self.get_distro(loop_dir) # if debian, reset the IP config file if self.distro == "debian": self.__debian_net_reset(loop_dir) # if redhat, remove any extraneous network config files # SEE FOOTNOTE 1 elif self.distro == "redhat": (exit_code, _, _) = self.do_execute( 'rm -f "%s"*' % os.path.join(loop_dir, glob.config.get("paths", "network_redhat_dir")[1:], "ifcfg-eth") ) if exit_code != 0: self.__quit_clean(loop_dir) return errors.throw(errors.XEN_DISK_FINALIZATION) # clean up self.__quit_clean() return errors.throw(errors.ERR_SUCCESS)
def main(): root = Tk() screen = Canvas(root, width=500, height=600, bg="#468A53") screen.pack() drawGrid(screen) board = [['#', '#', '#', '#', '#', '#', '#', '#', '#', '#'], ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'], ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'], ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'], ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'], ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'], ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'], ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'], ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'], ['#', '#', '#', '#', '#', '#', '#', '#', '#', '#']] board[4][4] = 'x' board[4][5] = 'o' board[5][4] = 'o' board[5][5] = 'x' arrayLegalMovesX = [(5, 3), (6, 4), (3, 5), (4, 6)] arrayLegalMovesO = [(4, 3), (3, 4), (6, 5), (5, 6)] gameEnd = False playTurn = 'o' print("Siapakah yang akan bermain sebagai hitam?") print("[1] Player") print("[2] Random Bot") print("[3] Minimax Bot") playerO = input("> ") print("Siapakah yang akan bermain sebagai putih?") print("[1] Player") print("[2] Random Bot") print("[3] Minimax Bot") playerX = input("> ") depthO = 1 depthX = 1 if (playerO == '3'): print("Tingkat Kesulitan bot hitam? [1-6, 6 paling sulit]") depthO = int(input("")) if (playerX == '3'): print("Tingkat Kesulitan bot putih? [1-6, 6 paling sulit]") depthX = int(input("")) print( "GAME BEGINS! Input your command by using 'row,column' of the grid you want to play" ) # For checking purpose only. Delete if the project is finished. print('arrayLegalMovesO : ', arrayLegalMovesO) print('arrayLegalMovesX : ', arrayLegalMovesX) showBoard(board) drawBoard(board, screen) # showScore(board) while not gameEnd: # showBoard(board) # showScore(board) if (playTurn == 'o'): if (arrayLegalMovesO): koordinat = execute(playerO, board, arrayLegalMovesO, arrayLegalMovesX, playTurn, depthO) jalan(board, koordinat, playTurn, arrayLegalMovesO, arrayLegalMovesX) updateArrayLegalMove(board, arrayLegalMovesO, arrayLegalMovesX) else: print( "Sorry my friend, there is no legal move for you this turn" ) elif (playTurn == 'x'): if (arrayLegalMovesX): koordinat = execute(playerX, board, arrayLegalMovesO, arrayLegalMovesX, playTurn, depthX) jalan(board, koordinat, playTurn, arrayLegalMovesO, arrayLegalMovesX) updateArrayLegalMove(board, arrayLegalMovesO, arrayLegalMovesX) else: print( "Sorry my friend, there is no legal move for you this turn" ) gameEnd = cekGameEnd(arrayLegalMovesO, arrayLegalMovesX) print("eval state " + playTurn + " = " + str( evalState(playTurn, board, arrayLegalMovesO, arrayLegalMovesX))) playTurn = switchPlay(playTurn) # For checking purpose only. Delete if the project is finished. print('arrayLegalMovesO : ', arrayLegalMovesO) print('arrayLegalMovesX : ', arrayLegalMovesX) showBoard(board) # showScore(board) root.update() drawBoard(board, screen) drawScoreBoard(board, screen) # showWin() root.mainloop()
def changeMode(self, server): print "changing mode" cmd = "ssh root@%s chmod %s %s" % (server, self.mode, self.destination) execute(cmd)
def main() -> None: mode_help = "Mode help." # Get the description from the docstring of the function parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, usage=USAGE) # Set values of default arguments parser.set_defaults(dump="", staging=str(data / "staging"), server=str(data / "server"), ignore=['.jsonl', '.json', '.aae'], replace=False, mode="copy") parser.add_argument('-d', '--dump', type=str, required=False, help=mode_help) parser.add_argument('--staging', type=str, required=False, help=mode_help) parser.add_argument('--server', type=str, required=False, help=mode_help) parser.add_argument('-i', '--ignore', type=list, required=False, help=mode_help) parser.add_argument('-r', '--replace', type=bool, required=False, help=mode_help) parser.add_argument('-m', '--mode', type=str, required=False, help=mode_help) # Parse parameters cli_args = parser.parse_args() # Instantiate default args object args = Arguments(cli_args.dump, staging_paths(cli_args.staging), server_paths(cli_args.server), cli_args.ignore, cli_args.replace, cli_args.mode) print(args) # Get user input stage_opts = ["y", "n"] stage_question = ( f"\nDo you want to stage files? {'/'.join(stage_opts)}: ") stage_answer = cli_ask_question(question=stage_question, options=stage_opts) if stage_answer == "y": validate_staging(args) # Prepare migration from dump plan_staging = plan(source=args.dump, destinations=args.staging, ignore=args.ignore) # Execute migration execute(df=plan_staging, mode=args.mode, replace=args.replace) # Prepare migration to server from staging plan_server = plan(source=args.staging["HOME"], destinations=args.server, ignore=args.ignore) else: # Prepare direct migration to server plan_server = plan(source=args.dump, destinations=args.server, ignore=args.ignore) # Confirm load job load_options = ["y", "n"] load_question = ( f"\nReady to load data to the server? {'/'.join(load_options)}: ") load_answer = cli_ask_question(question=load_question, options=load_options) if load_answer == "y": # Execute migration execute(df=plan_server, mode=args.mode, replace=args.replace) else: print(f"\nAll files are ready to load in staging. Abortng.") return if stage_answer == "y": # Cleanup optionally_clean_dir(args.staging["HOME"])
def install_key(self): ret = self.require_remote() if ret: return ret # also require password if not self.require_dict(self.remote_server, "password"): return errors.throw(errors.BACKEND_INVALID_INPUT) # open config file and get the current contents try: file = open(glob.config.get("paths", "user_ssh_config"), "r") ssh_config = file.read() file.close() # no such file so just create it blank later except IOError: ssh_config = "" # define the server since ssh-copy-id doesn't have a port switch file = open(glob.config.get("paths", "user_ssh_config"), "a") file.write( "\n" + "Host panenthe_" + self.remote_server["ip"] + "\n" + "Hostname " + self.remote_server["ip"] + "\n" + "User root\n" + "Port " + str(self.remote_server["port"]) + "\n" ) file.close() execute( 'sed -r "/_' + self.remote_server["ip"] + '$/d" ' + "-i %s" % glob.config.get("paths", "user_ssh_known_hosts") ) # sanity check # grab the key for the remote host (exit_code, _, _) = execute( "ssh-keyscan -t rsa,dsa -p " + str(self.remote_server["port"]) + " " + self.remote_server["ip"] + " >> %s" % glob.config.get("paths", "user_ssh_known_hosts") ) if exit_code != 0: self.die_reconfig(ssh_config) return errors.throw(errors.SERVER_REMOTE_KEYSCAN) # send the key to the server (exit_code, stdout, _) = execute( 'expect -c "log_user 0\n' + "spawn ssh-copy-id -i %s panenthe_" % glob.config.get("paths", "master_public_key") + self.remote_server["ip"] + "\n" + "expect {\n" + ' \\"password: \\" {\n' + ' send \\"' + self.remote_server["password"] + '\\r\\"\n' + " expect {\n" + ' \\"Permission denied\\" {\n' + ' expect \\"password: \\"\n' + ' send \\"\\r\\"\n' + ' expect \\"password: \\"\n' + ' send \\"\\r\\"\n' + " expect eof\n" + ' send_user \\"INVALID_PASSWORD\\"\n' + " exit\n" + " }\n" + " eof {\n" + " send_user SUCCESS\n" + " exit\n" + " }\n" + " }\n" + " }\n" + "\n" + " ERROR {\n" + " send_user PRIVATE_KEY_NOT_FOUND\n" + " exit\n" + " }\n" + "\n" + ' \\"No route to host\\" {\n' + " send_user NO_ROUTE_TO_HOST\n" + " exit\n" + " }\n" + "\n" + ' \\"Could not resolve \\" {\n' + " send_user COULD_NOT_RESOLVE\n" + " exit\n" + " }\n" + "\n" + " eof {\n" + " send_user KEY_ALREADY_INSTALLED\n" + " exit\n" + " }\n" + "}\n" + '"' ) # reconfigure user_ssh_config self.die_reconfig(ssh_config) # expect's error code if exit_code != 0: return errors.throw(errors.SERVER_REMOTE_KEYCOPY) # invalid password if stdout[0] == "INVALID_PASSWORD": return errors.throw(errors.SERVER_INVALID_PASSWORD) # no key found elif stdout[0] == "PRIVATE_KEY_NOT_FOUND": return errors.throw(errors.SERVER_PRIVATE_KEY_NOT_FOUND) # no route to host elif stdout[0] == "NO_ROUTE_TO_HOST": return errors.throw(errors.SERVER_NO_ROUTE_TO_HOST) # could not resolve elif stdout[0] == "COULD_NOT_RESOLVE": return errors.throw(errors.SERVER_COULD_NOT_RESOLVE) # key already installed elif stdout[0] == "KEY_ALREADY_INSTALLED": return errors.throw(errors.SERVER_KEY_ALREADY_INSTALLED) # success! elif stdout[0] == "SUCCESS": return errors.throw(errors.ERR_SUCCESS) # unknown error return errors.throw(errors.SERVER_ERR_UNKNOWN)
def do_execute(self, cmd): return execute(cmd)