首页 > 代码库 > linux自动化建互信

linux自动化建互信

自动化执行建互信,也可以使用其他脚本调用.不多说,直接上代码

#!/usr/bin/env python
# encoding: utf-8
import os
import pexpect
import getpass
#yum install -y python-paramiko pexpect  #依赖的安装包.直接用yum即可
import paramiko
import pexpect,os,optparse
def ssh_trust(ip,user,mypassword):
    try:
        pkey=‘/root/.ssh/id_rsa‘
        key=paramiko.RSAKey.from_private_key_file(pkey)
        s=paramiko.SSHClient()
        s.load_system_host_keys()
        s.connect(hostname =ip,port=22,username=user,pkey=key)
        stdin,stdout,stderr=s.exec_command(‘echo "Mutual trust has been successful"‘)
        print stdout.read()
    except:
        print(‘Begin to build mutual trust‘)
        child = pexpect.spawn(‘ssh-copy-id -o StrictHostKeyChecking=no -i /root/.ssh/id_rsa.pub %s@%s‘ % (user,ip))
        child.expect (‘password:‘)
        child.sendline (mypassword)
        child.interact()
        child.close(force=True)
def exec_trust(ip,user,mypassword):
    if os.path.exists(‘/root/.ssh‘) and os.path.exists(‘/root/.ssh/id_rsa.pub‘):
        ssh_trust(ip,user,mypassword)
    else:
        print(‘Create a public key‘)
        os.system("ssh-keygen  -t rsa -N ‘‘ -f ~/.ssh/id_rsa")
        ssh_trust(ip,user,mypassword)
if __name__ == ‘__main__‘:
    parse=optparse.OptionParser(usage=‘" usage : %prog [options] arg1, arg2 "‘, version="%prog 1.0")
    parse.add_option(‘-u‘, ‘--user‘, dest = ‘user‘, type = str, help = ‘Login user name‘)
    parse.add_option(‘-p‘, ‘--password‘, dest = ‘password‘, type = str, help = ‘The user password‘)
    parse.add_option(‘-i‘, ‘--ip‘, dest = ‘ip‘, type = str, help = ‘The IP address.‘)
    parse.add_option(‘-v‘, help=‘version 1.0‘)
    parse.set_defaults(v = 1.0)
    options,args=parse.parse_args()
    ip = options.ip
    user = options.user
    if user is None:
        user=getpass.getuser()
    passwd = options.password
    if passwd is None:
        passwd=‘setpay@123‘  #当传入密码为空是,自动的默认密码
    exec_trust(ip,user,passwd)


本文出自 “梧桐” 博客,请务必保留此出处http://songhl.blog.51cto.com/1538319/1926497

linux自动化建互信