0

How can I run commands on the remote server to which I login to, using pexpect and store the result in the form of a string into a variable?

I made a connection to the server in the following way:

COMMAND_PROMPT = '[#$] '
TERMINAL_PROMPT = '(?i)terminal type\?'
TERMINAL_TYPE = 'vt100'
SSH_NEWKEY = '(?i)are you sure you want to continue connecting'

child = pexpect.spawn('ssh -l %s %s'%(loginuser, servername))
i = child.expect([pexpect.TIMEOUT, SSH_NEWKEY, COMMAND_PROMPT, '(?i)password'])

if i == 0: # Timeout
    print('ERROR! could not login with SSH. Here is what SSH said:')
    print(child.before, child.after)
    print(str(child))
    sys.exit (1)

if i == 1: # In this case SSH does not have the public key cached.
    child.sendline ('yes')
    child.expect ('(?i)password')

if i == 2:
    # If a public key was setup to automatically login
    pass

if i == 3:
    child.sendline(password)
    # Now we are either at the command prompt or
    # the login process is asking for our terminal type.
    i = child.expect ([COMMAND_PROMPT, TERMINAL_PROMPT])
    if i == 1:
        child.sendline (TERMINAL_TYPE)
        child.expect (COMMAND_PROMPT)

Now suppose I want to execute the following command on the server I logged in to and save the result to a string in my python script itself:

 ps -ef|grep process1

How can this be done?

Inian
  • 80,270
  • 14
  • 142
  • 161
  • You want `pidof process1` if you value your sanity. – tripleee Jun 30 '16 at 11:25
  • What command should I use if I want to run `pidof process1` **on the server that I logged into _in_ my script** and **not the server that currenty has my script**, and also store the result as a string – Vibhuti Shukla Jul 01 '16 at 06:52

2 Answers2

1

I think this might help you.

import subprocess
import sys

url="http://www.anyurlulike.any"
# Ports are handled in ~/.ssh/config since we use OpenSSH
COMMAND="uname -a"
ssh = subprocess.Popen(["ssh", "%s" % url, COMMAND],
                   shell=False,
                   stdout=subprocess.PIPE,
                   stderr=subprocess.PIPE)

result = ssh.stdout.readlines()
if result == []:
error = ssh.stderr.readlines()
print >>sys.stderr, "ERROR: %s" % error
else:
print result
Abhishake Gupta
  • 2,939
  • 1
  • 25
  • 34
  • Subprocess: It's the default Python library that runs commands. You can make it run ssh and do whatever you need on a remote server. – Abhishake Gupta Jun 30 '16 at 11:35
0

You can use read() function, it will give you the entire output.

result = child.read()
sozkul
  • 665
  • 4
  • 10