bprat3
bprat3

Reputation: 23

Getting Error while using pexpect: TypeError: 'spawn' object is not subscriptable

I am trying to write a python code with pexpect, to login into multiple servers and run commands such as "ls".

below is my code:

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


ssh = get_credential()
print(ssh)
password = ssh[1]
print(password)

server = ["server1", "server2"]

for host in server:
    print(host.strip())
    ssh_command = f"ssh {ssh[0]}@{host.strip()}"
    print(ssh_command)
    ssh = pexpect.spawn(ssh_command, timeout=5)
    ssh.expect('Password:')
    #        password = str(ssh[1])
    ssh.sendline('{}'.format(password))
    ssh.expect(r'\$')
    ssh.sendline('ls')  # run a command
    print(f"output from {host}:")
    print(ssh.before.decode())
    ssh.expect(r'\$')
    ssh.logfile = sys.stdout
    print(ssh.before.decode())
    ssh.close()

password = ssh[1]
print(password)

Getting error for server2, server1 gives result fine.

Error:

 ssh_command = f"ssh {ssh[0]}@{host.strip()}"
TypeError: 'spawn' object is not subscriptable

Not sure why server2 in for loop is not being considered.

Upvotes: 1

Views: 32

Answers (0)

Related Questions