python ssh批量登录 自动交互

用python来ssh远程登录,如果用os.system('commod'),结果就是人机互动,跟不用也没啥区别。

百度发现,可以用pexpect模块来实现自动交互。

# python3
import pexpect

def ssh_cmd(ip, passwd):
    #a = os.system('ssh ' +s)
    ssh = pexpect.spawn('ssh root@%s'%ip)
    try:
        i = ssh.expect(['password:','continue connecting (yes/no)?'], timeout=2)
        if i ==0:
            ssh.sendline(passwd)
        elif i ==1:
            ssh.sendline('yes\n')
            ssh.expect('password: ')
            ssh.sendline(passwd)
        ret = 0
    except pexpect.EOF:
        print ("EOF")
        ssh.close()
        ret = -1
    except pexpect.TIMEOUT:
        print ("TIMEOUT")
        ssh.close()
        ret = -2
    return ret

#ssh 192.168.9.2-192.168.0.10的9台机器
for i in range(2,11):
    ip = '192.168.0.'+str(i)
    passwd = 'password'#密码
    num= ssh_cmd(ip,passwd)
    print (num)
pexpect文档 https://pexpect.readthedocs.io/en/stable/api/pexpect.html
参考链接: http://www.cnblogs.com/ma6174/archive/2012/05/25/2508378.html(python3有点问题,ssh.read()会报出错)



你可能感兴趣的:(互联网,安全,程序人生)