[[email protected] glpi_switch_ocs]# cat ssh3.py #!/usr/bin/env python# -*- coding: utf-8 -*- import pexpectimport getpass, osdef ssh_command (User, host, password, command): ssh_newkey = ' Are You sure you want to continue connecting ' child = pexpect.spawn (' ssh -l %s %s %s '% (user, host, command)) i = child.expect ([Pexpect. timeout, ssh_newkey, ' password: ') # if the login times out, print an error message and exit . if i == 0: # Timeout print ' error! ' print ' Ssh could not login. here is what ssh said: '       &NBsp; print child.before, child.after return None # if ssh does not public key, accept it . if i == 1: # ssh does not have the public key. just accept it. child.sendline (' yes ') child.expect (' password: ') i = child.expect ([Pexpect. timeout, ' password: ']) if i == 0: # Timeout print ' SSH could not login. here is what ssh said: ' print child.before, child.after return none Child.sendline (password) return childdef main (): host = raw_input (' hostname: ') user = raw_input (' User: ') password = getpass.getpass () command = raw_input (' enter the command: ') child = ssh_command (User, host, password, command) child.expect (pexpect. EOF) print child.beforeif __name__ == ' __main__ ': try: main () except exception, e: print str (e) traceback.print_exc () &nbsP; os._exit (1) [[email protected] glpi_switch_ocs]# python ssh3.py hostname: 172.16.66.132 user: rootpassword: enter the Command: lsb_release -ano lsb modules are available. Distributor id: debiandescription: debian gnu/linux 7.9 (wheezy) release: 7.9codename: wheezy
This article is from "tossing the years." "Blog, be sure to keep this provenance http://990487026.blog.51cto.com/10133282/1715953
Python expect interaction