Python and pexpect for SSH operation

Source: Internet
Author: User

Download and install the Pexpect and ptyprocess modules and combine the python2.7 to achieve the following:

TAR-ZXVF pexpect-4.0.1.tar.gz  

CD pexpect-4.0.1

Python Install

TAR-ZXVF ptyprocess-0.5.tar.gz


Python Install

PY Script

#!/usr/bin/env python


Import Pexpect

#from Getpass Import Getpass

#passwd = Getpass ()

def ssh_cmd (User,ip, CMD,PASSWD):

SSH = pexpect.spawn (' ssh%[email protected]%s '%s '% (user,ip,cmd))


i = ssh.expect ([' Password: ', ' Continue connecting (yes/no)? '], timeout=5)

If i = = 0:

Ssh.sendline (passwd)

elif i = = 1:

Ssh.sendline (' yes ')

Ssh.expect (' Password: ')

Ssh.sendline (passwd)

Except Pexpect. Eof:

Print "EOF"

Except Pexpect. TIMEOUT:



R = ()

Print R

Ssh.close ()

if __name__ = = ' __main__ ':

File=open ("/mess/filelist", ' R ')

A = ()

File.close ()

For host in A.split ("\ n"):

If host:

USER,IP,CMD,PASSWD = Host.split ("::")

Print "--%s run:%s--"% (IP, cmd)




Root:: assword

root:: s-ef|grep ssh|awk ' {print $8} '::p assword

Python and pexpect for SSH operation

Related Article

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: 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.