1

I'm beginner to python and I would like to start with automation. Below is the task I'm trying to do.

ssh -p 2024 [email protected]

[email protected]'s password:

I try to ssh to a particular machine and its prompting for password. But I have no clue how to give the input to this console. I have tried this

import sys

import subprocess

con = subprocess.Popen("ssh -p 2024 [email protected]", shell=True,stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr =subprocess.PIPE)

print con.stdout.readlines()

If I execute this, output will be like

python auto.py

[email protected]'s password:

But I have no clue how to give the input to this. If some could help me out in this, would be much grateful. Also could you please help me after logging in, how to execute the commands on the remote machine via ssh.

Would proceed with my automation if this is done

I tried with con.communicate() since stdin is in PIPE mode. But no luck.

If this cant be accomplished by subprocess, could you please suggest me alternate way to execute commands on remote console(some other module) useful for automation ? since most of my automation depends on executin commands on remote console

Thanks

2
  • see Fabric module Commented Dec 1, 2016 at 15:28
  • See ssh-agent! Don't try to pass paswords by a script!! Commented Dec 1, 2016 at 15:54

2 Answers 2

2

I have implemented through pexpect. You may need to pip install pexpect before you run the code:

import pexpect
from pexpect import pxssh

accessDenied = None
unreachable = None
username = 'someuser'
ipaddress = 'mymachine'
password = 'somepassword'
command = 'ls -al'
try:
    ssh = pexpect.spawn('ssh %s@%s' % (username, ipaddress))
    ret = ssh.expect([pexpect.TIMEOUT, '.*sure.*connect.*\(yes/no\)\?', '[P|p]assword:'])
    if ret == 0:
        unreachable = True

    elif ret == 1:  #Case asking for storing key
        ssh.sendline('yes')
        ret = ssh.expect([pexpect.TIMEOUT, '[P|p]assword:'])
        if ret == 0:
            accessDenied = True
        elif ret == 1:
            ssh.sendline(password)
            auth = ssh.expect(['[P|p]assword:', '#'])   #Match for the prompt
    elif ret == 2:  #Case asking for password
        ssh.sendline(password)
        auth = ssh.expect(['[P|p]assword:', '#'])       #Match for the prompt

    if not auth == 1:
        accessDenied = True
    else:
        (command_output, exitstatus) = pexpect.run("ssh %s@%s '%s'" % (username, ipaddress, command), events={'(?i)password':'%s\n' % password}, withexitstatus=1, timeout=1000)
    print(command_output)
except pxssh.ExceptionPxssh as e:
    print(e)
    accessDenied = 'Access denied'

if accessDenied:
    print('Could not connect to the machine')
elif unreachable:
    print('System unreachable')

This works only on Linux as pexpect is available only for Linux. You may use plink.exe if you need to run on Windows. paramiko is another module you may try, with which I had few issues before.

Sign up to request clarification or add additional context in comments.

Comments

0

I have implemented through paramiko. You may need to pip install paramiko before you run the code:

import paramiko
username = 'root'
password = 'calvin'
host = '192.168.0.1'

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=str(username), password=str(password))
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
chan = ssh.invoke_shell()
time.sleep(1)
print("Cnnection Successfully")

If you want to pass command and grab the output, Simply perform the following steps:

chan.send('Your Command')
if chan is not None and chan.recv_ready():
   resp = chan.recv(2048)
   while (chan.recv_ready()):
      resp += chan.recv(2048)
output = str(resp, 'utf-8')
print(output)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.