Python expect interaction

Source: Internet
Author: User



[[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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.