Search code examples
pythonfunctionif-statementpython-3.4pexpect

Issue with python 3.0 pexpect module


Here is the piece of base code which I wrote to do an automatic ssh to the linux, but every time it is getting into cases==0, which means it's thinking every time it's a "newkey"/ (yes/no):

Please help me solving it. I am stuck at the basic level.

#!/home/python/Python-3.4.3/python

import subprocess;
import pexpect;


def f1_input():
        global server, id, password, commands;
        server = input("Enter Server: ");
        id = input("Enter User ID: ");
        password = input("Enter Password: ");
        commands = input("Enter Commands: ");
        return server, id, password, commands;


def f2_exec():
        child = pexpect.spawn('ssh %s@%s %s'%(id,server,commands));
        newkey = 'Are you sure you want to continue connecting (yes/no)? ';
        passkey = 'password:';
        cases = child.expect([newkey, passkey, pexpect.EOF]);
        print("cases=", cases);

        if cases==0:
                print("cases=", cases);
                child.sendline('yes');
                child.expect('password:');
                child.sendline(password);
                child.expect(pexpect.EOF);
                print(child.before);

        elif cases==1:
                print("cases=", cases);
                child.sendline(password);
                child.expect(pexpect.EOF);
                print(child.before);

        elif cases==2:
                print("cases=", cases);
                print("Timeout!!!");

        else:
                print("cases=", cases);
                print("EXIT");

f1_input();
f2_exec();

Solution

  • your problem is with ssh, and should reproduce without pexpect. It may not be able to write to ~/.ssh/known_hosts file, or option StrictHostKeyChecking=no in ~/.ssh/config or similar.

    Furthermore, your solution is better resolved with a program such as sshpass(1) or a python module like paramiko.