Thursday, 14 June 2018

python - Execute the system Linux command on remote Linux machine

python - Execute the system Linux command on remote Linux machine


Python Program:


mport pexpect
import getpass
import sys

PASSWORD = "admin123"

def child_kill(child_pro):
    if child_pro.isalive():
        print "Still child is live 1 \n"
        child_pro.close()       # Kill the child, give argument as force=true then also same behaviour
    if child_pro.isalive():
        print "Still child is live 2\n\n"
    else:
        print "Child is dead"

def child_read_command(child_pro, command, expect_str):
    child_pro.sendline (command)
    child_pro.expect (expect_str)

# use list format, string format is not working
    output = []
    done = False
    while True:
        try:
            if not child_pro.isalive():
                line = child_pro.readline()
                done = True
            else:
# Wait on multiple expect eg: i = child.expect(['first', 'second'])
# i retrun 0 for first, and 1 for second
                i = child_pro.expect(['\n', expect_str])
                if i == 0:
                    line = child_pro.before
                    print(line)
                else:
                    line = child_pro.before
                    print(line)
                    break
            output.append(line)
            if done:
                raise pexpect.EOF(0)
                print "Rasie the pexect EOF"
        except pexpect.EOF:
            print "Break of EOF"
            break

    print "\n\nOutput value = ", output
    child_kill(child_pro)

def ssh_login(host_address):
    child = pexpect.spawn ('ssh '+host_address)
    child.logfile = open("/home/labuser/mylog", "w")   # This will store the output logs into the file
#    child.logfile = sys.stdout
    child.expect ('password: ')
    child.sendline (PASSWORD)
    child.expect ('machine:')
    return child


def main():
    child = ssh_login("192.168.1.50")
    child_read_command(child,'ls','machine:')


main()



No comments:

Post a Comment