【Python】模拟ssh登录执行命令

通过收集WAF日志获取到攻击IP,想调用机房出口FW封禁攻击IP,看了下python通过ssh登录juniper并封禁IP。
1)pexpect

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pexpect

def ssh_cmd(ip, passwd, cmd):
    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
    except pexpect.EOF:
        print "EOF"
        ssh.close()
    except pexpect.TIMEOUT:
        print "TIMEOUT"
        ssh.close()

ssh_cmd('10.59.0.248','******','ls')

2)paramiko

#-*- coding: utf-8 -*-
#!/usr/bin/python 
import paramiko

def ssh_cmd(ip,username,passwd,cmd):
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip,22,username,passwd,timeout=5)
        for m in cmd:
            stdin, stdout, stderr = ssh.exec_command(m)
#           stdin.write("Y")   #简单交互,输入 ‘Y’ 
            out = stdout.readlines()
            #屏幕输出
            for o in out:
                print o,
        print '%s\tOK\n'%(ip)
        ssh.close()
    except :
        print '%s\tError\n'%(ip)
if __name__=='__main__':
    cmd = ['whoami','echo hello!']#你要执行的命令列表
	ssh_cmd('10.59.0.248','******',cmd)