使用python脚本轻松实现ssh免密登陆配置

1.安装python和pip包

yum install -y epel-release
yum install -y python python-pip

2.pip安装依赖库

pip install pexpect     # 此库用相当于linux中的expect命令

3.完整脚本

# coding=UTF-8
import sys,os,pexpect,subprocess

host_controller="192.168.174.150"                            # 控制节点IP地址
host_addresses=["192.168.174.151","192.168.174.152"]           # 客户端们的IP地址
host_domains=["client1","client2"]                          # 客户端们的域名
host_username="root"                                         # ssh连接的用户,控制端的用户为root
host_passwd="110119"                                         # ssh连接的用户密码


# 本地创建ssh公钥
if os.path.exists("/root/.ssh/id_rsa.pub") == True:
	print("\033[32m"+"ssh公钥已创建"+"\033[0m")                # 输出绿色字体
else:
	print("\033[32m"+"ssh公钥未创建,开始创建"+"\033[0m")
	child = pexpect.spawn('ssh-keygen -t rsa -b 1024')
	child.expect('Enter file in which to save the key')
	child.sendline('')
	child.expect('Enter passphrase')
	child.sendline('')
	child.expect('Enter same passphrase again')
	child.sendline('')

	child.expect(pexpect.EOF)               # 用于等待子进程的结束
	print(child.before.decode())            # 等待命令执行完毕并打印输出信息
	print("\033[32m" + "ssh公钥已创建" + "\033[0m")
	print("\n")


# 向被控主机添加公钥的方法
def add_ssh_public_key_client(address,username,password):
	print("\033[32m"+"{}正在被添加公钥".format(address)+"\033[0m")
	# BatchMode=yes:表示使SSH在连接过程中不会提示输入密码,而直接尝试免密连接,-o ConnectTimeout=5:表示限制连接超时时间为5秒
	public_key_flag=os.system("ssh {}@{} -o BatchMode=yes -o ConnectTimeout=5 'exit'".format(username,address))
	if public_key_flag== 0:
		print("\033[32m" + "{}已经可以ssh连接".format(address) + "\033[0m")
		return
	child = pexpect.spawn('ssh-copy-id -i /root/.ssh/id_rsa.pub {}@{}'.format(username,address))
	try:
		child.expect('Are you sure you want to continue connecting')
	except pexpect.TIMEOUT:       # 如果try块中的咨询超时5秒没有出现就会出现异常pexpect.TIMEOUT
		print("\033[32m"+"{}已经不是首次ssh连接了".format(address)+"\033[0m")
	else:                         # 是否回答咨询yes
		child.sendline('yes')
	finally:
		child.expect('password')
		child.sendline(password)
	child.expect(pexpect.EOF)               # 用于等待子进程的结束
	print(child.before.decode())            # 等待命令执行完毕并打印输出信息
# 测试ssh连接的方法
def test_ssh_connection(all_flag,address,username):
	print("\033[32m" + "{}测试是否可以ssh连接".format(address) + "\033[0m")
	flag=os.system('ssh {}@{} -o ConnectTimeout=5 "exit"'.format(username,address))
	if flag==0:
		print("\033[32m" + "Success: {}可以ssh免密连接".format(address) + "\033[0m")
	else:
		print("\033[1;31m" + "Failed: {}ssh免密连接失败".format(address) + "\033[0m")     # 输出红色字体
		all_flag=1
	return all_flag

# 本地的密钥开始加入被控制主机
for i in range(0, len(host_addresses)):
	add_ssh_public_key_client(host_addresses[i],host_username,host_passwd)
	print("\n")
# 测试ssh连接
for i in range(0, len(host_addresses)):
	final_flag=test_ssh_connection(0,host_addresses[i],host_username)
if final_flag ==1:
	sys.exit("ssh测试失败,请检查!")
else:
	print("\033[32m" + "Success: 全部可以ssh免密连接" + "\033[0m")
print("\n")

4.执行结果

[root@server ~]# python ansible_auto.py
ssh公钥未创建,开始创建
: 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:RvdYf1KOFDyKBuEB6DbFQdfNP9aBPs1/0vIFnutEj5E root@server
The key's randomart image is:
+---[RSA 1024]----+
|     ++o+o o .o  |
|    . oo... o.oo |
|   . .  o...oo+oo|
|    +  . .o+.==B.|
|   . .  S.. .oE=+|
|       .     .=*=|
|              o=+|
|             .. .|
|             ..  |
+----[SHA256]-----+

ssh公钥已创建


192.168.174.151正在被添加公钥
: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'root@192.168.174.151'"
and check to make sure that only the key(s) you wanted were added.




192.168.174.152正在被添加公钥
: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'root@192.168.174.152'"
and check to make sure that only the key(s) you wanted were added.




Success: 192.168.174.151可以ssh免密连接
Success: 全部可以ssh免密连接


Success: 192.168.174.152可以ssh免密连接
Success: 全部可以ssh免密连接

相关推荐

  1. 使用python脚本轻松实现ssh登陆配置

    2023-12-08 08:24:09       44 阅读
  2. 一键配置ssh登录脚本

    2023-12-08 08:24:09       30 阅读
  3. 快速配置ssh登录

    2023-12-08 08:24:09       23 阅读
  4. ssh登录

    2023-12-08 08:24:09       39 阅读
  5. ssh 登录

    2023-12-08 08:24:09       28 阅读
  6. SSH登录

    2023-12-08 08:24:09       13 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-08 08:24:09       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-08 08:24:09       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-08 08:24:09       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-08 08:24:09       20 阅读

热门阅读

  1. nginx 一键切换停机维护页面 —— 筑梦之路

    2023-12-08 08:24:09       40 阅读
  2. 生成对抗网络GAN中的潜向量Z是用来做什么的?

    2023-12-08 08:24:09       41 阅读
  3. Docker实战笔记 三 Docker私有库

    2023-12-08 08:24:09       26 阅读
  4. 图表管理功能(前后端实现增删改查)

    2023-12-08 08:24:09       34 阅读
  5. 微信小程序 - 文件工具类 fileUtil.js

    2023-12-08 08:24:09       37 阅读
  6. 第59天:django学习(八)

    2023-12-08 08:24:09       32 阅读
  7. Git初学入门指令

    2023-12-08 08:24:09       30 阅读
  8. 策略模式终极解决方案之策略机

    2023-12-08 08:24:09       30 阅读
  9. 鸿蒙(HarmonyOS)应用开发——构建页面(题目答案)

    2023-12-08 08:24:09       67 阅读