- 指令碼當前目錄下建立host_list 檔案,需要免密登陸的伺服器IP地址一行一個。
- 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))