Linux服务器批量ssh免密登陆

  1. 脚本当前目录下创建host_list 文件,需要免密登陆的服务器IP地址一行一个。
  2. 做免密登陆的用户已经使用ssh-keygen创建了公钥。
  3. python3执行脚本。
import paramiko
"""
每个服务器的密码都一样
host_list文件格式:每行一个IP地址
[root@jump tzhli]# cat host_list 
10.0.0.214
10.0.0.213
10.0.0.212
"""
user = "root"
passwd = "123"

def exec_commit(host, cmd, port=22):
    """远程执行系统命令"""
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    #ssh.connect(hostname=host, port=port)
    ssh.connect(hostname=host, port=22, username=user, password=passwd)
    stdin, stdout, stderr = ssh.exec_command(cmd)
    res, err = stdout.read(), stderr.read()
    result = res if res else err
    ssh.close()
    return result.decode().strip()

if user == "root":
    user_home = "/root"
else:
    user_home = "/home/%s" % (user)

with open("%s/.ssh/id_rsa.pub" % (user_home),"r",encoding="utf-8") as key_file:
    pub_key = key_file.read().strip("\n")

with open("./host_list","r",encoding="utf-8") as host_flie:
    read_file_list = host_flie.readlines()

for host_str in read_file_list:
    host = host_str.strip("\n")
    if len(host) == 0:
        continue
    exec_commit(host=host,cmd="echo %s >> %s/.ssh/authorized_keys" % (pub_key,user_home))
    print("%s服务器的公钥已添加。" % (host))



你可能感兴趣的:(linux,centos,ssh)