问题
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!
回答1:
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')
来源:https://stackoverflow.com/questions/18234030/send-commands-to-a-remote-machine-application-with-python