Example of pexpect module encapsulation ssh in python

Source: Internet
Author: User
Tags ssh in python

Most of the time you need to do a batch of operations on a batch of hosts, using Python can do a good job. If you do not have the automation tools deployed on the current network, and you do not want to use the Paramiko such a relatively heavyweight module, you can through the Pexpect module through a simple spawn execution and interaction to complete a number of simple command operations.

Installation of Pexpect modules

The code is as follows Copy Code
# wget https://pypi.python.org/packages/source/p/pexpect/pexpect-3.3.tar.gz
# tar ZXVF pexpect-3.3.tar.gz
# CD pexpect-3.3
# python setup.py Install

Example:

The code is as follows Copy Code

#!/usr/bin/env python
#-*-Coding:utf-8-*-
Import Pexpect
def ssh_cmd (IP, passwd, cmd):
ret =-1
SSH = pexpect.spawn (' ssh root@%s '%s '% (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\n ')
Ssh.expect (' Password: ')
Ssh.sendline (passwd)
Ssh.sendline (CMD)
R = Ssh.read ()
Print R
RET = 0
Except Pexpect. Eof:
Print "EOF"
Ssh.close ()
ret =-1
Except Pexpect. TIMEOUT:
Print "TIMEOUT"
Ssh.close ()
RET =-2
return ret
Ssh_cmd ("192.168.0.102", "361way", "uptime")

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