pexpect not executing command by steps
Question: I have this Python3 code which use Pexpect.

    
    
    import pexpect
    import getpass
    import sys
    
    def ssh(username,password,host,port,command,writeline):
        child = pexpect.spawn("ssh -p {} {}@{} '{}'".format(port,username,host,command))
        child.expect("password: ")
        child.sendline(password)
        if(writeline):
            print(child.read())
    
    def scp(username,password,host,port,file,dest):
        child = pexpect.spawn("scp -P {} {} {}@{}:{}".format(port,file,username,host,dest))
        child.expect("password: ")
        child.sendline(password)
    
    try:
        filename = sys.argv[1]
        print("=== sendhw remote commander ===")
        username = input("Username: ")
        password = getpass.getpass("Password: ")
        ssh(username,password,"some.host.net","22","mkdir ~/srakrnSRV",False)
        scp(username,password,"some.host.net","22",filename,"~/srakrnSRV")
        ssh(username,password,"some.host.net","22","cd srakrnSRV && sendhw {}".format(filename),True)
    
    except IndexError:
        print("No homework name specified.")
    

My aim is to:

  * SSH into the host with the `ssh` function, create the directory `srakrnSRV`, then
  * upload a file into the `srakrnSRV` directory, which is previously created
  * `cd` into `srakrnSRV`, and execute the `sendhw <filename>` command. The `filename` variable is defined by command line parameteres, and print the result out.

After running the entire code, Python prints out

    
    
    b'\r\nbash: line 0: cd: srakrnSRV: No such file or directory\r\n'
    

which is not expected, as the directory should be previously created.

Also, I tried manually creating the `srakrnSRV` folder in my remote host.
After running the command again, it appears that `scp` function is also not
running. The only runnning pexpect coomand was the last `ssh` function.

How to make it execute in order? Thanks in advance!


Answer: You may lack permission for executing commands through ssh. Also there is
possibility that your program sends scp before prompt occurs.

