Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

Hello, all. I'm totally new to python.

Have a look at the below code, which will connect to host and executes one command

ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect(host, username=user, password=pw)

print 'running remote command'

stdin, stdout, stderr = ssh.exec_command(command)

stdin.close()

for line in stdout.read().splitlines():

    print '%s$: %s' % (host, line)

    if outfile != None:

        f_outfile.write("%s\n" %line)

for line in stderr.read().splitlines():

    print '%s$: %s' % (host, line + "\n")

    if outfile != None:

        f_outfile.write("%s\n" %line)

ssh.close()

if outfile != None:

    f_outfile.close()

print 'connection to %s closed' %host

except:

   e = sys.exc_info()[1]

   print '%s' %e

works fine when then remote command needn't bother with a tty. I found an invoke_shell model Nested SSH meeting with Paramiko. I'm not at all happy with this arrangement, since, in such a case that a server has a brief that isn't indicated in my script - > endless loop or a predefined prompt in the content is a string in the return text - > not all information will be gotten. Is there any better solution perhaps where stdout and stderr are sent back like in my content?

1 Answer

0 votes
by (26.4k points)
edited by

To run the commands on a password protected client, I try to use this below method:

import paramiko

nbytes = 4096

hostname = 'hostname'

port = 22

username = 'username' 

password = 'password'

command = 'ls'

client = paramiko.Transport((hostname, port))

client.connect(username=username, password=password)

stdout_data = []

stderr_data = []

session = client.open_channel(kind='session')

session.exec_command(command)

while True:

    if session.recv_ready():

        stdout_data.append(session.recv(nbytes))

    if session.recv_stderr_ready():

        stderr_data.append(session.recv_stderr(nbytes))

    if session.exit_status_ready():

        break

print 'exit status: ', session.recv_exit_status()

print ''.join(stdout_data)

print ''.join(stderr_data)

session.close()

client.close()

Want to learn the concepts of python? Join the python training course fast!

Related questions

0 votes
2 answers
asked Oct 4, 2019 in Python by Tech4ever (20.3k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...