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

 更新时间:2023年12月12日 17:01:20   作者:碧蓝幻想  
这篇文章主要为大家详细介绍了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免密连接

到此这篇关于python利用脚本轻松实现ssh免密登陆配置的文章就介绍到这了,更多相关python ssh免密登陆配置内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 在RedHat系Linux上部署Python的Celery框架的教程

    在RedHat系Linux上部署Python的Celery框架的教程

    这篇文章主要介绍了在RedHat系Linux上部署Python的Celery框架的教程, Celery是一个并行分布框架,拥有良好的I/O性能,需要的朋友可以参考下
    2015-04-04
  • 如何把python项目部署到linux服务器

    如何把python项目部署到linux服务器

    这篇文章主要介绍了如何把python项目部署到linux服务器,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-08-08
  • python使用response.read()接收json数据的实例

    python使用response.read()接收json数据的实例

    今天小编就为大家分享一篇python使用response.read()接收json数据的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-12-12
  • Python中自定义函数的教程

    Python中自定义函数的教程

    这篇文章主要介绍了简单讲解Python中内置函数的使用,函数的使用是Python学习当中的基本功,需要的朋友可以参考下
    2015-04-04
  • python的rllib库你了解吗

    python的rllib库你了解吗

    这篇文章主要介绍了python urllib库的使用,帮助大家更好的利用python学习爬虫,感兴趣的朋友可以了解下,希望能够给你带来帮助
    2021-11-11
  • python序列类型种类详解

    python序列类型种类详解

    这篇文章主要介绍了python序列类型种类详解,需要的朋友们可以学习参考下。
    2020-02-02
  • Python 通过URL打开图片实例详解

    Python 通过URL打开图片实例详解

    这篇文章主要介绍了Python 通过URL打开图片实例详解的相关资料,需要的朋友可以参考下
    2017-06-06
  • Pytorch运行过程中解决出现内存不足的问题

    Pytorch运行过程中解决出现内存不足的问题

    内存不足是很多人感到头疼的问题,本文主要介绍了Pytorch运行过程中解决出现内存不足的问题,具有一定的参考价值,感兴趣的可以了解一下
    2024-02-02
  • Pytorch 使用不同版本的cuda的方法步骤

    Pytorch 使用不同版本的cuda的方法步骤

    这篇文章主要介绍了Pytorch 使用不同版本的cuda的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-04-04
  • pytorch如何实现多个矩阵拼接

    pytorch如何实现多个矩阵拼接

    这篇文章主要介绍了pytorch如何实现多个矩阵拼接问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-09-09

最新评论