python paramiko 远程登陆主机并获取主机信息

#!/usr/bin/python
# encoding: utf-8
#filename: host_information_get.py
#author: gaohaixiang
#writetime:20200409

import paramiko

def host_ssh_conn(ip):
    port,username,userpassword = 22,"root","123456"

    #存放查询数据结果的文件
    ff = open("result.txt","a+")
    ff.writelines("#"*50+"\n")
    ff.writelines(ip+"\n")

    #登陆主机及登陆时错误捕捉处理
    try:
        ssh = paramiko.SSHClient()         #调用paramiko模块下的SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())   #加上这句话不用担心选yes的问题,会自动选上(用ssh连接远程主机时,第一次连接时会提示是否继续进行远程连接,选择yes)
        ssh.connect(ip,port,username,userpassword,timeout=3)    #连接远程主机,SSH端口号为22,会话超时为3秒
    except:
        return None
    else:
        pass

    #ip,主机名,系统类型
    commands = ["ip a|grep inet|grep brd","hostname","cat /etc/redhat-release"]
    for command in commands:
        stdin, stdout, stderr = ssh.exec_command(command,timeout=10,get_pty=True)   #执行命令
        # print (stdout.readlines())
        results = stdout.readlines()
        print(results)
        for result in results:
            ff.writelines(result)
    ssh.close()
    ff.close()

if __name__ == '__main__':
    # ip处理
    file = open("ip_list.txt", "r")
    iplist = file.readlines()
    for ips in iplist:
        ip = ips.strip("\n").strip()
        print(ip)

        #调用函数
        host_ssh_conn(ip)
    file.close()

你可能感兴趣的:(python,运维,python,ssh,linux)