Automating processes with python

I am trying to write a python script that starts a process and does some operations. The commands I want to automate with a script are outlined in red in the image. The problem is that after the first command is executed, the qemu environment will start, and the rest of the commands must be executed in the qemu environment. So I want to know how can I execute these commands with a script in python? Because as I know I can do the first command, but I don’t know how I can execute those commands when I am going to qemu environment.

enter image description here

Could you please help me how can I do this process?

+3


source to share


2 answers


The first thing that came to my mind was pexpect , a quick google search came up on this blog auto-testing-vms-using-pexpect-and-qemu which seems to pretty much match what you are doing:

import pexpect

image = "fedora-20.img"
user = "root"
password = "changeme"

# Define the qemu cmd to run
# The important bit is to redirect the serial to stdio
cmd = "qemu-kvm"
cmd += " -m 1024 -serial stdio -net user -net nic"
cmd += " -snapshot -hda %s" % image
cmd += " -watchdog-action poweroff"

# Spawn the qemu process and log to stdout
child = pexpect.spawn(cmd)
child.logfile = sys.stdout

# Now wait for the login
child.expect('(?i)login:')

# And login with the credentials from above
child.sendline(user)
child.expect('(?i)password:')
child.sendline(password)
child.expect('# ')

# Now shutdown the machine and end the process
if child.isalive():
    child.sendline('init 0')
    child.close()

if child.isalive():
    print('Child did not exit gracefully.')
else:
    print('Child exited gracefully.')

      

You can also do this with by subprocess.Popen

checking stdout for lines (qemu)

and writing to stdin. Something like this:



from subprocess import Popen,PIPE

# pass initial command as list of individual args
p = Popen(["./tracecap/temu","-monitor",.....],stdout=PIPE, stdin=PIPE)
# store all the next arguments to pass
args = iter([arg1,arg2,arg3])
# iterate over stdout so we can check where we are
for line in iter(p.stdout.readline,""):
    # if (qemu) is at the prompt, enter a command
    if line.startswith("(qemu)"):
        arg = next(args,"") 
        # if we have used all args break
        if not arg:
            break
        # else we write the arg with a newline
        p.stdin.write(arg+"\n")
    print(line)# just use to see the output

      

Where args

contains all of the following commands.

+1


source


Don't forget Python has batteries. Take a look at the Suprocess module in the lib standard library. There are many errors in the process management and the module takes care of all of them.



You probably want to start a qemu process and send the following commands, writing it to the standard input (stdin). The Subprocess module allows you to do this. See qemu has command line options to connect to stdi:-chardev stdio ,id=id

+1


source







All Articles