2

I am trying to create a shutdown script to remotely power down some servers remotely; I have enabled telnet, and when using PuTTY or similar, it is a simple matter to run the shutdown procedure.

I attempted to automate using the following Python script:

import telnetlib

doReadWrite(tn, wrt, rd):
    if wrt is not None:
        tn.write(wrt)
    if rd is not None:
        return tn.read_until(rd)

ip_list = [list of IP addresses]

for ip in ip_list:
    server = telnetlib.Telnet(ip)
    doReadWrite(server, None, b'login: ')
    doReadWrite(server, username+b'\r\n', b'Password: ')
    doReadWrite(server, password+b'\r\n', b'$')
    doReadWrite(server, b'su\r\n', b'Password: ')
    doReadWrite(server, root_pass+b'\r\n', b'#')
    doReadWrite(server, b'/sbin/halt\r\n', None)
    server.close()

If I enter the above script line by line in the interactive shell, it works as expected, however, if I run it from the command line, i.e., python shutdown_script.py, it hangs; if I specify a timeout, I get a timeout error. If I explicitly run the script as Python 2.7, it works fine, and for the time being, is an acceptable work around.

What differences are there between the execution of commands in the interactive shell,and the command-line intepreter that cause this difference in behaviour?

0 Answers0