第一步: ssh-keygen 生成公钥和私钥对
-t后为加密方式rsa和dsa都可以,默认为dsa,根据加密方式不同,生成id_rsa,id_rsa.pub或id_dsa,id_dsa.pub
-P 后加密码,''不填为空
#ssh-keygen -t rsa -P ''
第二步: 用ssh-copy-id将公钥写到远程机器的~/.ssh/authorized_keys中
#ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.1.1
第三步: ssh免密登录远程机器验证
#ssh 192.168.1.1
免密登录脚本 sshauth
#!/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] // 目标机ip
user = 'root' // 目标机的用户名
password = 'temp321@' // 目标机的密码
loginPrompt = '[$#>]'
cmd = 'ssh-copy-id -i /root/.ssh/id_rsa.pub ' + user + '@' + ip
ssh_newkey = 'Are you sure you want to continue connecting'
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)
本文详细介绍如何通过ssh-keygen生成公钥和私钥对,使用ssh-copy-id将公钥写入远程机器,并验证免密登录。同时提供了一个Python脚本实现自动化配置。
1万+

被折叠的 条评论
为什么被折叠?



