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