linux ssh免密码登录脚本
一、准备工作。
安装python(已安装可忽略)
yum install python
安装pip
yum install python-pip
安装 pexpect3.3
pip install pexpect==3.3
生成公钥 ssh-keygen
二、执行脚本
#!/usr/bin/env python # -*- encoding:utf8 -*- import sys, os, io import pexpect argc = len(sys.argv) if (argc != 2): os._exit(1) ip = sys.argv[1] user = 'root' password = '123456' loginPrompt = '[$#>]' cmd = 'ssh-copy-id -i /root/.ssh/id_rsa.pub ' + user + '@' + ip ssh_newkey = 'Are you sure you want to continue connecting (yes/no)?' success = 'Now try logging into the machine' child = pexpect.spawn(cmd) index = child.expect([success, ssh_newkey, 'password: ', pexpect.TIMEOUT, pexpect.EOF]) if (index == 0): print "Success!!" elif (index == 1): child.sendline("yes") index = child.expect(['assword:', pexpect.TIMEOUT, pexpect.EOF]) if (index == 0): child.sendline(password) index = child.expect([success, pexpect.TIMEOUT, pexpect.EOF]) if (index == 0): print "Success!!" elif (index == 2): child.sendline(password) index = child.expect([success, pexpect.TIMEOUT, pexpect.EOF]) if (index == 0): print "Success!!" else: print "Connection Error!" os._exit(1) child.close(force=True)
执行完脚本后再登录该机器就不需要再输入密码。