• Ansible 2.6 Pthon API


    核心代码

    python3.6

    ansible 2.6

     官方ansible-api文档:Python API — Ansible Documentation

    ansibleAPI 常用模块

    1. 用于读取yaml,json格式的文件
    2. from ansible.parsing.dataloader import DataLoader
    3. #用于管理变量的类,包括主机,组,扩展等变量
    4. from ansible.vars.manager import VariableManager
    5. #用于创建和管理inventory,倒入inventory文件
    6. from ansible.inventory.manager import InventoryManager
    7. #ad-hoc 存储着角色列表,任务,处理代码块
    8. from ansible.playbook.play import Play
    9. #ad-hoc ansible底层用到的任务队列
    10. from ansible.executor.task_queue_manager import TaskQueueManager
    11. #回调基类,用来定义回调事件,比如返回失败成功等信息
    12. from ansible.plugins.callback import CallbackBase
    13. #执行playbook
    14. from ansible.executor.playbook_executor import PlaybookExecutor
    15. #操作单个主机
    16. from ansible.inventory import host
    17. #操作单个主机组
    18. from ansible.inventory import group

    InventoryManager

    1. #实例化需要两个参数
    2. "参数一为读取yml文件的信息,需要实例化 DataLoader"
    3. "参数二为读取从那个位置读取资产配置文件,多个可逗号分割"
    4. intertory = InventoryManager(loader='',sources='')
    5. #以字典的方式打印出主机和主机组相关信息
    6. intertory.get_group_dict()
    7. #获取所有的主机
    8. inventory.get_hosts()
    9. #添加主机到指定主机组
    10. "参数一指定主机地址"
    11. "参数二指定主机端口"
    12. "参数三指定主机群组,必须存在的群组"
    13. inventory.add_host(host='10.1.41.200',port=2222,group='game_group')
    14. #获取指定的主机对象
    15. inventory.get_host(hostname='10.1.41.200')


    VariableManager

    1. #实例化需要两个参数
    2. "参数一为读取yml文件的信息,需要实例化 DataLoader"
    3. "参数二为资产管理配置变量"
    4. variable = VariableManager(loader=loader,inventory=inventory)
    5. #获取变量
    6. variable.get_vars()
    7. # 查看指定主机的详细变量信息
    8. "传入的host是inventory.get_host获得的主机对象"
    9. host = inventory.get_host(hostname='10.1.41.200')
    10. host_vars = variable.get_vars(host=host)
    11. #设置主机变量方法 
    12. "传入的host是inventory.get_host获得的主机对象"
    13. host = inventory.get_host(hostname='10.1.41.200')
    14. variable.set_host_variable(host=host,varname='ansible_ssh_pass',value='root')
    15. variable.set_host_variable(host=host,varname='ansible_ssh_user',value='root')
    16. #添加扩展变量
    17. "参数是一个字典多个逗号分割"
    18. variable.extra_vars={'devops':'best'}

    1. #!/usr/bin/env python
    2. from collections import namedtuple
    3. from ansible.executor.task_queue_manager import TaskQueueManager
    4. from ansible.inventory.manager import InventoryManager
    5. from ansible.parsing.dataloader import DataLoader
    6. from ansible.playbook.play import Play
    7. from ansible.plugins.callback import CallbackBase
    8. from ansible.vars.manager import VariableManager
    9. # Create a callback object so we can capture the output
    10. class ResultsCollector(CallbackBase):
    11.     def __init__(self, *args, **kwargs):
    12.         super(ResultsCollector, self).__init__(*args, **kwargs)
    13.         self.host_ok = {}
    14.         self.host_unreachable = {}
    15.         self.host_failed = {}
    16.     def v2_runner_on_unreachable(self, result):
    17.         self.host_unreachable[result._host.get_name()] = result
    18.     def v2_runner_on_ok(self, result, *args, **kwargs):
    19.         self.host_ok[result._host.get_name()] = result
    20.     def v2_runner_on_failed(self, result, *args, **kwargs):
    21.         self.host_failed[result._host.get_name()] = result
    22. def main():
    23.     host_list = ['10.1.41.210','10.1.41.200']
    24.     Options = namedtuple('Options', ['connection''module_path''forks''remote_user',
    25.                                      'private_key_file''ssh_common_args''ssh_extra_args''sftp_extra_args',
    26.                                      'scp_extra_args''become''become_method''become_user''verbosity''check',
    27.                                      'diff'])
    28.     # required for
    29.     # https://github.com/ansible/ansible/blob/devel/lib/ansible/inventory/manager.py#L204
    30.     sources = ','.join(host_list)
    31.     if len(host_list) == 1:
    32.         sources += ','
    33.     # initialize needed objects
    34.     loader = DataLoader()
    35.     options = Options(connection='smart', module_path=['/usr/share/ansible'], forks=100,
    36.                       remote_user=None, private_key_file=None, ssh_common_args=None, ssh_extra_args=None,
    37.                       sftp_extra_args=None, scp_extra_args=None, become=None, become_method=None,
    38.                       become_user=None, verbosity=None, check=False, diff=False,)
    39.     passwords = dict()
    40.     # create inventory and pass to var manager
    41.     inventory = InventoryManager(loader=loader, sources=sources)
    42.     variable_manager = VariableManager(loader=loader, inventory=inventory)
    43.     for host in host_list:
    44.         inventory.add_host(host=host,port=65534)
    45.         hostname=inventory.get_host(hostname=host)
    46.         variable_manager.set_host_variable(host=hostname,varname='ansible_ssh_pass',value='root')
    47.         variable_manager.set_host_variable(host=hostname,varname='ansible_ssh_user',value='root')
    48.     # create play with tasks
    49.     play_source = dict(
    50.         name="Ansible Play",
    51.         hosts=host_list,
    52.         gather_facts='no',
    53.         #tasks=[dict(action=dict(module='command', args=dict(cmd='/usr/bin/uptime')))]
    54.         #tasks=[dict(action=dict(module='shell', args='/usr/sbin/ip a'))]
    55.         tasks=[
    56.                 dict(action=dict(module='setup', args='')),
    57.         #        dict(action=dict(module='setup', args=''),register='shell_out'),
    58.         #        dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}')))
    59.         ]
    60.     )
    61.     play = Play().load(play_source, variable_manager=variable_manager, loader=loader)
    62.     # actually run it
    63.     tqm = None
    64.     callback = ResultsCollector()
    65.     try:
    66.         tqm = TaskQueueManager(
    67.             inventory=inventory,
    68.             variable_manager=variable_manager,
    69.             loader=loader,
    70.             options=options,
    71.             passwords=passwords,
    72.         )
    73.         tqm._stdout_callback = callback
    74.         result = tqm.run(play)
    75.     finally:
    76.         if tqm is not None:
    77.             tqm.cleanup()
    78.     print("UP ***********")
    79.     for host, result in callback.host_ok.items():
    80.         try:
    81.             print('{0} >>> {1}'.format(host, result._result['stdout']))
    82.         except :
    83.             print('{0} >>> {1}'.format(host, result._result['ansible_facts']))
    84.     print("FAILED *******")
    85.     for host, result in callback.host_failed.items():
    86.         print('{0} >>> {1}'.format(host, result._result['msg']))
    87.     print("DOWN *********")
    88.     for host, result in callback.host_unreachable.items():
    89.         print('{0} >>> {1}'.format(host, result._result['msg']))
    90. if __name__ == '__main__':
    91.     main()

    基于上面的内容,自己封装的API 如下:

    1. #!/usr/bin/env python
    2. # -*- coding:utf-8 -*-
    3. # author : liuyu
    4. # date : 2018/8/6 0006
    5. from collections import namedtuple
    6. from ansible.executor.task_queue_manager import TaskQueueManager
    7. from ansible.inventory.manager import InventoryManager
    8. from ansible.parsing.dataloader import DataLoader
    9. from ansible.playbook.play import Play
    10. from ansible.plugins.callback import CallbackBase
    11. from ansible.vars.manager import VariableManager
    12. import ansible.constants as C
    13. C.HOST_KEY_CHECKING = False
    14. def default_taskinfos():
    15.     TaskInfos = {
    16.         "hostinfo": [
    17.             {
    18.                 "host""0.0.0.0",
    19.                 "port"22,
    20.                 "user""root",
    21.                 "password""root"
    22.             },
    23.         ],
    24.         "taskinfo": [
    25.             {
    26.                 "module""setup",
    27.                 "args"""
    28.             },
    29.         ]
    30.     }
    31.     return TaskInfos
    32. # Create a callback object so we can capture the output
    33. class ResultsCollector(CallbackBase):
    34.     def __init__(self, *args, **kwargs):
    35.         super(ResultsCollector, self).__init__(*args, **kwargs)
    36.         self.host_ok = {}
    37.         self.host_unreachable = {}
    38.         self.host_failed = {}
    39.     def v2_runner_on_unreachable(self, result):
    40.         self.host_unreachable[result._host.get_name()] = result
    41.     def v2_runner_on_ok(self, result, *args, **kwargs):
    42.         self.host_ok[result._host.get_name()] = result
    43.     def v2_runner_on_failed(self, result, *args, **kwargs):
    44.         self.host_failed[result._host.get_name()] = result
    45. class AnsibleApi(object):
    46.     def __init__(self, TaskInfos):
    47.         self.taskinfo = TaskInfos.get('taskinfo', default_taskinfos()["taskinfo"])
    48.         self.hostinfo = TaskInfos.get('hostinfo', default_taskinfos()["hostinfo"])
    49.         self.resultinfo = []
    50.     def run(self):
    51.         host_list = []
    52.         [host_list.append(i.get("host"'0.0.0.0')) for i in self.hostinfo]
    53.         Options = namedtuple('Options', ['connection''module_path''forks''remote_user',
    54.                                          'private_key_file''ssh_common_args''ssh_extra_args''sftp_extra_args',
    55.                                          'scp_extra_args''become''become_method''become_user''verbosity',
    56.                                          'check',
    57.                                          'diff'])
    58.         # required for
    59.         # https://github.com/ansible/ansible/blob/devel/lib/ansible/inventory/manager.py#L204
    60.         sources = ','.join(host_list)
    61.         if len(host_list) == 1:
    62.             sources += ','
    63.         # initialize needed objects
    64.         loader = DataLoader()
    65.         options = Options(connection='smart', module_path=['/usr/share/ansible'], forks=100,
    66.                           remote_user=None, private_key_file=None, ssh_common_args=None, ssh_extra_args=None,
    67.                           sftp_extra_args=None, scp_extra_args=None, become=None, become_method=None,
    68.                           become_user=None, verbosity=None, check=False, diff=False, )
    69.         passwords = dict(sshpass=None, becomepass=None)
    70.         # create inventory and pass to var manager
    71.         inventory = InventoryManager(loader=loader, sources=sources)
    72.         variable_manager = VariableManager(loader=loader, inventory=inventory)
    73.         for host in self.hostinfo:
    74.             inventory.add_host(host=host.get('host'), port=host.get('port'))
    75.             hostname = inventory.get_host(hostname=host.get('host'))
    76.             variable_manager.set_host_variable(host=hostname, varname='ansible_ssh_pass', value=host.get('password'))
    77.             variable_manager.set_host_variable(host=hostname, varname='ansible_ssh_user', value=host.get('user'))
    78.             variable_manager.set_host_variable(host=hostname, varname='ansible_ssh_port', value=host.get('port'))
    79.             # print("设置全局管理变量 %s"%host.get('host'))
    80.         # create play with tasks
    81.         tasks = []
    82.         # print(self.taskinfo)
    83.         for task in self.taskinfo:
    84.             # tasks.append(dict(action=dict(module=task.get("module"), args=task.get("args"))))
    85.             play_source = dict(
    86.                 name="Ansible API Play",
    87.                 hosts=host_list,
    88.                 gather_facts='no',
    89.                 # tasks=[dict(action=dict(module='command', args=dict(cmd='/usr/bin/uptime')))]
    90.                 # tasks=[dict(action=dict(module='shell', args='/usr/sbin/ip a'))]
    91.                 tasks=[dict(action=dict(module=task.get("module"), args=task.get("args")))]
    92.                 # dict(action=dict(module='setup', args='')),
    93.                 #        dict(action=dict(module='setup', args=''),register='shell_out'),
    94.                 #        dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}')))
    95.             )
    96.             play = Play().load(play_source, variable_manager=variable_manager, loader=loader)
    97.             # actually run it
    98.             tqm = None
    99.             callback = ResultsCollector()
    100.             try:
    101.                 tqm = TaskQueueManager(
    102.                     inventory=inventory,
    103.                     variable_manager=variable_manager,
    104.                     loader=loader,
    105.                     options=options,
    106.                     passwords=passwords,
    107.                 )
    108.                 tqm._stdout_callback = callback
    109.                 result = tqm.run(play)
    110.             finally:
    111.                 if tqm is not None:
    112.                     tqm.cleanup()
    113.             # print("UP ***********")
    114.             # print(callback.host_ok.items())
    115.             for host, result in callback.host_ok.items():
    116.                 try:
    117.                     # print('{0} >>> {1}'.format(host, result._result['stdout']))
    118.                     self.resultinfo.append({host: {"message":result._result['stdout'],"code":0}})
    119.                 except:
    120.                     # print('{0} >>> {1}'.format(host, result._result['ansible_facts']))
    121.                     self.resultinfo.append({host: {"message":result._result['ansible_facts'],"code":0}})
    122.             # print("FAILED *******")
    123.             for host, result in callback.host_failed.items():
    124.                 # print('{0} >>> {1}'.format(host, result._result['msg']))
    125.                 self.resultinfo.append({host: {"message":result._result['msg'],"code":1}})
    126.             # print("DOWN *********")
    127.             for host, result in callback.host_unreachable.items():
    128.                 # print('{0} >>> {1}'.format(host, result._result['msg']))
    129.                 self.resultinfo.append({host: {"message":result._result['msg'],"code":-1}})
    130.         return self.resultinfo
    131. def Baserun(TaskInfos):
    132.     TaskInfos = {
    133.         "hostinfo": [
    134.             {
    135.                 "host""10.1.41.210",
    136.                 "port"65534,
    137.                 "user""root",
    138.                 "password""root"
    139.             },
    140.             {
    141.                 "host""10.1.41.220",
    142.                 "port"6553,
    143.                 "user""root",
    144.                 "password""root"
    145.             },
    146.         ],
    147.         "taskinfo": [
    148.             {
    149.                 "module""shell",
    150.                 "args""hostname"
    151.             },
    152.             {
    153.                 "module""command",
    154.                 "args""/usr/bin/uptime"
    155.             },
    156.         ]
    157.     }
    158.     ansibleapi = AnsibleApi(TaskInfos)
    159.     results = ansibleapi.run()
    160.     print(results)
    161. def getsysinfo(hostinfo):
    162.     TaskInfos = {
    163.         "hostinfo": [
    164.             {
    165.                 "host""10.1.41.210",
    166.                 "port"65534,
    167.                 "user""root",
    168.                 "password""root"
    169.             },
    170.             {
    171.                 "host""10.1.41.220",
    172.                 "port"6553,
    173.                 "user""root",
    174.                 "password""root"
    175.             },
    176.         ],
    177.         "taskinfo": [
    178.             {
    179.                 "module""setup",
    180.                 "args"""
    181.             },
    182.         ]
    183.     }
    184.     TaskInfos["hostinfo"]=hostinfo
    185.     # print(TaskInfos)
    186.     ansibleapi = AnsibleApi(TaskInfos)
    187.     result = ansibleapi.run()
    188.     resultinfo=[]
    189.     # print(result)
    190.     for res in result:
    191.         for k in res:
    192.             data = res[k]["message"]
    193.             code=res[k]["code"]
    194.             sysinfo = {}
    195.             disksize=0
    196.             if code !=0:
    197.                 resultinfo.append({k: res[k]})
    198.             else:
    199.                 for i in data["ansible_devices"]:
    200.                     if i[0:2in ("vd""ss""sd"):
    201.                         disksize=disksize+int(data["ansible_devices"][i]["sectors"]) * int(
    202.                             data["ansible_devices"][i]["sectorsize"]) / 1024 / 1024 / 1024
    203.                 sysinfo['disk'] = "{}".format(str(disksize) + str(" GB"))
    204.                 sysinfo['mem'] = round(data['ansible_memtotal_mb'] / 1024)
    205.                 sysinfo['cpu'] = "{} * {}".format(data['ansible_processor_count'] * data["ansible_processor_cores"],
    206.                                                   data['ansible_processor'][2])
    207.                 sysinfo['system'] = data['ansible_distribution'] + " " + data['ansible_distribution_version']
    208.                 resultinfo.append({k:{"message":sysinfo,"code":0}})
    209.     return resultinfo
    210. def execshell(hostinfo, shellcmd):
    211.     TaskInfos = {
    212.         "hostinfo": [
    213.             {
    214.                 "host""10.1.41.210",
    215.                 "port"65534,
    216.                 "user""root",
    217.                 "password""root"
    218.             },
    219.             {
    220.                 "host""10.1.41.220",
    221.                 "port"6553,
    222.                 "user""root",
    223.                 "password""root"
    224.             },
    225.         ],
    226.         "taskinfo": [
    227.             {
    228.                 "module""shell",
    229.                 "args"""
    230.             },
    231.         ]
    232.     }
    233.     TaskInfos["hostinfo"]=hostinfo
    234.     TaskInfos["taskinfo"][0]["args"] = shellcmd
    235.     ansibleapi = AnsibleApi(TaskInfos)
    236.     result = ansibleapi.run()
    237.     return result
    238. # data=getsysinfo([{"host": "10.1.41.220","port": 6553,"user": "root","password": "root"}])
    239. # print(data)
    240. # [{'10.1.41.220': {'disk': '30.0 GB', 'mem': 2, 'cpu': '4 * Intel(R) Core(TM) i7-7500U CPU @ 2.70GHz', 'system': 'CentOS 7.2.1511'}}]
    241. # data=execshell([{"host": "10.1.41.220","port": 6553,"user": "root","password": "root"}], "uptime")
    242. # print(data)
    243. # [{'10.1.41.220': ' 01:14:30 up  2:24,  2 users,  load average: 0.01, 0.02, 0.05'}]

    二,通过ansible-api 来添加免密认证

    1. #!/usr/bin/env python
    2. # -*- coding:utf-8 -*-
    3. # author : liuyu
    4. # date : 2018/8/6 0006
    5. from collections import namedtuple
    6. from subprocess import Popen, PIPE
    7. import re
    8. from ansible.executor.task_queue_manager import TaskQueueManager
    9. from ansible.inventory.manager import InventoryManager
    10. from ansible.parsing.dataloader import DataLoader
    11. from ansible.playbook.play import Play
    12. from ansible.plugins.callback import CallbackBase
    13. from ansible.vars.manager import VariableManager
    14. import ansible.constants as C
    15. C.HOST_KEY_CHECKING = False
    16. def default_taskinfos():
    17.     TaskInfos = {
    18.         "hostinfo": [
    19.             {
    20.                 "host""0.0.0.0",
    21.                 "port"22,
    22.                 "user""root",
    23.                 "password""root"
    24.             },
    25.         ],
    26.         "taskinfo": [
    27.             {
    28.                 "module""setup",
    29.                 "args"""
    30.             },
    31.         ]
    32.     }
    33.     return TaskInfos
    34. # Create a callback object so we can capture the output
    35. class ResultsCollector(CallbackBase):
    36.     def __init__(self, *args, **kwargs):
    37.         super(ResultsCollector, self).__init__(*args, **kwargs)
    38.         self.host_ok = {}
    39.         self.host_unreachable = {}
    40.         self.host_failed = {}
    41.     def v2_runner_on_unreachable(self, result):
    42.         self.host_unreachable[result._host.get_name()] = result
    43.     def v2_runner_on_ok(self, result, *args, **kwargs):
    44.         self.host_ok[result._host.get_name()] = result
    45.     def v2_runner_on_failed(self, result, *args, **kwargs):
    46.         self.host_failed[result._host.get_name()] = result
    47. class AnsibleApi(object):
    48.     def __init__(self, TaskInfos):
    49.         self.taskinfo = TaskInfos.get('taskinfo', default_taskinfos()["taskinfo"])
    50.         self.hostinfo = TaskInfos.get('hostinfo', default_taskinfos()["hostinfo"])
    51.         self.resultinfo = []
    52.     def run(self):
    53.         host_list = []
    54.         [host_list.append(i.get("host"'0.0.0.0')) for i in self.hostinfo]
    55.         Options = namedtuple('Options', ['connection''module_path''forks''remote_user',
    56.                                          'private_key_file''ssh_common_args''ssh_extra_args''sftp_extra_args',
    57.                                          'scp_extra_args''become''become_method''become_user''verbosity',
    58.                                          'check',
    59.                                          'diff'])
    60.         # required for
    61.         # https://github.com/ansible/ansible/blob/devel/lib/ansible/inventory/manager.py#L204
    62.         sources = ','.join(host_list)
    63.         if len(host_list) == 1:
    64.             sources += ','
    65.         # initialize needed objects
    66.         loader = DataLoader()
    67.         options = Options(connection='smart', module_path=['/usr/share/ansible'], forks=100,
    68.                           remote_user=None, private_key_file=None, ssh_common_args=None, ssh_extra_args=None,
    69.                           sftp_extra_args=None, scp_extra_args=None, become=None, become_method=None,
    70.                           become_user=None, verbosity=None, check=False, diff=False, )
    71.         passwords = dict(sshpass=None, becomepass=None)
    72.         # create inventory and pass to var manager
    73.         inventory = InventoryManager(loader=loader, sources=sources)
    74.         variable_manager = VariableManager(loader=loader, inventory=inventory)
    75.         for host in self.hostinfo:
    76.             inventory.add_host(host=host.get('host'), port=host.get('port'))
    77.             hostname = inventory.get_host(hostname=host.get('host'))
    78.             variable_manager.set_host_variable(host=hostname, varname='ansible_ssh_pass', value=host.get('password'))
    79.             variable_manager.set_host_variable(host=hostname, varname='ansible_ssh_user', value=host.get('user'))
    80.             variable_manager.set_host_variable(host=hostname, varname='ansible_ssh_port', value=host.get('port'))
    81.             # print("设置全局管理变量 %s"%host.get('host'))
    82.         # create play with tasks
    83.         tasks = []
    84.         # print(self.taskinfo)
    85.         for task in self.taskinfo:
    86.             # tasks.append(dict(action=dict(module=task.get("module"), args=task.get("args"))))
    87.             play_source = dict(
    88.                 name="Ansible API Play",
    89.                 hosts=host_list,
    90.                 gather_facts='no',
    91.                 # tasks=[dict(action=dict(module='command', args=dict(cmd='/usr/bin/uptime')))]
    92.                 # tasks=[dict(action=dict(module='shell', args='/usr/sbin/ip a'))]
    93.                 tasks=[dict(action=dict(module=task.get("module"), args=task.get("args")))]
    94.                 # dict(action=dict(module='setup', args='')),
    95.                 #        dict(action=dict(module='setup', args=''),register='shell_out'),
    96.                 #        dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}')))
    97.             )
    98.             play = Play().load(play_source, variable_manager=variable_manager, loader=loader)
    99.             # actually run it
    100.             tqm = None
    101.             callback = ResultsCollector()
    102.             try:
    103.                 tqm = TaskQueueManager(
    104.                     inventory=inventory,
    105.                     variable_manager=variable_manager,
    106.                     loader=loader,
    107.                     options=options,
    108.                     passwords=passwords,
    109.                 )
    110.                 tqm._stdout_callback = callback
    111.                 result = tqm.run(play)
    112.             finally:
    113.                 if tqm is not None:
    114.                     tqm.cleanup()
    115.             # print("UP ***********")
    116.             # print(callback.host_ok.items())
    117.             for host, result in callback.host_ok.items():
    118.                 try:
    119.                     # print('{0} >>> {1}'.format(host, result._result['stdout']))
    120.                     self.resultinfo.append({host: {"message":result._result['stdout'],"code":0}})
    121.                 except:
    122.                     # print('{0} >>> {1}'.format(host, result._result['ansible_facts']))
    123.                     self.resultinfo.append({host: {"message":result._result['ansible_facts'],"code":0}})
    124.             # print("FAILED *******")
    125.             for host, result in callback.host_failed.items():
    126.                 # print('{0} >>> {1}'.format(host, result._result['msg']))
    127.                 self.resultinfo.append({host: {"message":result._result['msg'],"code":1}})
    128.             # print("DOWN *********")
    129.             for host, result in callback.host_unreachable.items():
    130.                 # print('{0} >>> {1}'.format(host, result._result['msg']))
    131.                 self.resultinfo.append({host: {"message":result._result['msg'],"code":-1}})
    132.         return self.resultinfo
    133. def execshell(hostinfo, shellcmd):
    134.     TaskInfos = {
    135.         "hostinfo": [
    136.             {
    137.                 "host""10.1.41.210",
    138.                 "port"65534,
    139.                 "user""root",
    140.                 "password""root"
    141.             },
    142.           
    143.         ],
    144.         "taskinfo": [
    145.             {
    146.                 "module""shell",
    147.                 "args"""
    148.             },
    149.         ]
    150.     }
    151.     TaskInfos["hostinfo"]=hostinfo
    152.     TaskInfos["taskinfo"][0]["args"] = shellcmd
    153.     ansibleapi = AnsibleApi(TaskInfos)
    154.     result = ansibleapi.run()
    155.     return result
    156. def setremotenopass(ip,port,username,password,fs):
    157.     #data=execshell([{"host": ip,"port": port,"user": username,"password": password}], "sed -i '/oldauthorized/d' /root/.ssh/authorized_keys")
    158.     data=execshell([{"host": ip,"port": port,"user": username,"password": password}], "echo {} >> /root/.ssh/authorized_keys".format(fs))
    159.     child = Popen(["ssh -o StrictHostKeyChecking=no %s 'hostname && ip a| grep global'"%(ip)],shell=True,stdout=PIPE)
    160.     out,err=child.communicate()
    161.     print(data,out)
    162. if __name__ == "__main__":
    163.     
    164.     
    165.     password="hostpassword"
    166.     port=15625
    167.     id_rsa_file="/root/.ssh/id_rsa.pub"
    168.     
    169.     hosts="./ip"
    170.     
    171.     with open(hosts,'r'as f:
    172.         lines=f.readlines()
    173.     with open(id_rsa_file,'r'as fpub:
    174.         fpubrsa=fpub.readlines()[0].strip('\n')
    175.     for i in lines:
    176.         result = re.findall(r"\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b", i)
    177.         if result:
    178.            for ip in result:
    179.                setremotenopass(ip,port,'root',password,fpubrsa)

  • 相关阅读:
    【编程DIY】一.几个有趣的小程序
    【双指针-简单】977. 有序数组的平方
    基于C++和C#窗体实现各种无损压缩算法并进行比较分析
    Docker 容器常见故障的排查处理
    如何避免远程访问欺诈?让远程办公更加安全的六个建议
    Seata四大模式之XA模式详解及代码实现
    IU酒店落子重庆,数山城美景
    chatgpt输出mysql常用语法汇总
    3D全景模型展示可视化技术演示
    有趣的statement stack
  • 原文地址:https://blog.csdn.net/ly1358152944/article/details/126436323