Cooli
Cooli

Reputation: 179

Send commands to a remote machine application with Python

I want to do the following in Python. Connect to a remote machine open an application there and then send some commands to this application. My idea was to do it through telnetlib and subprocess. I managed to connect to the machine and start the application (with telnetlib alone), but I am not sure how to continue. Is it possible?

P.S. I am also open to ideas to do it another way, but I would prefer to do it with python.

Thanks in advance!

Upvotes: 0

Views: 695

Answers (1)

amb1s1
amb1s1

Reputation: 2075

you can do the following:

child = pexpect.spawn('telnet 192.168.0.1')
child.expect('[Ll]ogin') #you use the expected output, here will match either Login or login
child.sendline('username')
child.expect('[Pp]assword')
child.sendline('password')
child.expect('your remote prompt')
child.sendline('command')

you can install pexpect using pip

You can also have a list of expect:

index = child.expect['[Ll]ogin', '[Pp]assword']
if index == 0:
    child.sendline('username')
else index == 1:
    child.sendline('password')

Upvotes: 1

Related Questions