Chamistad
Chamistad

Reputation: 13

terminating a ssh connection created by Python pexpect spawn

I have created a SSH tunnel using the python pexpect.spawn() command. I would like to close or terminate this ssh connection post my processing. I have tried giving the <sshtunnel>.close() / <sshtunnel>.kill() / <sshtunnel>.terminate() command. Even though, on giving the <sshtunnel>.isalive() method I get a value False meaning the child process has been closed, I still see the ssh tunnel process running on my linux ubuntu machine.

Any inputs on how to get this ssh tunnel process terminated ? Here is the brief code snippet.

    username="username"
    passwd="password"
    try:
        child=pexpect.spawn("ssh -C2qTnNf -D XXXX [email protected]")
        i=child.expect('password:')
        print(i)
        if i==0:
            print(passwd)
            time.sleep (0.5)
            child.sendline(passwd)
            child.expect('$')
            time.sleep(2) 
            print(child)
            print(child.isalive())
            print('####')
            child.close(force=True)
           #child.terminate(force=True)
            time.sleep(5)
            print(child.isalive())
            print(child)
    except Exception as e:
        print(str(e))

Upvotes: 1

Views: 1528

Answers (1)

pynexj
pynexj

Reputation: 20768

ssh -f would fork a child ssh process running in background (like a daemon) and the parent process would exit immediately.

For pexpect.spawn('ssh -f ...'), pexpect can only interact with the parent ssh process so it cannot stop the background tunnel ssh process.

To kill the tunnel ssh process you need to find its PID and do something like os.system('kill ...') or os.kill(pid, sig).

Upvotes: 1

Related Questions