python,pexpect登錄ssh並執行命令

1、 安裝python的Pexpect模塊

wget http://jaist.dl.sourceforge.net/project/pexpect/pexpect/Release%202.3/pexpect-2.3.tar.gz

tar xzf pexpect-2.3.tar.gz

cd pexpect-2.3

python setup.py install

2、 執行腳本

可以登錄到機器執行一些簡單的命令等。。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pexpect
from getpass import getpass
passwd = getpass()
def ssh_cmd(user,ip, cmd):
        ssh = pexpect.spawn('ssh %s@%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("/root/python/filelist",'r')
        a = file.read()
        file.close()
        for host in a.split("\n"):
                if host:
                        user,ip,cmd = host.split("::")
                        print "-- %s run:%s --" % (ip, cmd)
                        ssh_cmd(user,ip,cmd)

more /root/python/filelist

root::1.1.1.1::ls&&date

root::2.2.2.2::ls&&date

................

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章