python2.7 脚本实现SSH 免密登录 Mac OS

导读:本篇文章讲解 python2.7 脚本实现SSH 免密登录 Mac OS,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

 使用python2.7, 加上paramiko库实现。可以遍历多个服务器自动配置

目前在Macbook Air测试是正常的,能把公钥拷贝到服务器。

python2.7 脚本实现SSH 免密登录 Mac OS

下面上代码2个文件 ,一个python, 一个txt用存ip账号密码。

#! python2.7
# -*- coding:utf-8 -*-
# @Time    : 2021/6/1 14:34
# @Author  : Lani
# @File    : sshauto.py
import logging
import os, paramiko
import traceback


def ssh_authentication(server_ip, user, passwd):
    """进行ssh的免密码认证"""
    # server_id 备份服务器地址,字符串
    logging.info("test ping server %s ..." % server_ip)
    if os.system("ping %s -c 3 >>/dev/null" % server_ip):
        # 先测试一下连通性
        return -1

    if os.path.exists(os.path.expanduser("~/.ssh/id_rsa")) and os.path.exists(
            os.path.expanduser("~/.ssh/id_rsa.pub")):
        print "~/.ssh/id_rsa.pub {}".format("公钥已经存在")
    else:
        if os.system("ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa"):  # 在客户端生成ssh密钥,设置好参数,这样就不会中途要求输入
            return -1
        else:
            if os.path.exists(os.path.expanduser("~/.ssh/id_rsa")) and os.path.exists(
                    os.path.expanduser("~/.ssh/id_rsa.pub")):
                print "ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa  {}".format("指令执行成功")

    # 使用用户名,密码建立ssh链接
    transport = paramiko.Transport((server_ip, 22))
    try:
        transport.connect(username=user, password=passwd)
    except Exception:
        print "transport ERROR {}".format(traceback.format_exc())
        return -1

    ssh = paramiko.SSHClient()
    ssh._transport = transport  # 将sftp和ssh一同建立
    sftp = paramiko.SFTPClient.from_transport(transport)

    sftp.put(os.path.expanduser("~/.ssh/id_rsa.pub"), "/Users/{}/.ssh/filebackkey.pub".format(user))  # 上传公钥

    stdin, stdout, stderr = ssh.exec_command(
        "cat /Users/{}/.ssh/filebackkey.pub >> /Users/{}/.ssh/authorized_keys".format(user,
                                                                                      user))  # 添加公钥 这里根据实际情况进行修改,设置成用户名下的.ssh
    if stderr.channel.recv_exit_status():
        ssh.close()
        print "cat copy key  ERROR"
        return -1

    stdin, stdout, stderr = ssh.exec_command(
        "chmod 600 /Users/{}/.ssh/authorized_keys".format(user))  # 这里根据实际情况进行修改,设置成用户名下的.ssh
    if stderr.channel.recv_exit_status():
        ssh.close()
        print "ssh ERROR"
        return -1

    

    transport.close()
    ssh.close()

    if os.system("eval `ssh-agent` && ssh-add"):  # 客户端添加私钥
        return -1
    return 0


if __name__ == '__main__':
    all_ip_info = None
    with open("hostip.txt", "r") as f:
        all_ip_info = f.readlines()

    if all_ip_info is not None:
        for ip_info in all_ip_info:
            ip_info = ip_info.split(" ")

        
            if len(ip_info) == 2:
                ssh_authentication(ip_info[0], ip_info[1], "")  # 服务端: ip, 账号,空密码
            elif len(ip_info) > 2:
                ssh_authentication(ip_info[0], ip_info[1], ip_info[2])  # 服务端: ip, 账号,密码

hostip.txt 文件 :  服务端: ip, 账号,空密码 用单个空格隔开就可以了,换行输入多个

192.168.06.49 test test

参考 :

https://blog.csdn.net/yhb_csdn/article/details/99057482?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-4.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-4.control

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/101657.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!