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 setup.py Install

TAR-ZXVF ptyprocess-0.5.tar.gz

cd/ptyprocess-0.5

Python setup.py Install


PY Script

#!/usr/bin/env python

#-*-Coding:utf-8-*-

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

Try

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:

Print "TIMEOUT"

Else

R = Ssh.read ()

Print R

Ssh.close ()


if __name__ = = ' __main__ ':

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

A = File.read ()

File.close ()

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

If host:

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

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

Ssh_cmd (USER,IP,CMD,PASSWD)

-------------------------------------------------------------------------------------------

/mess/filelist

Root::192.168.100.100::ls-l::p assword

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


Python and pexpect for SSH operation

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.