python pexpect模块封装ssh
很多时候需要批量在一批主机上执行某个操作时,利用python 可以很好的完成这个工作。如果在现网主机上没有部署自动化工具时,同时你又不想使用paramiko这样相对重量级的模块,你可以通过pexpect模块通过一个简单的spawn执行并交互完成一些简单的命令操作。
pexpect模块的安装
1# wget https://pypi.python.org/packages/source/p/pexpect/pexpect-3.3.tar.gz
2# tar zxvf pexpect-3.3.tar.gz
3# cd pexpect-3.3
4# python setup.py install
示例:
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3import pexpect
4def ssh_cmd(ip, passwd, cmd):
5 ret = -1
6 ssh = pexpect.spawn('ssh root@%s "%s"' % (ip, cmd))
7 try:
8 i = ssh.expect(['password:', 'continue connecting (yes/no)?'], timeout=5)
9 if i == 0 :
10 ssh.sendline(passwd)
11 elif i == 1:
12 ssh.sendline('yesn')
13 ssh.expect('password: ')
14 ssh.sendline(passwd)
15 ssh.sendline(cmd)
16 r = ssh.read()
17 print r
18 ret = 0
19 except pexpect.EOF:
20 print "EOF"
21 ssh.close()
22 ret = -1
23 except pexpect.TIMEOUT:
24 print "TIMEOUT"
25 ssh.close()
26 ret = -2
27 return ret
28ssh_cmd("192.168.0.102","361way","uptime")
捐赠本站(Donate)
如您感觉文章有用,可扫码捐赠本站!(If the article useful, you can scan the QR code to donate))
- Author: shisekong
- Link: https://blog.361way.com/python-pexpect-command/3983.html
- License: This work is under a 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议. Kindly fulfill the requirements of the aforementioned License when adapting or creating a derivative of this work.