bprat3
bprat3

Reputation: 23

Getting error with "pexpect.TIMEOUT" , while performing ssh with "pexpect.spawn" on multiple servers

I am trying to write a simple script, which ssh to individual servers switch user if required and execute command. However i am not able to make it work even after lot of try.

Any help will be really appreciated with what mistakes i am making in my code.

import pexpect
import os
import subprocess
import getpass
import pexpect
import sys

def get_credential():
    """Prompt user for ADS username and password"""
    username = getpass.getuser()
    print("[#] Connecting ADSuser as: [{}] ".format(username))
    password = getpass.getpass(" Enter ADS Password: ")
    return username, password


def host_list(filepath="hosts.txt"):
    with open(filepath, "r") as file_local:
        hosts = file_local.readlines()
        if not hosts:
            print("[#] No hosts found in file: [{}]".format(filepath))
            print("[#] Would you like to add hosts to file: [{}]".format(filepath))
            response = input("Enter [y/n]: ")
            if response.lower() == "y":
                host_list_wrights(filepath)
            else:
                print("[#] Exiting...")
                exit(0)
        else:
            print("[#] Hosts found in file: [{}]".format(filepath))
            for host in hosts:
                print(host.strip())
    return hosts



def host_list_wrights(filepath="hosts.txt"):
    """Wright host.txt file with list of hosts"""
    with open(filepath, "w") as file_local:
        while True:
            host = input("Enter host name : ")
            if host:
                file_local.write(host + "\n")
            else:
                break
def switch_to_user():
        if input("Do you want to switch to a different user other than your ADSID ? [y/n]: ") == "y":
            privlaged_user = input("Enter user to switch to: ")
            return privlaged_user
        else:
            return None

def command_to_run():
    command = input("Enter command to run on the server: ")
    return command

def excute_command_on_host(host, username, password, new_user,  command):
    try:
        ssh = pexpect.spawn('ssh {}@{}'.format(username, host.strip()), timeout=10)
        ssh.expect('password:')
        ssh.sendline(password)
        ssh.expect(r'\$')
        if new_user:
            ssh.sendline('pbrun /bin/su - {}'.format(new_user))
            ssh.expect('Password:')
            ssh.sendline(password)
            ssh.expect(r'\$')
        ssh.sendline(command)
        ssh.expect(r'\$')
        print(ssh.before.decode())
    except pexpect.EOF:
        print("[#] EOF Received : Connection to host: [{}] failed".format(host.strip()))
    except pexpect.TIMEOUT:
        print("[#] Timeout Received : Connection to host: [{}] failed".format(host.strip()))
    finally:
        ssh.close()


if __name__ == "__main__":
    ssh_host = host_list()
    ssh = get_credential()
    password = ssh[1]
    username = ssh[0]
    command = command_to_run()
    new_user = switch_to_user()
    print("new user :", new_user)
    for host in ssh_host:
        print("Connecting to host: {}".format(host.strip()))
        print("Username: {}".format(username))
        print("Password: {}".format(password))
        excute_command_on_host(host, username, password, new_user, command)
    exit()

NOTE: hosts.txt will have multiple server

Trying to ssh to all servers mentioned in "hosts.txt" and based on input, will switch user and execute the command or will not switch to user (i.e with adsid only) will execute the command.

Upvotes: 1

Views: 21

Answers (0)

Related Questions